- Home /
Keeping reference after scene reload
I am making a simple Pong game on IPhone. I have made a Singleton GameManager, which keeps references to the Score text, Game over panel and the ball. Whenever I reload my scene, all of those references are missing. How do I keep those gameobject references after reload?
Answer by efeguclu · Jul 04, 2017 at 01:51 PM
private void Start(){
DontDestroyOnLoad(gameObject);
}
// or JS
private function Start(){
DontDestroyOnLoad(gameObject);
}
or that may be better..
private bool IsDontDestroy=false;
private void Start(){
IsDontDestroy = true;
}
private void OnLevelWasLoaded(int level){
if(!IsDontDestroy)
Destroy(gameObject);
}
private void DisableDontDestroy(){
IsDontDestroy = false;
}
or JS
private var IsDontDestroy=false;
private function Start(){
IsDontDestroy = true;
}
private function OnLevelWasLoaded(var level){
if(!IsDontDestroy)
Destroy(gameObject);
}
private function DisableDontDestroy(){
IsDontDestroy = false;
}
Answer by PijusVose · Jul 04, 2017 at 02:59 PM
What if I want those objects become destroyable after load? How do I Undo DontDestroyOnLoad?
DontDestroyOnLoad does exactly what it says it does. It won't destroy the object when a new scene is loaded. Doesn't make it undestructable programmatically
But when the object is on DontdestroyOnLoad, it is not in the scene, but in the Dont Destroy On Load in the Hierachy. How do I put it back into my Scene in the hierarchy?
if it is UI object use the OnLevelWasLoaded Code that I gave and Add these lines
gameObject.transform.SetParent(GameObject.Find("Canvas").transform);