1

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that does the job, i was overcomplicating things for myself with the collision portion of the question. to take it one step further, lets say i dont know what hits my object, so instead of <Bullet> is there a way to say <Whatever just hit my object>?
No, not really. You need to know what scripts you are looking for im afraid.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.