When I click on the button, I want to set some values to a gameobject in another scene and then load that scene. I tried using Gameobject.Find, but it returns NullReferenceException. I tried using DontDestroyOnLoad before loading to second scene, but it still doesn’t find it.
You can’t Find GameObjects which don’t exist in the hierarchy, and objects in not yet loaded scenes aren’t in the hierarchy yet. There are a few typical approaches:
- Load the new scene additively, then Find the GameObject as you are already trying (using a tag instead of the GameObject’s name is a slightly better approach by the way)
- Use a GameObject with DontDestroyOnLoad set, then load the new scene. When the new scene loads have the GameObject you want to set the values on find this DontDestroyOnLoad object and get its initialization values from it.
- Pass the values in static variables, which aren’t affected by scene loads and aren’t associated with GameObjects anyways.
Google for DontDestroyOnLoad, additive scene loading, and static variables for more information on each topic.
I guess that the problem is that this object is a child of two other objects, but if I use dontdestroyonload then the whole scene stays the same.
+1 for use DontDestroyOnLoad, if you have GameObjects which you need to reference from a different scene, they probably are a Utility or a StateManager in both cases you want the object to be persistent.
DontDestroyOnLoad - simply means that when you switch scenes said object won’t be deleted and maintain the data it holds (meaning no re-initialization as well).
Hope this helps