- Home /
how to call script of other scene to current.
hi all, i am doing a project in unity3d.i have one doubt,can it possible to call a script from other scene to current scene.if so,how it would be?......please let me know..anybody pls help..
If you want to carry script between scenes then make that script as static and add it to a game object and set that object to be DontDestroyOnLoad.
Otherwise answer is no. When a new scene is loaded, everything from the previous is destroyed (Except those DontDestroyOnLoad objects). So calling an instance method from previous scene would result in null reference exception.
A static method on the other hand is acting different, as it belongs to the class, you do not need instance to call it but it won't have access to any non static variable.
Answer by fafase · Nov 19, 2014 at 05:52 AM
Considering your latest comment, I would guess you are after what is called in a fancy way data persistence.
So there are different ways to do so.
DontDestroyOnLoad:
You add that method in a script and the object will survive reloading a scene
private string myString;
public string MyString{get{return myString;}}
void Start()
{
DontDestroyOnLoad(gameObject);
}
then any other script can take care of it:
void Start(){
// find the object and get the script
string str = script.MyString;
Destroy(theObject);
}
Once you got your value you should get rid of the object if you do not need it since it will remain else just keep it.
PlayerPrefs:
Second way is to store the value in memory:
string myString;
void OnDestroy()
{
PlayerPrefs.SetString("Data", myString);
}
in the other script:
void Start()
{
string str = PlayerPrefs.GetString("Data");
}
Static:
The latest is to use some static value:
static class Data{
public static string MyString{get;set;}
}
Now here is the script containing the value:
private string myString;
void OnDestroy(){
Data.MyString = myString;
}
and in the other script:
void Start(){
string str = Data.MyString;
}
well,thats something useful fafase :))...........i think it may work out..tnx a lot ....
$$anonymous$$ark the answer as Accepted if it does the trick for you :)
Answer by nketc · Nov 18, 2014 at 03:20 PM
Go to the add component in inspector window, click scripts, and add any script that exist in your project. Either you are using it on any other scene or object.
tnx a lot nketc...........:)...but the thing is...i have some objects in hierarchy to drag to appropriate position in script wchich coudnt be available in my current scene.....so how could it possible....i want to call string from the other script to my current script....can it possible through any way.
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Gradually reduce speed 1 Answer
Move Towards Target Color 2 Answers
How can I make the score counter use the custom font? 1 Answer
How do we instantiate random sprites from an array... 1 Answer