Search code examples
c#unity-game-enginegameobject

Unity Changing the Text of an object in another script/scene


Basically, I have this Text (scoreText) which is in my "Menu" scene so hence I have initiated it in GameControlMenu.cs, however, I'm trying to change its text from my other script GameControl.cs whilst I'm currently on my "Main" scene.

GameControlMenu.cs:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class GameControlMenu : MonoBehaviour
{

public static GameControlMenu instanceMenu;

public Text scoreText;

void Start()
{
    //does stuff but not important to question
}
}

GameControl.cs:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

public class GameControl : MonoBehaviour
{
public static GameControl instance;

public int score = 5;

void Start()
{   
    GameControlMenu.instanceMenu.scoreText.text = "PREVIOUS SCORE: " + score;
}
}

This setup works for a couple of my other variables which I'm accessing from another file but for whatever reason this just keeps throwing me the error: NullReferenceException: Object reference not set to an instance of an object

Any help is appreciated :)


Solution

  • You can't do GameControlMenu.instanceMenu... since GameControlMenu is in another scene as you described, and the instance isn't in the current scene.

    But what you can do is to store the value somewhere first, and let the GameControlMenu use it when the other scene loads like so:

    GameControlMenu.cs

    public class GameControlMenu : MonoBehaviour
    {
    
        public static GameControlMenu instanceMenu;
    
        public static string StuffToShowOnScoreText { get; set; }
    
        public Text scoreText;
    
        void Awake()
        {
            // So that it loads the text on start
            scoreText.text = StuffToShowOnScoreText;
            // ...
        }
    }
    

    GameControl.cs

    public class GameControl : MonoBehaviour
    {
        public static GameControl instance;
    
        public int score = 5;
    
        void Start()
        {   
            // Store the value 
            GameControlMenu.StuffToShowOnScoreText = "PREVIOUS SCORE: " + score;
        }
    }