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?
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.
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.
fyi, I believe you could also do a yield in a coroutine for WaitForEndOfFrame and that would be sufficient (time), also.
If the 1 second is not bothering you, though, doesn’t matter.
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