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

如何修复Unity中使用'new'关键字创建MonoBehaviour的警告

Unity警告 You are trying to create a MonoBehaviour using the 'new' keyword 原因与修复

触发原因

  • Unity中所有继承自MonoBehaviour的类,生命周期完全由引擎管理,绝对不能用new关键字直接创建实例。用new生成的MonoBehaviour实例是无效的:不会挂载到任何GameObject上,不会触发Awake/Start/Update等生命周期,也无法正常使用协程、Invoke等引擎提供的功能,引擎检测到这种写法就会抛出该警告。
  • 你贴出的CardDatabase本身没有问题,警告来源是你代码里new Card(...)这一行:你的Card类肯定写了: MonoBehaviour的继承声明,属于被错误new的MonoBehaviour类。

修复方案

根据你对Card类的需求选对应方案即可:

方案1:Card作为纯数据类使用(推荐,匹配你当前的写法)

如果Card只用来存储卡牌ID、名称、数值这类数据,不需要挂载到场景物体上、也不需要用Unity的生命周期/API,直接删掉Card类对MonoBehaviour的继承,改成普通C#类就行:

// 去掉: MonoBehaviour,纯数据类不需要被引擎托管
public class Card
{
    public int id;
    public string cardName;
    public int cost;
    public int attack;
    public int health;
    public string iconAddress;

    // 原有带参构造函数可以正常保留使用
    public Card(int id, string cardName, int cost, int attack, int health, string iconAddress)
    {
        this.id = id;
        this.cardName = cardName;
        this.cost = cost;
        this.attack = attack;
        this.health = health;
        this.iconAddress = iconAddress;
    }
}

改完之后你原来CardDatabase里的代码完全不用动,直接new Card()不会再触发任何警告,也是数据类最合理的实现方式。

方案2:Card必须继承MonoBehaviour

如果你的Card类需要挂载到卡牌物体上、要用到协程/物理事件/生命周期函数这类MonoBehaviour专属能力,就不能用new创建,必须走Unity的实例化规则:

  1. 先把做好的卡牌对象做成预制体,挂载Card脚本
  2. 用Instantiate接口生成实例,不要直接new
  3. MonoBehaviour不支持带参构造函数,初始化逻辑单独写Init方法实现

对应代码示例:

public class CardDatabase : MonoBehaviour
{
    public static List<Card> cardList = new List<Card>();
    // Inspector里拖入做好的Card预制体
    public Card cardPrefab;

    private void Awake()
    {
        Card newCard = Instantiate(cardPrefab);
        // 调用自定义初始化方法传参
        newCard.Init(0, "Blank", 1, 1, 1, "111b");
        cardList.Add(newCard);
    }
}

// Card类保留MonoBehaviour继承
public class Card : MonoBehaviour
{
    public int id;
    public string cardName;
    public int cost;
    public int attack;
    public int health;
    public string iconAddress;

    // 替换构造函数为Init方法
    public void Init(int id, string cardName, int cost, int attack, int health, string iconAddress)
    {
        this.id = id;
        this.cardName = cardName;
        this.cost = cost;
        this.attack = attack;
        this.health = health;
        this.iconAddress = iconAddress;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 01:45:43