“不允许从 MonoBehaviour 构造函数调用 Load";在不继承 MonoBehaviour 的脚本上 [英] "Load is not allowed to be called from MonoBehaviour constructor" On script that does not inherit from MonoBehaviour
本文介绍了“不允许从 MonoBehaviour 构造函数调用 Load";在不继承 MonoBehaviour 的脚本上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个班级;BuildableObject
和 TempObject
.出于某种原因,Unity 将 TempObject
视为 MonoBehaviour 类,如果我从构造函数中使用 Resources.Load()
,它会在其中抛出错误.
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
}
}
推荐答案
出现错误的原因是我从 MonoBehaviour
类中实例化了 TempObject
:>
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
}
这篇关于“不允许从 MonoBehaviour 构造函数调用 Load";在不继承 MonoBehaviour 的脚本上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文