- Home /
Assigning a GameObject Script Variable Before Start is Called
I have a non-monobehaviour class named Tile that instantiates a gameObject from a prefab in its constructor, and the instantiated gameObject needs to know about the existence of the specific Tile ideally before Start is run. In order to achieve this, I have made a monobehaviour class TileRef that has a reference to a tile as a public variable, and I placed it on the prefab. How can I make sure there is a reference in the TileRef.Tile variable before Start runs, or are there better/cleaner ways of implementing this? I should also mention that I have tried both setting the variable in the prefab and setting the prefab to disabled before instantiating it, neither of which seemed to work( I found this solution in another pretty old Ask Unity post).
something like this for example?
Instantiate(prefab).GetComponent<$$anonymous$$yPrefabClass>().Tile = this;
public class $$anonymous$$yPrefabClass
{
Tile tileRef;
}
The problem is that I still need to store the instantiated gameObject in a variable because I need it further down after instantiating it, so this method won't work.
why it wont work? just store it.
GameObject yourObject = Instantiate(prefab);
yourObject.GetComponent<$$anonymous$$yPrefabClass>().Tile = this;
Answer by bpaynom · Mar 06, 2019 at 01:39 PM
yourPrefab.gameObject.SetActive(false);
GameObject go = Instantiate( yourPrefab );
// do stuff
// The Start() callback now knows all you did before.
go.SetActive ( true );
yourPrefab.gameObject.SetActive( true );