c# - Unity 在 Start() 函数中查找带有组件的子项失败

标签 c# unity3d

我找不到当前游戏对象的子对象(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/

相关文章:

C#使用自己的字体而不安装它

c# - SQL CLR - 当前上下文的 "Static"变量

c# - Unity - 任意角度之间的夹具旋转

c# - 如何检查设备是否已在 Unity 中的所有轴上旋转

c# - 构建 Azure Function v3 时无法解析程序集 'Microsoft.AspNetCore.Mvc.Core, Version=3.1.0.0"

c# - LINQ to NHibernate,如何做这个查询

unity3d - 当游戏对象已经处于事件状态时调用 gameObject.SetActive(true) 的性能?

c# - 自定义随机数生成器

c# - XSD.exe - 如何初始化从 xs :choice 创建的类型

c# - 错误 : "Operation is not valid due to the current state of the object"