0
votes

I have a canvas prefab called ScoreMenu which I instantiate programmatically.

GameObject scoreMenu = (GameObject)Instantiate(Resources.Load("Prefabs/Menus/ScoreMenu"));

In my canvas I have several text fields and buttons. I'm having trouble referencing those text fields so I can change the contents of it. My canvas has a script with a public score variable of type Text. Which I'm able to reference if it's of type ScoreMenu. But the instantiated object is of type GameObject. So I'm far unable to successfully cast it to another type so I can do things like scoreMenu.score.text = "203"; I keep getting nullreference errors or casting error. What is the proper way to reference child objects of a canvas prefab?

UPDATE II:

I've narrowed down the problem.

    GameObject scores = Instantiate(Resources.Load("Prefabs/Menus/ScoreMenu")) as GameObject; 
    ScoreMenu scoresMenu = scores.GetComponent<ScoreMenu>();    

This seems to be the correct way to instantiate and reference the prefab. However the problem lies within the variables inside my prefab class. Within my class I can reference and change the Textobject. But when I try to do this outside the class I get a nullreference error.

public class ScoreMenu : MonoBehaviour {

    public Text numStrokes;


    void OnAwake () {


    }

    void Start () {
        numStrokes = GameObject.Find("Strokes").GetComponent<Text>();
        numStrokes.text = "0000"; // this works
    }

    public void test () {

        print (numStrokes.text); // when calling this method from outside the class I get nullreference error

    }
1

1 Answers

0
votes

Found it, I think. I had to drag the texfield object from the hierarchy to the public variable field in the inspector.

enter image description here