Thanks for clarifying.
So, you should have a method within your Enemy.cs script that looks like this;
private void OnTriggerEnter2D(Collider2D collision)
{
DamageDealer damageDealer = collision.gameObject.GetComponent<DamageDealer>();
if (!damageDealer)
{
return;
}
ProcessHit(damageDealer);
}
When there is a collision here, the first line gets a reference to the DamageDealer component on the other GameObject, e.g. the thing that just hit the enemy. In this case, this would be the player’s laser.
Assuming it finds this component, it calls ProcessHit
and passes that instance of the DamageDealer class as a reference.
private void ProcessHit(DamageDealer damageDealer)
{
health -= damageDealer.GetDamage();
damageDealer.Hit();
if (health <= 0)
{
Die();
}
}
The ProcessHit
method above reduces the health of the enemy by the value returned by the GetDamage
method for the instance of the DamageDealer class that has been passed as a parameter for this method.
The next line calls the Hit
method on that instance of the DamageDealer, which remember, is a component on the Player’s laser. The Hit
method then calls Destroy(gameObject)
which destroy’s the player’s laser.
So, there are two areas here where this could be going wrong for you;
- there isn’t a DamageDealer.cs script component on the player’s laser prefab
- you aren’t calling
Hit
as shown on the second line in the ProcessHit
method
You should be able to check the prefab fairly easily. With regards to the code, to determine what is getting called when, use some Debug.Log
statements and see what happens. For example, within the Enemy.cs script you could do this;
private void OnTriggerEnter2D(Collider2D collision)
{
DamageDealer damageDealer = collision.gameObject.GetComponent<DamageDealer>();
if (!damageDealer)
{
return;
}
Debug.Log("Found DamageDealer component on GameObject : " + collision.gameObject);
ProcessHit(damageDealer);
}
Hope this helps
Updated Wed Dec 12 2018 16:25
The above is covered in lecture Layer Collsion Matrix (#106 at the time of writing), here’s a link to the GitHub commit at that point in the course;