If a gameObject with Prefab identier is instantiated during runtime and has a script that keeps a reference to another gameObject, after loading, the reference is gone. Other things are kept, and it doesn’t matter if the reference is part of a custom class or whatever. As long as it’s a gameObject (and probably transform as well), it’s lost, but things like strings and ints are kept.
Does anyone have a solution?
There are a number of ways to solve the problem, take your pick from solutions I have used below.
Attach a script containing the following
GameObject myGameObject
Awake {
myGameObject = GameObject.Find("NameOfReference");
}
There are other ways to do this as well. If you are looking for a manager you can declare a static variable on the manager as follows. This only works for GameObject you plan to keep only a single instance of.
// On the manager
public class MyManager: MonoBehaviour {
public static GameObject myManager;
Awake {
myManager = this;
}
}
...
// On the prefab
GameObject manager;
Awake {
manager = MyManager.myManager;
}
Finally you can set the reference from the instantiating script. This works best if you need to set a different reference each time.
//On the calling object
myClone = Instantiate(// Instantiate paramaters);
myClone.publicReference = myGameObject;
this doesn’t work when you need references,
i made a game with different characters you can select and every time i instantiate a character aka gameObject i cant get access to my moblie ui controller or none of things attach to original prefab like my slider which i use for health you can’t access