我找不到当前游戏对象的子对象(Prefab 我有父游戏对象(它是从另一个脚本中的预制件创建的),并且有 2 个 child 。层次结构如下:
RewardItemPrefab
----RewardName(有文本组件)。
----图片(有SpriteRenderer组件)。
void Start ()
{
if (RewardText == null)
{
RewardText = this.GetComponentInChildren<Text>();
if (RewardText == null)
{
Debug.Log("RewardText == null");
return;
}
}
RewardText.text = _text;
if (RewardImage == null)
{
RewardImage = this.GetComponentInChildren<Image>();
if (RewardImage == null)
{
Debug.Log("RewardImage == null");
return;
}
}
RewardImage.sprite = Reward.LoadRewardSprite(RewardImageProp);
}
但在此之前,正如我所说,这个游戏对象是从另一个脚本创建的:
var go = new GameObject(reward.Name, typeof(RewardProfileView));
go.GetComponent<RewardProfileView>().RewardItem = reward;
'RewardItem' 属性是 Reward 类属性:
public Reward RewardItem
{
get { return _reward; }
set
{
if (value != null)
{
_reward = value;
RewardTextProp = _reward.Name;
RewardImageProp = _reward.Name;
}
else
{
_reward = null;
}
}
}
RewardTextProp 和 RewardImageProp 只是字符串字段。
注意:需要能够设置动态创建的预制件的子属性。
最佳答案
如果您在一个Start()
方法中创建了GameObject,然后尝试在另一个Start()
方法中访问它,你会遇到麻烦的。这是一个典型的竞争条件示例,您不知道哪个Start()
方法将首先执行。
最简单和最直接的解决方案是将 GameObject 创建部分放在 Awake()
方法中。
Awake()
方法保证在 Start()
方法开始运行之前为所有游戏对象运行。
关于c# - Unity 在 Start() 函数中查找带有组件的子项失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31852592/