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

Unity使用new创建MonoBehaviour触发黄色警告问题咨询

错误原因

你收到的警告核心原因是ScoreMultiplerFinder继承了MonoBehaviour类,而Unity明确禁止使用new关键字直接构造MonoBehaviour类型的实例。这类实例仅允许两种生成方式:要么提前挂载到场景的GameObject对象上,要么通过GameObject.AddComponent<T>()方法动态添加生成。你在单例的getter中直接new ScoreMultiplerFinder()的写法违反了这个规则,所以触发了警告。

解决方案

这里提供两种可直接复用的修复方案,你可以根据自己的需求选择:

方案1:保留MonoBehaviour继承,改用Unity标准单例写法

如果你的ScoreMultiplerFinder后续需要用到MonoBehaviour的生命周期方法(如Update、协程等),可以选择这个方案:

  1. 在场景中新建一个空GameObject,命名为CheckpointManager,将ScoreMultiplerFinder脚本挂载到这个物体上
  2. 替换ScoreMultiplerFinder的代码如下:
using System.Collections.Generic;
using UnityEngine;
using System.Linq;

public class ScoreMultiplerFinder : MonoBehaviour
{
    private static ScoreMultiplerFinder instance;
    private List<GameObject> checkpoints = new List<GameObject>();
    public List<GameObject> Checkpoints => checkpoints;

    public static ScoreMultiplerFinder Singleton => instance;

    private void Awake()
    {
        // 单例防重逻辑
        if (instance != null && instance != this)
        {
            Destroy(gameObject);
            return;
        }
        instance = this;
        // 初始化检查点逻辑移到Awake中执行
        checkpoints.AddRange(GameObject.FindGameObjectsWithTag("Checkpoint"));
        checkpoints = checkpoints.OrderBy(waypoint => waypoint.name).ToList();
    }
}

这个方案不需要修改你挂载在玩家对象上的FindClosestMultiplier()方法,原有调用逻辑完全兼容。

方案2:移除MonoBehaviour继承,支持直接new实例

如果你的ScoreMultiplerFinder不需要用到任何MonoBehaviour的功能,直接移除继承关系即可,修复后代码如下:

using System.Collections.Generic;
using UnityEngine;
using System.Linq;

public class ScoreMultiplerFinder
{
    private static ScoreMultiplerFinder instance;
    private List<GameObject> checkpoints = new List<GameObject>();
    public List<GameObject> Checkpoints => checkpoints;

    public static ScoreMultiplerFinder Singleton
    {
        get
        {
            if (instance == null)
            {
                instance = new ScoreMultiplerFinder();
                instance.checkpoints.AddRange(GameObject.FindGameObjectsWithTag("Checkpoint"));
                instance.checkpoints = instance.checkpoints.OrderBy(waypoint => waypoint.name).ToList();
            }
            return instance;
        }
    }
}

这个方案不需要在场景中额外创建挂载脚本的物体,代码改动量极小,原有调用逻辑同样完全兼容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 02:54:08