- Home /
Duplicate Question
How to call a function from another script.
Script A: I have one script, which is attached to the main camera and contains lots of GUI information.
Script B: I have another script which is attached to a prefab which gets instantiated many times throughout the game, But is not present at the beginning of the game, it get instantiated later by the user.
I need to call a function from script B in script A.
in Script B:
public function Test(){
print("it worked");
}
in Script A:
var ScriptB : ScriptB;
ScriptB.Test():
This gives me a NullReferenceException, "NullReferenceException: Object reference not set to an instance of an object"
Sounds like it would be checking for it before it exists. You're seeing this error during runtime right? I would put an extra check before ScriptB.Test(); to see if a prefab exists first.
I tried adding a variable in for an extra check and I got the same message. Also yes it is happening at runtime.
var testNum = 5;
public function Test(){
print("it worked");
}
var ScriptB : ScriptB;
print(ScriptB.testNum);
ScriptB.Test():
@Other$$anonymous$$ods Can you recall how may times this question has been asked before?
Here are the duplicate Questions I got from 1 google search:
http://answers.unity3d.com/questions/13248/how-to-call-a-function-from-another-script-getting.html
http://answers.unity3d.com/questions/7555/how-do-i-call-a-function-in-another-gameobjects-sc.html
http://forum.unity3d.com/threads/57072-Calling-function-from-other-scripts-c
http://answers.unity3d.com/questions/11206/call-a-function-in-a-different-script-using-javasc.html
http://answers.unity3d.com/questions/337750/why-cant-i-call-function-from-another-script.html
http://answers.unity3d.com/questions/261891/better-way-to-call-function-from-another-script-fr.html
http://answers.unity3d.com/questions/265270/call-function-in-another-script.html
http://answers.unity3d.com/questions/185288/calling-a-function-from-another-script.html
http://answers.unity3d.com/questions/200095/calling-functions-from-another-script-not-attached.html
http://answers.unity3d.com/questions/8770/accessing-functions-in-other-scripts.html
http://answers.unity3d.com/questions/197065/access-functions-in-another-script.html
http://answers.unity3d.com/questions/423161/calling-functions-from-another-script.html
http://answers.unity3d.com/questions/130931/calling-functions-from-any-script-.html
http://answers.unity3d.com/questions/393220/calling-function-from-other-scripts.html
http://answers.unity3d.com/questions/238794/simply-calling-a-method-from-another-script-.html
http://answers.unity3d.com/questions/128805/how-do-i-call-methods-from-other-scripts-using-c.html
How did you not find all these yoursefl? Why did you not do a google search? Why did you post this question?
they're also all over the suggested questions list, which pops up as you type your question and is on the right of the screen now where i can see it.