I have two creatures in my game. Both are goblins. I created the first, added it to the screen, then I duplicated the first one to create a second one and then added that to the screen. I changed their names to “goblin one” and “goblin two” … yeah I know, very creative.
With that said, they are both on the enemy layer. When my character uses his weapon, in this case a rock he is throwing, to hit the goblin, how do you distinguish between which goblin is actually being hit.
My code works great when there is only one goblin on the screen, however, when I add a second goblin, the code does some funky things.
Here’s the code in my weapon script. This runs when the weapon collides with the goblins:
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.name == "First Goblin" || collision.gameObject.name == "Second Goblin")
{
AudioSource.PlayClipAtPoint(weaponHitsEnemy, Camera.main.transform.position);
Destroy(gameObject);
FindObjectOfType<Enemy>().ProcessEnemyDeath(weaponDamage);
}
else
{
AudioSource.PlayClipAtPoint(weaponHitsWall, Camera.main.transform.position);
Destroy(gameObject);
}
}
In the code above, if the weapon collides with the goblin, the ProcessEnemyDeath method is then fired off:
public void ProcessEnemyDeath(int damageValue)
{
hitPoints -= damageValue;
if (hitPoints <=0)
{
var floatnewX = transform.position.x; // leave gold at enemy's x position
var floatnewZ = transform.position.z; // leave gold at enemy's x position
var bobsYPos = FindObjectOfType<Bob>().transform.position.y; // leave gold at bob's y position
// drop some gold after the enemy has died
Instantiate(weaponGold, new Vector3(floatnewX, bobsYPos, 0f), Quaternion.identity);
Destroy(gameObject);
}
}
I think the problem occurs when I fire off the method of processing the enemy death. It doesn’t know exactly which enemy I am hitting so it picks the second goblin.
How do I get the code to understand that they are two separate objects on the screen that need to be processed independently of one another.
Hope this makes sense.