I’ve been having a lot of trouble with this. I’ve attached Script A to Object A in Scene A and I want to access Script A in Script B attached to Object B in Scene B. And yes, I’ve used DontDestroyOnLoad. It works, but I keep getting null errors because when I try to attach Script A to Script B in the inspector, Script A isn’t there. Note: Script A has Boolean values that I wish to be read by Script B.
I’m trying to make a game which involves choices and after you make a choice, you go to the next scene, but you can go back to the previous scene to change your choice. I want the choices to be saved somewhere, so at the end all the choices you picked will be displayed. Can someone help me out here? I know my question is a bit vague, but if someone can help me with my first problem then that would be helpful. I’ve heard a lot about PlayerPrefs, but it seems a little confusing. I’m not sure I want to go that route right now. I’d rather just stick with the Don’tDestroyOnLoad method for now if I can.
There are lots of ways to do this at runtime from your ‘Script B’ - by type, tag, name, etc. Take a look at;
// eg. inside ScriptB Awake() or Start()
ScriptA myScriptA = Object.FindObjectOfType<ScriptA>();
Debug.Log(myScriptA.someBoolean);
Note that usually you don’t want to do this every frame (in an Update method, for example). It’s best to get the reference once, save it, and reuse it rather than find it every frame/time you need it.
Or, you could (carefully) make ScriptA a singleton or set a basic static reference to itself that other scripts can use, but these are a bit more advanced and have a few things to be aware of when you use them, particularly when you’re loading and unloading scenes or using script execution orders.
Thanks for the response! How would I go about saving it though? Do I use player prefs (which I’m not familiar with) or is there something else I can do?
If you use ScriptA as you’ve suggested above using ‘DontDestroyOnLoad’ then it will exist for the lifetime of the app, unless you destroy it manually… so, ScriptA holding your choices will persist while you load/unload other scenes. Unless you want to save your choices so they’re available when you quit and run the app again there’s no need to save them.
If you do want to save the choices you could use PlayerPrefs (useful for small bits of data) or save a datafile (eg. save a file in the directory Application.persistentDataPath). You could read/write your own format or use something handy like JSON as there are libraries that help save and restore entire objects (classes, structs, etc) with a few lines of code. I’m using a fork of TinyJSON to do this right now.