[SOLVED] Script not triggering when projectile collides with enemy.

For some reason, the projectile just goes straight through the enemy and nothing occurs.

Pictures of the inspector for the projectile object and the enemy object:

This is my projectile script:

using UnityEngine;
using System.Collections;

public class ProjectileScript : MonoBehaviour
{

        public float speed;
        public int damage;
        public float lifeSpan;
        public bool isEnemyShot;
        public Vector3 targetPosition;

        void Update ()
        {
                transform.position = Vector2.MoveTowards (transform.position, targetPosition, speed * Time.deltaTime);
        }
}

Enemy Health script:

using UnityEngine;
using System.Collections;

public class HealthScript : MonoBehaviour
{

        public int hp = 1;
        public bool isEnemy = true;

        public void Damage (int damage)
        {
                hp -= damage;
  
                if (hp <= 0) {
                        Destroy (gameObject);
                }
        }

        void OnTriggerEnter2D (Collider2D otherCollider)
        {
                print ("shshs");
                // Is this a shot?
                ProjectileScript projectile = otherCollider.gameObject.GetComponent<ProjectileScript> ();
                if (projectile != null) {
                        print ("runs here");
                        // Avoid friendly fire
                        if (projectile.isEnemyShot != isEnemy) {
                                Damage (projectile.damage);
                                print ("runs here2");
                                // Destroy the shot
                                Destroy (projectile.gameObject); // Remember to always target the game object, otherwise you will just remove the script
                        }
                }
        }
}

The projectile passes through the object because it’s going way too fast.
People use raycast to prevent this problem.

Even when the speed is 2 it still moves right through!
What function(s) could I use to fix this?

Well, it passes through cause the collider is a trigger.

Yes, I know but it’s not supposed to pass through.
The “HealthScript” is supposed to delete the projectile upon collision, but no collision is registered.
Reading the MoveTowards API, I don’t believe the problem is speed related.

Fixed it! It’s because I used “EnterCollision2D” but the sphere is 3D.

1 Like