[英]"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
. BuildableObject
和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.出于某种原因,Unity 将
TempObject
MonoBehaviour 类,如果我从构造函数中使用Resources.Load()
,它会在其中抛出错误。
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:我收到错误的原因是因为我正在从
MonoBehaviour
类实例化TempObject
:
using UnityEngine;
public class Example : MonoBehaviour {
public BuildableObject Selected = new TempObject(); // real error
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.