error CS0120: An object reference is required to access non-static member `UnityEngine.Collision.ga

Hey guys im kinda new to this but my code wont work, its should collide with “Bullet” and take away health, please help?

using UnityEngine;
using System.Collections;

public class EnemyHealth : MonoBehaviour {
public int maxHealth = 100;
public int currentHealth = 100;

public float healthbarlength;

// Use this for initialization
void Start () {
healthbarlength = Screen.width / 2;

}

// Update is called once per frame
void Update () {
AddjustCurrentHealth (0);
}

public void AddjustCurrentHealth(int adj) {
currentHealth += adj;
if (currentHealth < 1)
currentHealth = 0;

if(currentHealth > maxHealth)
currentHealth = maxHealth;

if(maxHealth <1)
maxHealth = 1;

if ( Collision.gameObject.tag == “Bullet” );
currentHealth = -10;
}

}

Thanks for any help :slight_smile:

Please use code tags:

You can’t just say if (Collision.gameObject.tag == “Bullet”) like that because it doesn’t know which collision you’re talking about. You need a specific instance of a collision.

So you would need to write this method:

void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.tag == "Bullet")
        currentHealth = -10;
}

That method will be called by Unity when a collision occurs, and will pass in the instance of the collision for you to work with.

1 Like
using UnityEngine;
using System.Collections;

public class EnemyHealth : MonoBehaviour {
    public int maxHealth = 100;
    public int currentHealth = 100;
   
    public float healthbarlength;
   
    // Use this for initialization
    void Start () {
        healthbarlength = Screen.width / 2;
       
    }
   
    // Update is called once per frame
    void Update () {
        AddjustCurrentHealth  (0);
    }

    public void AddjustCurrentHealth(int adj) {
        currentHealth += adj;
        if (currentHealth < 1)
            currentHealth = 0;
       
        if(currentHealth > maxHealth)
            currentHealth = maxHealth;
       
        if(maxHealth <1)
            maxHealth = 1;

        if ( Collision.gameObject.tag == "Bullet" );
        currentHealth = -10;
    }
       
        }

Thats it! Thank you! Very much appreciated.