Help with Accessing a Variable on Text Object

I need to access an integer variable in Another Script called Points.

Canvas2 -> Text -> TextScipt -> Points

I have tried several ways but I can’t seem to make it work.

Line 40 seems to work but gives an NRE
Lines 41/42 seem to work setting Points,
Line 43 Errors and stops execution

Here is TextScript which is attached to Canvas2.Text.TextScript

Points always comes out zero. line 13 works but it throws an error.

Any help would be appreciated.

Retro, the problem is that you are trying to access a object before it even exists, Canvas2 will only exist after you instantiate it. And since you are instantiating it as GameObject you are able to change the variables and etc, otherwise you wouldn’t be able to do that, since it’s a prefab and it would be trying to clone the info that resides within the original prefab (points = 0). Since you are instantiating it as gameobject and giving a name to it (scoreText in this case), you should be using this name that you gave to access this instance of the prefab.

The text is inside a gameobject which is inside the Canvas Gameobject, so you have to access scoreText’s child, you could access it using the child name with scoreText.transform.Find(“Text”).gameObject, or using the index:

scoreText.transform.GetChild(0).gameObject.GetComponent<TextScript>().Points;
// scoreText = instance of the Canvas2 Prefab being instantiated by this event;
// .transform.GetChild(0).gameObject = accessing the Text GameObject inside this instance of the Canvas2;
// .GetComponent<TextScript>().Points = the integer inside the Text's script inside this instance of the Canvas2;

if you add this code between line 45 and line 46 it will probably work as you intended to, you should delete lines 39~43;

Am I getting the right idea, because its not working.

You got the right Idea Retro, I’ve said the wrong syntax, sorry

we are already accessing the gameobject by .transfom.GetChild(0), so we don’t need to use .GetChild(0).gameObject. Instead we should use it straight:

scoreText.transform.GetChild(0).GetComponent<TextScript>().Points;

Did it worked @RetroDan?

Line 41 still gives an NRE Error:

I’m using the same code syntax in my game and in the same kind of context, are you initializing Canvas2 as public GameObject instead of Canvas? Mine has been initialized as GameObject and it is working just fine.

Thanks a million @Joao_Dalvi , I have it working!

The problem was in the Canvas2 Prefab which was still treating Csnvas2 as a Canvas instead of GameObject; it needed to be updated. :blush:

1 Like

I’m glad that it helped =) let me know if I can be of further help, I learn a lot trying to help solve those problems too :grinning:

1 Like