Search code examples
c#unity-game-enginedisableprefab

Disable Child Element of a Prefab with Script


I have just started to learn Unity 2d and I have taken a task at hand where I want to Instantiate a Prefab from Assets folder and then disable some of the child elements in it once the prefab is initiated. Following is my code :

void createPuzzleGame()
    {
        Puz = Resources.Load("Dog") as GameObject;
        Instantiate(Puz, PuzArea.transform);
        for (int i = 0; i < Puz.transform.childCount; ++i)
        {
            Transform currentItem = Puz.transform.GetChild(i);
            if (currentItem.name.StartsWith("a") || currentItem.name.StartsWith("og"))
            {
                currentItem.gameObject.SetActive(false); //this line doesn't work
            }
            else
            {
                Debug.Log(currentItem.name);
            }
        }
    }

I want to disable all child images of the prefab Puz that start with letter 'a' or 'og'. The prefab Dog(clone) gets created on running the code. However the child elements don't seem to disable. Where am I going wrong? Please help.


Solution

  • You are trying to iterate through the children of the original prefab Puz.

    You rather need to iterate through the newly created instance

    var instance = Instantiate(Puz, PuzArea.transform);
    foreach(Transform child in instance.transform)
    {
        if (child.name.StartsWith("a") || child.name.StartsWith("og"))
        {
            child.gameObject.SetActive(false);
        }
        else
        {
            Debug.Log(child.name);
        }
    }