c# - 您正在尝试使用“新”关键字创建 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;
}
非常感谢。
解决方案
我们不使用构造函数来初始化 MonoBehaviours。它们需要在 start 或 awake 函数中初始化,并在运行时使用 AddComponent/RemoveComponent 来管理它们,或者只是将它们留在预制件上。您似乎正在尝试使用此构造函数在其他地方创建 Character 类的对象。(也许在另一个脚本中?)
推荐阅读
- javascript - 如何将输入字段的宽度调整为 html 中的最大长度?
- linux - 如何将 linux 命令行输出保存到 .txt 文件?
- python - 将数据框的(抓取)列表写入单个 excel 表
- javascript - 如何禁用拆分成更漂亮的新行?
- python - 使用 map lambda 销毁小部件 tkinter
- google-sheets-api - Google Ads 脚本是否有任何调试器?
- java - 如果字符串以数组的任何值结尾 Java
- discord.js - 无法添加反应 discord.Js
- kotlin - Kotlin:如何从一个字节中获取某个位置的位值?
- apache-kafka - 如何从 Kafka 消费者返回对 RESTFUL 请求的响应?