Zoey S
Zoey S

Reputation: 35

get variable from object collided with

I am trying to reduce the health of an enemy hit with a bullet. the bullets have different damage values, and those are stored within the 'bullet' script, while the enemy health is stored in the 'enemy' script. so i'm basically trying to get the damage value from the 'bullet' script on the bullet that currently hit the enemy.

void OnTriggerEnter2D(Collider2D collision) {
    if (collision.tag == "bullet") {
        healthCur -= 50f; // trying to reduce health by bullet damage instead of fixed 50hp

        if (healthCur <= 0) {
            Die();
        }
    }
}

i have seen similar questions on that matter but haven't been able to get a working solution, so if this is a duplicate it would be nice to get a little more information apart from a a duplicate link.

thanks.

Upvotes: 1

Views: 596

Answers (1)

Fredrik Widerberg
Fredrik Widerberg

Reputation: 3108

Assuming that the bullet class is called Bullet and that it has a field Damage

void OnTriggerEnter2D(Collider2D collision) {
    if (collision.tag == "bullet") {
        healthCur -= collision.gameObject.GetComponent<Bullet>().Damage;

        if (healthCur <= 0) {
            Die();
        }
    }
}

https://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html

Upvotes: 2

Related Questions