An object reference is required to access non-static member
hello all, im trying to make a health system for my game, te players runs with this script:
public int maxHealth;
public int currentHealth;
void Start ()
{
currentHealth = maxHealth;
}
public void TakeDamage (int amount)
{
currentHealth -= amount;
}
and i have a lazer prefab, with a script that handles the colision with the players and calls for the "take damage function"
public int baseDamage;
GameObject player;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
}
void OnTriggerEnter (Collider other)
{
if (other.gameObject == player)
{
HealthSystem.TakeDamage (baseDamage);
}
}
}
i tryied to make it static, but it didn't help.
thanks in advance
Answer by UnityCoach · Jul 10, 2017 at 02:29 AM
From what I understand, you want to reference the player's HealthSystem component.
Try this :
public int baseDamage;
GameObject player;
HealthSystem healthSystem;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
healthSystem = player.GetComponent<HealthSystem>();
}
void OnTriggerEnter (Collider other)
{
if (other.gameObject == player)
{
healthSystem.TakeDamage (baseDamage);
}
}
}
Answer by Elprofeta · Jul 10, 2017 at 07:09 PM
i tryied that and didnt work, anyway after some more changes i finally make it work:
public int baseDamage;
GameObject disparo;
void OnTriggerEnter (Collider other)
{
if (other.tag == "Player")
{
HealthSystem healthRef = other.GetComponent<HealthSystem> ();
healthRef.TakeDamage (baseDamage);
Destroy (gameObject);
}
}
thank you @UnityCoach for pointing me in the right direction, that was really helpful.
It makes even more sense this way. If you remove the tag check, and simply check for healthRef != null ins$$anonymous$$d, you end up with something very generic that applies damage to anything that can take some.