c# - 为什么 MonoBehaviour Start() 上的类引用丢失
问题描述
我在静态方法中创建了一个新 GameObject 的实例,并在其中设置了所有 GameObject 字段。但是,当我尝试从 Start() 获取字段时,引用属性为空。
public class Hero : MovableStrategicObject
{
public string heroName;
public Player conrtollingPlayer;
protected new void Start()
{
base.Start();
Debug.Log("2 - Hero name: " + heroName);
Debug.Log("2 - Controlling player exists: " + (conrtollingPlayer != null));
Debug.Log("2 - Tile exists: " + (currentTile != null)); // Inherited attribute
}
public static GameObject Spawn(Tile tile, Player player, string name, string prefabPath = "Heroes/HeroPrefab")
{
GameObject o = MovableStrategicObject.Spawn(prefabPath, tile);
var scripts = o.GetComponents(typeof(MonoBehaviour));
Hero hero = null;
foreach (MonoBehaviour s in scripts)
{
if (s is Hero)
hero = s as Hero;
}
if (hero != null)
{
Instantiate(o, (Vector2)tile.gameObject.transform.position, Quaternion.identity);
o.GetComponent<Hero>().conrtollingPlayer = player;
o.GetComponent<Hero>().heroName = name;
Debug.Log("1 - Hero name: " + o.GetComponent<Hero>().heroName);
Debug.Log("1 - Controlling player exists: " + (o.GetComponent<Hero>().conrtollingPlayer != null));
Debug.Log("1 - Tile exists: " + (o.GetComponent<Hero>().currentTile != null)); // Inherited attribute
return o;
}
else
{
Debug.Log("Object (" + prefabPath + ") has no Hero script attached.");
return null;
}
}
}
结果:
PS 您可以确定它是正确的游戏对象,因为英雄名称和所有派生属性都已正确分配。
解决方案
问题出在这一行:
Instantiate(o, (Vector2)tile.gameObject.transform.position, Quaternion.identity);
因为这个对象是 GameObject 的一个新实例,所以与前一个对象的所有分配都不会影响这个实例。所以修复是:
GameObject h = Instantiate(o, (Vector2)tile.gameObject.transform.position, Quaternion.identity);
h.GetComponent<Hero>().conrtollingPlayer = player;
h.GetComponent<Hero>().heroName = name;
return h;
新对象已经具有此信息。
推荐阅读
- google-vault-api - 创建组时出现内部服务器错误
- vuejs2 - 如何使用 vue 路由器添加表单部分 HTML?
- c++ - 通过 C++ 中的重载构造函数初始化未知类型的变量
- java - 我试图将数组存储到 txt 文件
- powershell - Jenkins Pipeline Script - 评估批处理/powershell的标准输出
- react-native - 处理生物特征认证
- scala - SBT:如何依赖同一项目中的交叉编译模块
- python - 在python中计算运行中位数的最短方法是什么?
- sdk - Spring Boot Application with S/4Hana On-Premise 使用 Cloud SDK 3.9.0
- database - 查找被锁定并存在编译问题的表、包、程序的列表