Hi all,
I’m trying to code a system wherein projectiles, upon colliding with an enemy, deal damage to it and then destroy themselves. Currently, I am trying to do this through the following code, in the script for the projectile itself:
void OnCollisionEnter2D(Collision2D collision){
GameObject collidedWith = collision.gameObject;
if (collidedWith.layer == 10){
Enemy enemy = (Enemy)collision.gameObject;
enemy.DamageEnemy(50);
Destroy(this.gameObject);
}
Where DamageEnemy is a method within the Enemy class itself, and Layer 10 is the ‘Enemies’ layer.
Now, when I try to load this code, I get the following error:
error CS0030: Cannot convert type UnityEngine.GameObject' to Enemy’
I’ve done a little reading online, but the only solution to a similar problem seemed to involve Instantiating a new object, which won’t work for me, since I don’t want to Instantiate a new object, but rather access the method of an already-existent object (the enemy being hit by the projectile). I was trying to convert collision.gameObject to an Enemy because gameObject does not have a DamageEnemy() method, but clearly this is impossible. The question, then, is how I’m supposed to access the DamageEnemy() method of the object in the collision, when the only way I know of accessing said object returns it in a form that does not have the DamageEnemy() method, and conversion into a form that does have this method isn’t possible.
Thanks.