Unity3d Unity:如何确保我的对象在被检查器访问之前被实例化?
这就是我要处理的。我有一个Unity3d Unity:如何确保我的对象在被检查器访问之前被实例化?,unity3d,Unity3d,这就是我要处理的。我有一个Tile类、一个TileController和一个TileControllerEditor public class Tile { public enum TileType { Blank, Portal } public TileType type; } 我想使TileController类的tileType属性作为下拉菜单在inspector中可用。我遇到的问题是,在我的自定义检查器中,当第一次访问tileType属性
Tile
类、一个TileController
和一个TileControllerEditor
public class Tile
{
public enum TileType {
Blank, Portal
}
public TileType type;
}
我想使
TileController
类的tileType
属性作为下拉菜单在inspector中可用。我遇到的问题是,在我的自定义检查器中,当第一次访问tileType
属性时,Awake()
还没有被调用,因此tile
是null
,我得到一个NullReferenceException
如何确保我的类成员在被检查器访问之前被完全实例化?我想出了一个适合我的解决方案。因为我在另一个编辑器脚本中创建了
TileController
s,所以我可以简单地向TileController
添加一个Init()
方法,该方法起到构造函数的作用,每次创建一个构造函数时我都会手动调用它
public class TileController : MonoBehaviour
{
// The View component of a Tile
public GameObject tileObject;
// The Model component of a Tile
public Tile tile;
public Tile.TileType tileType {
get {
return tile.type;
}
set {
tile.type = value;
}
}
public void Init()
{
tile = new Tile();
}
}
然后,当我创建TileController
(它们被附加到一个预置,我实例化并调用GetComponent()
on):
void GenerateTiles()
{
...
GameObject tileObject=实例化(boardController.tilePrefab);
TileControl TileControl=tileObject.GetComponent();
tileController.Init();
...
}
您可以在声明时初始化磁贴
对象,从而避免唤醒
public class TileController : MonoBehaviour
{
public GameObject tileObject;
public Tile tile = new Tile();
public Tile.TileType tileType {
get {
return tile.type;
}
set {
tile.type = value;
}
}
}
哈。凉的我不知道你能在C#中做到这一点。
public class TileController : MonoBehaviour
{
// The View component of a Tile
public GameObject tileObject;
// The Model component of a Tile
public Tile tile;
public Tile.TileType tileType {
get {
return tile.type;
}
set {
tile.type = value;
}
}
public void Init()
{
tile = new Tile();
}
}
void GenerateTiles()
{
...
GameObject tileObject = Instantiate(boardController.tilePrefab);
TileController tileController = tileObject.GetComponent<TileController>();
tileController.Init();
...
}
public class TileController : MonoBehaviour
{
public GameObject tileObject;
public Tile tile = new Tile();
public Tile.TileType tileType {
get {
return tile.type;
}
set {
tile.type = value;
}
}
}