I’m following this tutorial. I have an attacking cube running into a rectangle. I scripted it so that when they collide (OnTriggerEvent), one health point will be removed from the rectangle’s health pool. Unlike the tutorial, I do not want the attacking cube to destroy itself.
This works fine, except a few milliseconds/frames later all of the rectangle’s health points disappear in an instant as well. There is a slight hiccup between the first point vanishing and the rest of the pool (which happens all at once/super fast).
I feel like something strange is happening with OnTriggerEvent. It’s not just triggering on the initial collision, or something else is going on that I can’t explain. Do I understand this function correctly or am I misusing it?
Health code:
using UnityEngine;
using System.Collections;
public class Healthchange : MonoBehaviour {
TextMesh tm;
// Use this for initialization
void Start () {
tm = GetComponent<TextMesh>();
}
// Update is called once per frame
void Update () {
transform.forward = Camera.main.transform.forward;
}
public int current()
{
return tm.text.Length;
}
public void decrease()
{
if (current() > 1)
tm.text = tm.text.Remove(tm.text.Length - 1);
else
Destroy(transform.parent.gameObject);
}
}
Monster AI code:
using UnityEngine;
using System.Collections;
public class Monster : MonoBehaviour {
bool triggered = false;
// Use this for initialization
void Start () {
GameObject tower = GameObject.Find("Tower");
if (tower)
GetComponent<NavMeshAgent>().destination = tower.transform.position;
}
void OnTriggerEnter(Collider co)
{
if (co.name == "Tower")
{
co.GetComponentInChildren<Healthchange>().decrease();
triggered = true;
}
}
}
Now, I already fixed the issue at hand by using a boolean to explicitly state if and when the rectangle can be damaged. So after the first hit, it cannot lose health (for now):
void OnTriggerEnter(Collider co)
{
if (triggered == false)
{
if (co.name == "Tower")
{
co.GetComponentInChildren<Healthchange>().decrease();
triggered = true;
But I don’t want to use a band-aid if I don’t have to. I thought Unity was smart enough to do this logic for me. Am I wrong? Why is the collision event triggering more than once when the objects are just standing next to each other?