I am following a tutorial to make a simple 2d shoot 'em up. If I type out the script myself it does not work but if I copy and paste the script everything works as expected. The non-working script never seems to call OnTriggerEnter2d because I tried putting in print statements but they never appear. The only differences I can find are different placement of brackets, spaces and comments but I see no reason for differing behavior. This has been driving me up the wall and I would greatly appreciate any explanation for the differences in behavior between these 2 scripts.
Not working:
using UnityEngine;
public class HealthScript : MonoBehaviour
{
public int hp = 1;
public bool isEnemy = true;
public void Damage (int damageCount)
{
hp -= damageCount;
if (hp <= 0)
{
Destroy(gameObject);
}
}
void OnTriggerEnter2d(Collider2D otherCollider)
{
ShotScript shot = otherCollider.gameObject.GetComponent<ShotScript>();
if (shot != null)
{
if (shot.isEnemyShot != isEnemy)
{
Damage (shot.damage);
Destroy(shot.gameObject);
}
}
}
}
Working:
using UnityEngine;
public class HealthScript : MonoBehaviour
{
public int hp = 1;
public bool isEnemy = true;
public void Damage(int damageCount)
{
hp -= damageCount;
if (hp <= 0)
{
Destroy(gameObject);
}
}
void OnTriggerEnter2D(Collider2D otherCollider)
{
ShotScript shot = otherCollider.gameObject.GetComponent<ShotScript>();
if (shot != null)
{
if (shot.isEnemyShot != isEnemy)
{
Damage(shot.damage);
Destroy(shot.gameObject); // Remember to always target the game object, otherwise you will just remove the script
}
}
}
}