问题
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