首页 > 解决方案 > 您正在尝试使用“新”关键字创建 MonoBehaviour。这是不允许的

问题描述

抱歉,如果这有一个明显的答案,我对编码很陌生,我只是跟着教程一起学习。

当我运行此代码时,我收到以下错误消息: You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all UnityEngine.MonoBehaviour:.ctor()

我在网上环顾四周,但我很难找出问题所在 - 尝试在 MonoBehaviour 中使用“new”时似乎会出现此错误消息,但我的代码中没有任何地方写入“new”。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

[System.Serializable]
public class Character : MonoBehaviour
{
public string CharacterName;
public RectTransform root;

public Character (string _name)
{
    CharacterManager cm = CharacterManager.instance;
    GameObject prefab = Resources.Load ("Characters/[" + _name + "]") as GameObject;
    GameObject ob = Instantiate(prefab, cm.characterPanel);

    root = ob.GetComponent<RectTransform> ();
    CharacterName = _name;

    renderers.bodyRenderer = ob.transform.Find ("bodyLayer").GetComponent<Image> ();
    renderers.exprRenderer = ob.transform.Find ("exprLayer").GetComponent<Image> ();
}

class Renderers
{
    public Image bodyRenderer;
    public Image exprRenderer;
    
}

Renderers renderers;

}

非常感谢。

标签: c#

解决方案


我们不使用构造函数来初始化 MonoBehaviours。它们需要在 start 或 awake 函数中初始化,并在运行时使用 AddComponent/RemoveComponent 来管理它们,或者只是将它们留在预制件上。您似乎正在尝试使用此构造函数在其他地方创建 Character 类的对象。(也许在另一个脚本中?)


推荐阅读