- Home /
Find object from another scene
I need to find object from another scene ,I checked both Find and FindWithTag and both of them give me this error: NullReferenceException: Object reference not set to an instance of an object. What can I do?
Answer by Cornelis-de-Jager · Feb 03, 2019 at 09:13 PM
Its hard to say what a solution can be as we don't exactly know why you want the other object. But here are some solutions I use for working across scenes.
Using the Resource folder to store prefabs. In Unity you can have a folder called resources which is basically a collection of whatever you like (prefabs, materials, particle effects etc.) that you can access when your game is running, as appose to other assets that aren't available at run time. What I propose is that you find the object as a prefab/GameObject when you need it. Simple use the code below:
var myPrefab = Resources.Load<GameObject>("MyPrefab");
You can then Instantiate it and use it as you like. Here is how to use the Resource folder in detail. Click Here
Using a permanent object that doesn't despwan between scenes. If the object you want is a GameManager or a Spawn area or something that is consistent between scenes you can use the following code to prevent it from being thrown out on scene changes.
void Await () { DontDestroyOnLoad(this.gameObject); }
This way you can instantiate the object at the start scene and keep it as a child of the permanent object above.
See Doco Here
Sorry for using red text code but normal doesn't seem to want to play nice today.
Your answer
Follow this Question
Related Questions
How Expensive is Find function? 3 Answers
Is FindGameObjectWithTag deprecate? 1 Answer
GameObject.findGameObjectsWithTag returning empty? 1 Answer