Weird problem using a for loop instead of a foreach

During this challenge i came up with a different idea for gradually re enabling objects in the ballista prefab hierarchy, but did not work at the end:

    [SerializeField] int ballistaCost = 75;
    public int BallistaCost { get { return ballistaCost; } }
    [SerializeField] Transform[] prefabs;
    [SerializeField] float buildDelay = 2.5f;
    void Start()
    {
        StartCoroutine(Build());
    }

    public bool CreateTower(Towers prefab,Vector3 position )
    {
        Bank bank = FindObjectOfType<Bank>();
        if (bank == null)
        {
            return false;
        }
        if (bank.CurrentBalance >= ballistaCost)
        {
            Instantiate(prefab.gameObject, position, Quaternion.identity);
            bank.Withdraw(ballistaCost);
            return true;
        }
        return false;
    }
    IEnumerator Build()
    {
        prefabs = GetComponentsInChildren<Transform>();
        foreach(Transform prefab in prefabs)
        {
            prefab.gameObject.SetActive(false);
        }
        for(int i = 0; i <= 3; i++)
        {
            prefabs[i].gameObject.SetActive(true);
            Debug.Log(i);
            yield return new WaitForSeconds(buildDelay);
            Debug.Log("Checking");  
        }
    }

Aside my questionable choices, most of that was working, but for some reason the code cannot execute the “yield return new WaitForSeconds(buildDelay)” and get stuck in there without going back at the beginning of the loop and having re enabled just the parent that it was in index 0.

Anyone knows why this is very particular on what kind of loop to use or maybe did nor like that way to get the components reference?

The problem is not the loop. The problem is how you selected the parts. GetComponentInChildren also returns the value on the current game object, not just the children. See the documentation

What happened was that you stopped the coroutine when you disable the root game object (at index 0). The code continued (because that’s what code does) up to the point where you were yielding the WaitForSeconds but because the coroutine wasn’t running anymore, it got ignored and the code just stopped there.

Ah yes, there it is, got it thanks

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms