- Home /
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.
Answer by Captain_Pineapple · Feb 15 at 09:48 PM
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220613053049im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Is it possible to get the width (in unity units) of a GameObject including all of its children? 1 Answer
Recursively get all children 1 Answer
Hierarchy Foldout Variables Wanted 3 Answers
Add Pointer Down event trigger only to parent object. 1 Answer
Creating an array of immediate children of a game object -1 Answers