Going through empty gameObject by clicking first child, destroy it then activate the next one?

Hey, is there a better way to do this? I have a bunch of hidden gameObjects. When I click on the first gameObject, I destroy it then activate the next one. I’m doing it fine, but i’m sure this is not the best way. I’m still a novice. Then I get an error at the end saying that i’m out of bounds.


Here what it looks like:



Here is the code:

public class onMouseClick : MonoBehaviour {
    public Transform raceSet;

	// Use this for initialization
	void Start () {
	}
	
	// Update is called once per frame
	void Update () {
        Transform secondChild = raceSet.GetChild(1);
        RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), 
        Vector2.zero);

        if (Input.GetMouseButtonDown(0))
        {
            if (hit.collider != null)
            {
                if (hit.collider.gameObject == this.gameObject)
                {
                    Destroy(gameObject);
                    secondChild.gameObject.SetActive(true);
                }
            }
        }

   }

    
}

Thank you for your time!

when my answer code doesnt goes in a good format i just put some extra spaces at each code line that works for me.

There are a lot of thinks you can change.
First save vars once if posible, you are declaring a seconChild var when you can just assigned one at the start, but if you want to assign it there for whatever reason dont code extra unnecesary code, you would be able to deckare the var just before the secondChild.gameIbject.SetActive(true)

But dont really use that method, probably with your type of game you can reuse those platforms after that so you can have a pool of hiden objects and just activate and desactivate it by code.

Get use to work with layers and tags for avoiding extra checks, right now you have few objects but with a big project you might have thousands and somthing like raycast would have to do a ot of extra checks

Are all platforms / buttons (not sure what those are) the same? cause you could have just 1 with a bunch of positions and repositionate once per click.

That error is cause the parent object ends up without childs you can fix that just checking if secondChild is null.

If you are using a property frequently you can save it too at the start for saving some extra time like create a Vector2 vectorZero = Vector2.zero.

Also it is better usually a manger that those the work rather than having that script assigned to every object.

Hope it helps other will give you extra tips.