access another script from another scene?

Hello

I want to access another script to read one of its variables.
The thing is, this script is sitting on a gameobject in another scene?

Is this possible and how?

For context: Its from my main menu i want to access a another script from a level 1 scene.

Thank you

1 Like

You can’t create cross scene references when editing scenes, but you can find the script in the scene.

So pretty much every method that finds objects except dragging and dropping them into a field on a MonoBehaviour works. You can GameObject.Find, you can Object.FindObjectOfType, you can have the script you’re looking for register itself to a static variable, or you can get the scene and iterate it’s rootGameObjects

1 Like

Just so i 100% understand this line here:
You can’t create cross scene references when editing scenes, but you can find the script in the scene.

You are saying that it can´t be done right`? As the script i want to access is not in current scene but next one…
Sorry for my noob questions…

Maybe conception of accessing this variable is actually wrong? Why dont you push a value instead of searching for it ? I don’t know why you’d want to do that specifically. Then you can set value before and just pass it through non destroyable object to push it into next scene.

Hmm…

Its a simple prototype i am working on.
What if the value i was searching for was stored as a playerprefs INT. Then i should be able to search for it everywhere rght?

PlayerPrefs has their own methods to get/set values from it:
GetFloat/SetFloat,
GetInt/SetInt,
GetString/SetString.
There is also a method to check is specific key already set - HasKey.

You access those like that :
string someVariable = PlayerPrefs.GetString(“NameOfThePref”, “AlternativeValueIfIt’sNotSet”);

You can 100% access a script across scenes during run time, and there is absolutely no need to use player prefs to do so.

First note that you don’t have ‘scripts’ at run time. You have game objects and their respective components, of which all instances of monobehaviour classes. What you’re looking for is a means to find a reference to, or send/read something to/from the specific instance you’re looking for. And there’s a few different coding patterns you can use to do so.

Singleton would probably be the most common one that people reach for, though probably isn’t always needed. I tend to use the publisher/subscriber pattern, as usually I just want one thing to tell something in another scene to kick something off, or send a bit of information to another scene.

A bit more context with what you’re trying to do would be helpful though.

2 Likes