i need to find an object based on its child index

essentially i have a gun pickup system and i want to be able to disable the previous gun in the parent object this is what i am using to get the previous gun

    previousGunName = parent.GetChild(previousGunNum).name;
    previousGunNum = transform.GetSiblingIndex() - 1;
    previousGun = GameObject.Find(previousGunName).transform;

but this only works in the start function, so it will disable the first object but not the others.
if i put it in the update function, or any other function it returns this error:
UnityException: Transform child out of bounds

to disable the gun i just do previousGun.gameObject.SetActive(false);

How can i do this better.

i can also give the full script if needed.

Hey there,

i’d suggest to try and avoid solutions which require getting Transforms often or by name.

As a better way i’d suggest you create a variable

 Transform currentGun;

in your script.
Once you pick up a gun you can set the parent for the gun transform and save a direct reference to that gun transform in currentGun. Then once you pick up a new one, simply exchange the reference and set the parents accordingly.

hope this helps, let me know if anything was unclear.