Referencing a script?

I’m sure I’ve asked this type of question before, but I don’t think it was ever specifically about referencing to a script.

Basically, I have a prefab with a script, and I need to refer to that script’s variables for calculations and stuff for the script I’m working on.

I know the general idea of “GameObject.Find”, “GetComponent” and stuff like that. But I don’t think I’ve ever tried referencing another script directly. One time I somehow got away with just referencing the object, and then I was able to refer to its components’ variables. But I don’t remember anything about how I did it, or where (in which of my many scripts).

Here’s a simple explanation, because I tend to go off track:

Both scripts are on the same prefab.
I want one script to refer to the other, so I can use its variables.

ScriptName variableName = GetComponent();
// use variableName as your reference.

That’s the way :slight_smile:

If you use the script reference to carry out operations over time, a good tip is to create the variable outside of any methods, look it up (store it) in Start() and use it whenever you need it :slight_smile:

2 Likes
public OtherScriptName other;

If you put that in your script, it’ll create a ‘slot’ in that script’s inspector. You can then drag an object into that slot if it contains that other script.

Let’s not make the mistake of thinking that GameObject.Find is okay, though. (GetComponent is good; Find is not) That article has a bunch of ways to get references to other objects/components without using GameObject.Find.

2 Likes

Yeah, don’t forget you can just drag it in there, too. :slight_smile:

1 Like

Thanks guys, that worked. :slight_smile:

Cool :slight_smile:

1 Like