Hello!
I am still quite new to programming with Unity - or programing at all.
I have the following problem:
For a little game i make i want to have a bullet and enemys. Enemys have HP and the bullet has an amount of DMG. Now i want to access the enemy`s life from my bullet script.
Pseudocode should look like:
OnCollisionEnter2D()
{
if (hit is an enemy)
enemy.life -= DMG
Destroy(gameobject)
}
so what i want to do is to access the enemys life from the bullet. My problem is, i dont know how. Also there should be multiple enemys of the same type, so the dmg should only be applied to the enemy hit, ive had a similiar case with something else where a script affected all object of the same type.
private void OnCollisionEnter2D(Collision2D collision)
{
// good idea to check for a tag here, and skip mindless code execution if the tag differs.
var enemy = collision.collider.gameObject.GetComponent<Enemy>();
var dmg = 5f;
if(enemy != null)
{
enemy.health -= dmg
}
}
this is assuming the enemy hit actually has “Enemy.cs” script attached, with health value to reduce.