Search code examples
c#unity-game-engineunityscript

Unable to call public static method in other unity script


I have a two an "enemy" sprite that when the "player" sprite touches, should cause damage.

The PlayerStatus script just holds information about the players health. When the EnemyAIController OnTriggerEnter2D method is fired, I wanted to call a method in the PlayerStatus script that would reduce the health by x amount.

I made the TakeDamage method accessor public with a static modifier. So I could call PlayerStatus.TakeDamage(float x), but that doesn't work.

I get the error: An object reference is required to access non-static member `PlayerStatus.TakeDamage(float)'

I didn't want to use findObjectByTag because I have read that is slow and a lazy way of doing it.

Am I missing something?

PlayerStatus Script:

public class PlayerStatus : MonoBehaviour {

    public float health = 3.0f;

    public static void TakeDamage(float damage){
        health -= damage;

    }

}

EnemyAIController Script:

public class EnemyAIController : MonoBehaviour {

    void OnTriggerEnter2D(Collider2D other) {

            Debug.Log("Reduce Player Health"); 
            PlayerStatus.TakeDamage (1.0f);

    }

}

Solution

  • The problem is within class PlayerStatus. Inside static method TakeDamage you are accessing non-static variable health which of course can not be done.

    public static float health = 3.0f; // inside class PlayerStatus
    

    Should help you resolve the error.

    Otherwise, I'd recommend that you create a non static method TakeDamage, use findObjectByTag, and you can do it once in constructor (to avoid performance penalty). Simply save the result in class property, where you access it inside `OnTriggerEnter2D:

    (more of a pseudo code)

    public class EnemyAIController : MonoBehaviour {
    
        private PlayerStatus _player;
    
        public EnemyAIController() {
            // call base() if neccessery
            _player = findObjectByTag("your player");
        }
    
        void OnTriggerEnter2D(Collider2D other) {
    
                Debug.Log("Reduce Player Health"); 
                this._player.TakeDamage (1.0f);
    
        }
    
    }