【问题标题】:Health system script not running in Unity; no errors or Debug.Log statements popping up健康系统脚本未在 Unity 中运行;没有错误或 Debug.Log 语句弹出
【发布时间】:2020-10-12 03:14:47
【问题描述】:

对于我在 Unity 游戏中的健康系统,我有一个脚本负责我在游戏中的“敌人”生命值。游戏运行得很好,但脚本似乎没有做任何事情。我没有收到任何错误消息,但事实上它不起作用并且 Debug.Log 语句没有在控制台中弹出似乎是函数没有被正确调用或者其他东西出了问题。这是我的脚本:

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);
                }
            }
        }
    }
}

我已经在互联网上四处寻找问题所在,但我找不到任何东西。有人可以告诉我我的编程有什么问题吗?

【问题讨论】:

  • 把OnTriggerEnter函数从你的更新方法中去掉。
  • 这给了我一个错误,说缺少一个右大括号,即使它在那里......

标签: c# unity3d


【解决方案1】:

您的脚本当前不工作,因为您在Update() 方法中定义了OnTriggerEnter() 方法。当您这样做时,您正在定义一个本地函数,而 Unity 在实际发生碰撞时无法调用该函数。所以你的 OnTriggerEnter() 函数永远不会被调用。

例子:

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);
            }
        }
    }
}

【讨论】:

  • 那你的碰撞有问题。检查包含 OnTriggerEnter 的对象是否确实启用了 IsTrigger,并且两个对象都有一个盒子碰撞器和刚体。
  • 脚本所附加到的父对象没有刚体,但由于“敌人”是布娃娃,它的所有骨骼都具有您提到的组件。但是,当它被击中时,它确实会与子弹相互作用(例如:翻滚)。
  • 你确定敌人启用了 IsTrigger,因为如果他没有启用,你就需要使用 OnCollisionEnter。
  • 不!它没有启用,但现在它工作得很好!谢谢!
猜你喜欢
  • 1970-01-01
  • 2022-01-10
  • 2019-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-30
相关资源
最近更新 更多