About refferencing other scripts

Hello everyone.

I’ve been looking at some examples of C# in unity, and in some of them I see people refferencing to other scripts like this:

public Static ScriptName Instance;
public string randomString = "potatoes";

void Awake () {
   Instance = this;
}

And then, on another script

someOtherRandomString = ScriptName.Instance.randomString;

Then the variable someOtherRandomString’s value would be “potatoes” as well, so we are refferencing to another script, by creating a variable which holds an actual instance to the first script.

I find this way to be way more clean and easy than using the refferencing through the inspector (because we don’t always want the user to be able to configure those refferences from the inspector view), but I wanted to ask: Is this more CPU consuming than the other methods described in the documentation? Is there any way to do this in javaScript (I’m assuming there’s one, just don’t know it). And lastly I wanted to ask: why isn’t this method described in the unity documentation (correct me if i’m wrong but i didn’t see it the last time I checked)

And also, I would like to ask: If I use this method, I’m assuming there’s only one Instance of that script’s class running at the same time. Otherwise the variable Instance would hold two instances of the class at the same time, which can’t be as far as I know. Am I right?

Thank you

So that is a singleton pattern and is useful when you will only need to access the one current instance of another class.

The reason to do this rather than just have a totally static class is that you can set the variables on the Instance using the inspector but stil access them from elsewhere without needing to drag a reference.

You may also see script that looks like this:

 public static List<ScriptName> scriptNames = new List<ScriptName>();

 void Awake() {
      scriptNames.Add(this);

 }

 void OnDestroy() {
      scriptNames.Remove(this);
}

This code lets you quickly get all of the instances of the script currently alive in a foreach loop like this (in some other class)

 foreach(var s in ScriptName.scriptNames)
 {
 }

That is MUCH faster than using Find and GetComponent to get all of them.

in java it would be:

script1.js:

.....
static var somevariable = 1;
.....

script2.js:

.....
anothervariable = script1.somevariable; 
.....

then the value of anothervariable would be 1.