- Home /
calling functions from any script ?
I'm having trouble calling a function from any script I want. It seems like everything in the script that's going to be called must be set to a static. I'm very confused I cant just call a function from a different script and then have it call another function inside of that other script. Any easy way of doing this ?
Answer by Eric5h5 · Jun 16, 2011 at 04:46 PM
Nothing has to be set to static, and shouldn't be unless that's what you actually want (which it frequently isn't). See the docs about accessing other game objects.
I keep getting a nullReferenceException when I try accessing my function through the first code on the page.
That means you're trying to refer to an object which doesn't exist.
nvm needed to use GameObject.Find("$$anonymous$$ain Camera") and now it works great !
Answer by testure · Jun 16, 2011 at 04:34 PM
OtherScriptClass otherscript = transform.GetComponent<OtherScriptClass>();
otherscript.FunctionToCall();
easy as that.. though in order for it to work, you need OtherScriptClass assigned to the gameObject as a component.
Now, since you didn't say what language you're using I'm going to assume that you use what I use (C#). If you're using Javascript or Boo, then consult the unity refs and figure out how to make it work with your language (it's pretty easy).
You mentioned making something static- that's only for something that is not going to change during runtime (hence static). You can assign a script reference to a static variable and make it accessable to any script at any time- but it's only useful for things that are singular in nature (such as a camera controller, or gamestate manager, something like that).
In those cases, yes- you would use the static keyword and make it a publicly accessable member variable like this:
class MyClass : MonoBehaviour
{
public static MyClass Instance;
void Awake()
{
Instance = this; // you can now call MyClass.Instance.Function() from anywhere in any script
}
public void Function()
{
Debug.Log("Hey, it works");
}
}
Your answer
Follow this Question
Related Questions
Referencing functions from other scripts as variables 4 Answers
JavaScript - Reset Characters Position 2 Answers
Finding all public functions on a game object 1 Answer
Can't use GetComponent (Calling JS in C#), and don't know why 1 Answer
Calling function found on hundreds objects(best way?) 1 Answer