在 Unity 中使用 yield return StartCoroutine(new AttackAction(attacker, target).InitAction()); 时,如果 target 变量为 null,可能存在以下几种原因:

  1. 初始化 AttackAction 对象时,传递的 target 参数为 null。请确保在调用 InitAction 方法之前,target 参数被正确地初始化或传递给 AttackAction 类。

  2. AttackAction 类的构造函数中,将传递的 target 参数分配给类的成员变量 this.target。如果传递的 target 参数为 null,那么类的成员变量 target 也会是 null。

  3. 在调用 InitAction 方法之前,target 变量可能被修改为 null。请确保在调用 InitAction 方法之前,没有其他地方对 target 变量进行了修改。

为了确切确定 target 变量为 null 的原因,您可以在 InitAction 方法中添加一些调试输出来进一步排查问题。您可以使用 Unity 的 Debug.Log 方法来输出调试信息,比如检查 target 变量是否为 null 以及是否有其他地方对 target 变量进行了修改。

例如,您可以将以下代码添加到 InitAction 方法中:

public override IEnumerator InitAction()
{
    Debug.Log($'目标是否为空={target == null}');
    // 其他代码
}

通过调试信息,您可以确定 target 变量在哪个地方变成了 null,并根据具体情况进行调整。

Unity 中 Yield Return StartCoroutine 导致 Target 为 Null 的原因分析

原文地址: https://www.cveoy.top/t/topic/jHw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录