Unable to access public string of my class

I have a GameObject used as a prefab and it has this code attached:

public class PrefabScript : MonoBehaviour {

    public string prefabText;

    void Start () {
       
       // do stuff here on instantiation to populate prefabText

        // but for now...
        prefabText = "any old random text just to test!";
    }
}

The prefab has a tag of MyPrefab and when I want to grab the text from prefabText once it has been instantiated I do this:

public void GrabText() {

        GameObject go = GameObject.FindGameObjectWithTag ("MyPrefab");

        PrefabScript ps = go.GetComponent<PrefabScript> ();

        if (ps != null) {
           
            print( ps.prefabText);
        }
    }

But I always get nothing printed?

In the hierarchy I check the instantiated prefab and its prefabText field has text set yet when I try to access it I gat nothing but an empty string?

Che?

Edited after grizzly post…

print(ps.prefabText);

:slight_smile:

sorry my bad in posting, yes I have ps.prefabText in the code, I just typed it wrong here! Sorry, so I still get empty string :frowning:

Do you instantiate and then try to grab the string immediately?
If that’s the case, then the Start() method has not yet run. You would need to move the string assignment to Awake() or you would have to delay the method that gets the string.

1 Like

Ah, thanks! I will have a change around re the sequence and see if you are right :slight_smile:

Cool :slight_smile:

Why thank you! :):):):):slight_smile:

Turns out it was a timing thing as you suggested, I would never have figured that out! All I had to do was place a 1 second delay before I accessed the string and bingo.

Been on this for two whole days!!!

Thanks :slight_smile:

Cool, glad I could help ya sort it out :slight_smile:

fyi, I believe you could also do a yield in a coroutine for WaitForEndOfFrame and that would be sufficient (time), also. :slight_smile:
If the 1 second is not bothering you, though, doesn’t matter.

1 Like

It actually looks like I don’t even need to do that! I was trying to access the text way too early. After revisiting the logic I can lose the delay, but this was an interesting issue, one I had not come across before re that timings involved re start, awake and accessing etc so will prove very useful knowledge to now have. Thank you :slight_smile:

Cool :slight_smile: That’s good stuff to know. Take it easy, and enjoy your game :slight_smile:

1 Like

Glad to hear it’s sorted! It’s worth mentioning that Unity does provide some control over execution order. You can find this here: https://docs.unity3d.com/Manual/class-MonoManager.html

1 Like

Awesome :slight_smile: