Int value got from GetComponent returns null

Hello there, i have a code that updates itself by +1 every time an object gets destroyed which gets added to the score. Now i want to get this score and with every 1000 score i want to show an ad however when i get the score from the other class it returns null. Why is that happening?

public void Update() //i did defined adScore as int before this
    {
        adScore = GetComponent<GameManager>().adScore; //This returns null
        if (adScore % 1000 == 0)
        {
            if (Advertisement.IsReady())
            {
                Advertisement.Show();
            }
        }
    }

Are you sure you have a game manager attached to the same GameObject? If you do then I would instead have the game manager as a variable and reference it directly. You can drag and drop this in the inspector.

public GameManager gameManager;

private void Update()
{
    if(gameManager.adScore % 1000 ==)
    {
        // do stuff
    }
}

If the GameManager is not on the same object as this script then the problem is with how you are finding it. The code you wrote will look for a GameManager component within the game object your script is attached to. If this isn’t what you want then you either have to find the actual GameObject that has the game manager attached, or (what I would probably do for a game manager) is make it a singleton. Then, depending on your Singleton implementation, you can reference your GameManager like so:

adScore = GameManager.Instance.adScore;

nwm fixed it, changed the line with “adScore = GameObject.Find(“GameManager”).GetComponent().adScore;”
But thank you very much!

1 Like