2
votes

I can't find child objects of current gameobject(which is Prefab I've got parent gameobject(it's creating from prefab in another script), and has 2 children. The hierarchy is like:

RewardItemPrefab

----RewardName(Has Text component).

----Image(Has SpriteRenderer component).

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);
    }

But before this, as I said, this gameobject is created from another script:

var go = new GameObject(reward.Name, typeof(RewardProfileView));

go.GetComponent<RewardProfileView>().RewardItem = reward;

The 'RewardItem' property is Reward class property:

    public Reward RewardItem
    {
        get { return _reward; }
        set
        {
            if (value != null)
            {
                _reward = value;

                RewardTextProp = _reward.Name;

                RewardImageProp = _reward.Name;
            }
            else
            {
                _reward = null;
            }
        }
    }

RewardTextProp and RewardImageProp are just string fields.

NOTE: Need to make ability to set children properties of dynamicaly created prefab item.

1

1 Answers

0
votes

If you create the GameObject in one Start() method, and then try to to access it in another Start() method, you will run into trouble. This is a classic example of a race condition, in which you do not know which Start() method will be executed first.

The easiest and the most straight forward solution is to put the GameObject creation part in an Awake() method.

The Awake() methods are guaranteed to run for all GameObjects before the Start() methods begin to run.