You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中MonoBehaviour的Null检查不符合预期问题求助

Unity中MonoBehaviour.Update里Null检查异常问题

在Unity的MonoBehaviour的Update钩子中对prevActivity对象进行Null检查,代码如下:

if (prevActivity != null) 
{
    // not null
}  
else 
{
    // null
}

但调试中明明能看到prevActivity实例包含有效属性值,代码却始终进入else分支。

设置prevActivity的代码

if (currentActivity != null && !currentActivity.Equals(prevActivity)) 
{
    prevActivity = new Activity(currentActivity);
}

Activity类定义

public class Activity {
    public ActivityName activityName;
    public string label;
    public ActivityState state;
    public bool conditionsMetToPerform;
    // Note as of current design priority should be discreet for a particular unit
    public int weigth { get; private set; }
    public int energyCost { get; private set; }

    public Activity(ActivityName activityName, string label, int weigth) {
        this.activityName = activityName;
        this.label = label;
        this.weigth = weigth;
        this.state = ActivityState.NotStarted;
        this.conditionsMetToPerform = false;
    }

    public Activity(Activity activity) {
        this.activityName = activity.activityName;
        this.label = activity.label;
        this.weigth = activity.weigth;
        this.state = activity.state;
        this.conditionsMetToPerform = activity.conditionsMetToPerform;
        this.energyCost = activity.energyCost;
    }

    public void setEnergyCost(int energyCost) {
        this.energyCost = energyCost;
    }
    public enum ActivityName {
        Wander, BuyHealing, BuyArmor, BuyWeapon, Hunt, Flee, Fight, Berserk, RestAtHome, GoHome, Raid, Refuge, VisitBlacksmith
    }

    public enum ActivityState {
        NotStarted, InProgress, Completed, Abandoned
    }
}

排查方向与解决方案

  • 添加序列化特性:如果prevActivity是MonoBehaviour中的public/可序列化字段,Unity无法序列化未标记[System.Serializable]的自定义类,会导致运行时字段被重置为null。给Activity类添加该特性:
    [System.Serializable]
    public class Activity {
        // 原有代码不变
    }
    
  • 验证赋值逻辑是否执行:在prevActivity = new Activity(currentActivity);后添加日志,确认赋值操作是否按预期触发:
    prevActivity = new Activity(currentActivity);
    Debug.Log("prevActivity已赋值,实例地址:" + System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(prevActivity));
    
  • 用日志确认真实值:避免调试器显示延迟,在Update的Null检查前添加日志,输出对象的真实状态:
    Debug.Log($"prevActivity 是否为null: {prevActivity == null}, 实例信息: {prevActivity?.activityName}");
    
  • 检查是否有意外赋值null的代码:搜索项目中所有修改prevActivity的代码,确认没有在其他路径(如OnDisable、其他方法)中把它设为null。

内容的提问来源于stack exchange,提问作者Snedden27

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 01:00:55