Home > Enterprise >  Disable Child Element of a Prefab with Script
Disable Child Element of a Prefab with Script

Time:12-05

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.

CodePudding user response:

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

CodePudding user response:

Puz is the prefab's reference. Instantiate returns the actual instance you create from Puz. You need to change the instance:

Transform dog = Instantiate(Puz, PuzArea.transform).transform;
for (int i = 0; i < dog.childCount;   i) { /* ... */ }

or, you can add a script to your prefab, and move this logic there, something like this (in this case, you have to add your references to _images on the prefab, but you can use your search by name logic also):

public class Puzzle : MonoBehaviour
{
    [SerializeField] private GameObject[] _images;

    public void SetImagesVisibility(bool visible)
    {
        for (int i = 0; i < _images.Length; i  ) _images[i].SetActive(visible);
    }
}

and you can use this at instantiating:

Puzzle puz = Instantiate(Puz, PuzArea.transform).GetComponent<Puzzle>();
puz.SetImagesVisibility(false);
  • Related