简体   繁体   中英

Health system script not running in Unity; no errors or Debug.Log statements popping up

For my health system in a Unity game, I have a script that is accountable for my in-game "enemy" hit-points. The game runs just fine, but the script doesn't seem to be doing anything. I'm not getting any error messages, but the fact that it's not working and Debug.Log statements aren't popping up in console seem to be that functions aren't being called properly or that something else is awry. Here is my script:

using System.Diagnostics;
using UnityEngine;
public class Health : MonoBehaviour {
private float hitPoints = 5;
    // Health popup
    void announceUp()
    {
        UnityEngine.Debug.Log("If this message shows in Debug.Log, the script should be working.");
    }
    // Update is called once per frame
    void Update()
    {
        void OnTriggerEnter(Collider other)
        {
            if (other.gameObject.tag == "Bullet")
            {
                UnityEngine.Debug.Log("The enemy has been hit!");
                hitPoints = hitPoints - 1f;
                if (hitPoints == 0f)
                {
                    UnityEngine.Debug.Log("The enemy has been eliminated!");
                    Destroy(gameObject);
                }
            }
        }
    }
}

I've poked around the internet to see what's wrong, but I couldn't find anything. Could someone inform me on what could be wrong with my programming?

Your scrpt is currently not working, because you are defining the OnTriggerEnter() Method inside the Update() Method. When you do that you are defining a local function and Unity then can't call that function when actual collision happens. So your OnTriggerEnter() Function never get's called.

Example:

using System.Diagnostics;
using UnityEngine;

public class Health : MonoBehaviour 
{
    private float hitPoints = 5;
    // Health popup
    void announceUp() {
        UnityEngine.Debug.Log("If this message shows in Debug.Log, 
            the script should be working.");
    }

    // Update is called once per frame
    void Update() {}

    void OnTriggerEnter(Collider other) {
        if (other.gameObject.tag == "Bullet") {
            UnityEngine.Debug.Log("The enemy has been hit!");
            hitPoints = hitPoints - 1f;
            if (hitPoints == 0f) {
                UnityEngine.Debug.Log("The enemy has been eliminated!");
                Destroy(gameObject);
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM