0
votes

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);

    }

}
1
Jaka has explained your problem. But remember -- it is an awfully good idea to have STATIC CLASSES and only write static calls inside that static class. Something to consider.Fattie
WHAT YOU ARE DOING IS EXTREMELY DANGEROUS Don't forget PlayerStatus is a MonoBehavior. *WHAT IS IT ATTACHED TO? What happens if you have more than one PlayerStatus script in your game?Fattie
Yikes. Anywhere specific I can read up on this?user-44651
Thanks for the ominous warning and then leaving without further explanation @JoeBlowuser-44651
i already typed "What happens if you have more than one PlayerStatus script in your game?" it's almost meaningless, and at any rate poorly defined, to use static methods in an ECS milieu. for something like "health" and "scoring" (basically "globals") in a game engine, just use static class (with of course static methods)Fattie

1 Answers

4
votes

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);

    }

}