简体   繁体   中英

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

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM