【问题标题】:"Load is not allowed to be called from MonoBehaviour constructor" On script that does not inherit from MonoBehaviour“不允许从 MonoBehaviour 构造函数调用加载”在不从 MonoBehaviour 继承的脚本上
【发布时间】:2020-03-12 22:59:45
【问题描述】:

我有两节课; BuildableObject 和 TempObject。出于某种原因,Unity 将 TempObject 视为 MonoBehaviour 类,如果我在构造函数中使用 Resources.Load(),它将引发错误。

为什么会这样,我该如何解决?

public abstract class BuildableObject {

    public abstract Vector2Int Space { get; set; }
    public abstract GameObject Body { get; set; }

    public void Init(GridSpace[,] World, Vector2Int pos) {
        Vector3 Pos = World[pos.x, pos.y].pos;

        //TODO: Optimize
        //TODO: Add availibility for multiple tile sizes
        Pos.x += Body.transform.lossyScale.x / 6;
        Pos.y += Body.transform.lossyScale.y / 6;

        Body.transform.position = Pos;

        Body.transform.position = new Vector3(Body.transform.position.x,Body.transform.position.y,-5);

        Object.Instantiate(Body);

        OnPlace();
    }

    public void OnPlace() { }
    public void OnUpdate() { }
    public void OnRemove() { }
    public void OnInteract(InteractData Data) { }

}
public class TempObject : BuildableObject {
    public override Vector2Int Space { get; set; } = new Vector2Int(2, 2);
    public override GameObject Body { get; set; }

    public TempObject() {
        Body = (GameObject)Resources.Load("BuildPrefabs/Test", typeof(GameObject)); //error
    }
}

【问题讨论】:

    标签: c# class unity3d inheritance runtime-error


    【解决方案1】:

    我收到错误的原因是因为我从 MonoBehaviour 类中实例化 TempObject:

    using UnityEngine;
    
    public class Example : MonoBehaviour {
        public BuildableObject Selected = new TempObject(); // real error
    }
    

    【讨论】:

      猜你喜欢
      • 2023-01-25
      • 1970-01-01
      • 2014-01-16
      • 1970-01-01
      • 2014-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多