so I’m able to find children of a gameobject by their index number with above function, but I dont know how to call a particular child by their index number.
like I want to do something like this
if childA is disabled, enable childB
if childB is disabled, enable childC
if childC is disabled, and there is no childD, enable childA again
and the loop goes on forever
also I’m noob at programing, so if you could explain your function, that would be very helpful, I want to learn, not just copy paste.
I’m actually having a really hard time understanding what you want to do. So I will assume you only want to enable objects, this is what you want then:
for iterates through all childs, then checks if the current child is disabled, if so enables the next one.
public void OnTargetHit()
{
gameObject.SetActive(false);
if (transform.GetSiblingIndex() < transform.parent.childCount - 1)
transform.parent.GetChild(transform.GetSiblingIndex() + 1).gameObject.SetActive(true);
else
transform.parent.GetChild(0).gameObject.SetActive(true);
}
Ok based on your comment your question has completely changed and is much clearer now ^^. Things like that shouldn’t be handled at a central point because you have to keep track of many things at the same time. Also checking if an object is disabled every frame is just bad design.
Instead you can create a very simply script which you attach to each target.
// Target.cs
using UnityEngine;
public class Target : MonoBehaviour
{
public GameObject Next;
private void OnCollisionEnter(Collision collision)
{
gameObject.SetActive(false);
if (Next != null)
Next.SetActive(true);
}
}
Just disable all targets in the scene except the first one. Now you can link your targets together in whatever order you like by dragging the “next” target which should be active onto the “Next” field in the inspector. You can also link the last target simply back to your first one.
If you don’t want to do the linking by hand you can create another script on the parent which just does the linking for you:
void Start()
{
if (transform.childCount <1)
{
Debug.LogWarning("not enough children to link them");
return;
}
GameObject last = transform.GetChild(0).gameObject;
for(int i = transform.childCount-1; i >= 0; i--)
{
Target target = transform.GetChild(i).GetComponent<Target>();
if (target != null)
{
target.Next = last;
last = target.gameObject;
}
}
}