Robert Robert - 1 month ago 6
C# Question

Accessing method in one script from another script

I have a pair of scripts I'm writing in C# in which one script calls a method from another script. However, I'm getting the following error:

Member 'PlayerActions.Attack()' cannot be accessed with an instance reference; qualify it with a type name instead


Here's where the method I want to call resides:

public class PlayerActions:MonoBehaviour{
public static void Attack(){
Debug.Log("Attacking");
}
}


Here's where I'm trying to call the method:

public class Combat:MonoBehaviour{
PlayerActions playerActions;
void Start(){
playerActions = GetComponent<PlayerActions>();
playerActions.Attack();
}
}


Both scripts are attached to the same Game Object.

Can anyone tell me how to fix the error I mentioned above and why I'm actually getting the error? I've always thought that you needed to reference the class you are trying to gain access to, but from what I'm understanding, this error is stating otherwise.

Answer

Remove the static modifier and your code will work!

public class PlayerActions:MonoBehaviour{
    public void Attack(){
        Debug.Log("Attacking");
    }
}
Comments