- Home /
Accessing function from another class?
I have one script with the following:
class Weapon
{
function SpawnWeapon()
{
print("It Works!");
}
}
And another that tries to access the function:
var theWeaponScript : Weapon;
function Update ()
{
theWeaponScript.SpawnWeapon();
}
It doesn't give me an error, but it doesn't print out anything, either.
Also, I don't think this is related, but I have another class in the same script as the "Weapon" class. Unity gives me a warning that "The class defined in script file does not match the file name".
The file name is Weapon.js? Try to have the custom class another name than the file name. All js scripts are actually a class, so it may be some name conflict occurring.
Answer by fafase · Jul 22, 2012 at 09:46 PM
You declare theWeaponScript variable to be of type Weapon which is a class. You need to make it of the type script name.
Also, because the function is a member method (belongs to a class) it is called through an instance of an object of type Weapon.
Edit: I actually wonder what is the name of your script, would it be Weapon.js? In this case, that would be the reason you do not get any error. You have a conflict name between the class and the script. Best would be to change one and then access the script like:
var script:ScriptName;
function Start(){
script =GameObject.Find("ObjectName").GetComponent(ScriptName);}
function Update(){
script.instanceName.functionName();
}
While a valid solution in theory, it doesn't exactly fit what I want because there will be many weapons of the same name in the game, not having distinct names... I was following the theory from a Youtube tutorial and he didn't do what you did: https://www.youtube.com/watch?v=p8fiHeh$$anonymous$$ubs
Your answer
Follow this Question
Related Questions
Instantiate inside class function returns NullReference 1 Answer
The name `PurchaseManager' does not exist in the current context 0 Answers
Make inspector show changes of class variable value in function? 1 Answer
Not sure why my function isn't working right. 0 Answers
Extended class functions 0 Answers