- Home /
access a gameobject from another scene at design-time
I'll try to describe my problem as clear as possible.
I have a baseclass that references other monobehaviour scripts attached to a gameobject in my scene. If I use dontdestroyonload() I can still access that gameobject from my other scenes at run-time since it's not destroyed upon scene loading.
But at design-time I'd like to be able to playtest my scenes separately, obviously I get a null-reference exception since the gamobject don't exist in that scene. I guess I could simply add the same gameobject to each and every of my scenes, and then remove all, but one before run-time.
My question is if there are another way of doing this? like a dontdestroyonload() but for design-time?
Best regards!
Answer by Joe-Censored · Mar 29, 2017 at 05:21 PM
For testing like this I would have a script in each scene check for the object when the scene loads, if the object isn't there you instantiate it. So in normal usage the scene uses the existing object from the previous scene, but when play testing the scene the object is there also.
Answer by Mentoliptus · Apr 01, 2017 at 08:11 AM
Make the object a singleton and have one instance in every scene, but destroy the other instances at runtime in the Awake methods. Something like this:
public class MyBehaviour : MonoBehaviour
{
private static MyBehaviour _instance = null;
public static MyBehaviour Instance
{
get
{
if (_instance == null)
{
_instance = (new GameObject("MyBehaviour")).AddComponent<MyBehaviour>();
}
return _instance;
}
}
void Awake()
{
if (_instance == null)
{
_instance = this;
DontDestroyOnLoad(this);
// perform initialization
}
else
{
// singleton implementation that ensures only one instance in scene
if (FindObjectsOfType(typeof(MyBehaviour)).Length > 1)
{
DestroyImmediate(gameObject);
}
}
}
}
This way you can start the game from every scene and have the object there.
Your answer
Follow this Question
Related Questions
Unity 2d select 2 object on another 2 scenes 2 Answers
Gameobject dependencies 0 Answers
My music duplicates and gives an error 1 Answer
How to link words from different scene 1 Answer
Confusion about DontDestroyOnLoad and very large scenes... 1 Answer