“Load is not allowed to be called from MonoBehaviour constructor” On script that does not inherit from MonoBehaviour

淺唱寂寞╮ 提交于 2021-01-29 22:20:37

问题


I have two classes; BuildableObject and TempObject. For some reason, Unity is treating TempObject like a MonoBehaviour class in which it throws an error if I use Resources.Load() from the constructor.

Why is this, and how do I fix it?

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
    }
}

回答1:


The reason I got an error was because I was instancing TempObject from a MonoBehaviour class:

using UnityEngine;

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


来源:https://stackoverflow.com/questions/60662859/load-is-not-allowed-to-be-called-from-monobehaviour-constructor-on-script-that

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!