I have been stuck on this for days. I’ve watched countless videos, tried several methods, wrote different scripts, but I never have success.
I have a cannon in my game that fires at oncoming enemies. When the fireball hits the enemy, I need that to be detected and subtract health from the enemy. Sounds SO simple right? I hope so.
I had it working before, but it destroyed itself when it hit the terrain, so I need a check to make sure that the Fireball is the only one that is detected.
Here’s my code:
ENEMY:
Box Collider - Not a trigger
using UnityEngine;
using System.Collections;
public class enemy1 : MonoBehaviour {
public GameObject target;
public float speed = 5.0f;
public int health = 1;
public int maxHealth = 1;
public int minHealth = 0;
// Use this for initialization
void Awake(){
health = maxHealth;
}
void Start () {
}
// Update is called once per frame
void Update () {
transform.position = Vector3.MoveTowards (transform.position, new Vector3 (1016, 6, 1000), speed * Time.deltaTime);
//transform.position = Vector3.MoveTowards (transform.position, new Vector3(target.transform.position.x, target.transform.position.y, target.transform.position.z), speed * Time.deltaTime);
//Health Management
if (health > maxHealth) {
health = maxHealth;
}
if (health < minHealth) {
health = minHealth;
}
//Check for damage
//receiveDamage ();
//If damage is <= minHealth, destroy it.
Death ();
}
void OnTriggerEnter(Collider other){
Debug.Log ("[COLLISION]Collision Detected!");
if(other.gameObject.transform.name == "Fireball 1")
{
Debug.Log ("[COLLISION]Enemy has been hit!");
receiveDamage (1);
}
}
void receiveDamage(int damage)
{
health -= damage;
}
void Death()
{
if(health <= minHealth)
{
Debug.Log ("[ENEMY]Unit has been destroyed.");
Destroy(gameObject);
}
}
}
Oh yeah, I move my objects through the Rigidbody it has helped me to fix a lot of various issues I was having with my characters movement.
Also, I think you should move the OnTriggerenter to the fireball object. I’m not sure about this but it may be that since your enemy is not a trigger, it can’t receive an OnTriggerenter message. Your fireball should though. If that’s not option, you can try using OnCollisionEnter(Collision collision) and get the other collider with collision.collider.
I think I may have discovered something useful. The fireball is a particle system. When I fire it, the object moves but the collider stays in the origin position. This doesn’t make much sense to me.
I ran some tests and a trigger need to handle it’s own collisions. It won’t trigger OnCollisionEnter on the other collider. You need to move collision logic to OnTriiggerEnter on the fireball!