Skip to content

Instantly share code, notes, and snippets.

@farukcan
Created January 15, 2022 16:00
Show Gist options
  • Save farukcan/cb7865963f59d4e3e6451a11dfcc0f3a to your computer and use it in GitHub Desktop.
Save farukcan/cb7865963f59d4e3e6451a11dfcc0f3a to your computer and use it in GitHub Desktop.
Unity GameObject Child Selector
// Author: github.com/farukcan
// Usage :
// selector.Select("Object 1");
// selector.SelectRandom();
// selector.OpenSelfAndSelect("Object 1");
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChildSelector : MonoBehaviour {
public void Select(string child_name) {
List<GameObject> selected = new List<GameObject>();
foreach(Transform child in transform)
{
child.gameObject.SetActive(false);
if (child_name == child.gameObject.name)
selected.Add(child.gameObject);
}
if (selected.Count == 0)
Debug.LogWarning("ChildSelector not found : " + child_name);
else
foreach (GameObject obj in selected)
obj.SetActive(true);
}
public void OpenSelfAndSelect(string child_name)
{
gameObject.SetActive(true);
Select(child_name);
}
public void SelectRandom(){
List<Transform> childs = new List<Transform>();
foreach(Transform child in transform)
{
childs.Add(child);
}
Select(childs[Random.Range(0,childs.Count)].gameObject.name);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment