Accessing the sibling of an object
Hey guys, this may be entirely too simple of a question but for some reason everything I try isn't working. I'm shooting a raycast at an enemy who has a collider that is a child of the main object. So when I cast the ray, it returns the out hit and I can call GetComponent();
I need to get a script that isn't attached to the collider object, nor the parent, I need to access a sibling of the object I've hit. Is there any way to call GetComponent on a sibling? Trying to access MouseLook from the Collider.
[1]: /storage/temp/63191-capture.jpg
The hit goes to the Collider GameObject so I can't do it on the parent because It's not on the parent... Right?
Well maybe I could just do, temporaryHit.parent.GetComponentInChildren
Answer by Mr0w3m · Feb 03, 2016 at 06:29 PM
That was it!
Script script = temporaryHit.parent.GetComponentInChildren
Thanks!
Downvote. This does not access the child, only a component in the child
Transform transform = temporaryHit.parent.FindChild("Child Name");
OR
Transform transform = temporaryHit.parent.GetChild(0);
GetChild(0) gets first child (1) gets second etc.
Answer by unity_IAZAm8FPo3W9Uw · Aug 02, 2018 at 07:44 AM
You can get the next child of the same parent by using the GetSiblingIndex like this:
SomeObject.transform.parent.GetChild(SomeObject.transform.GetSiblingIndex() + 1);
Answer by Hoorza · Jan 26, 2019 at 02:18 PM
That is the easiest way for me:
someObject = transform.parent.gameObject.transform.GetChild(0).gameObject;
The number in the brackets next to the GetChild() part is the index for the children of the parent object, so in this case, it will access sibling object that is the first child (index number 0), increase index number to access next child in the hierarchy. Hope it helps someone as it took me a while to get it right. Cheerio!
Hey I dont know why I am doing this because I am very late, but instead of doing
someObject = transform.parent.gameObject.transform.GetChild(0).gameObject;
You can do:
someObject = transform.parent.GetChild(0).gameObject;
The reason is that transform.parent or transform.GetChild (all types of these methods) return a transform. In your code, you are getting the transform's parent (which will give the transform), then getting the gameObject of the parent and then getting the transform from the gameObject.
Your answer
Follow this Question
Related Questions
Randomized array result from other scipt 2 Answers
Changing script variable from another script doesn't change it in the original script? 0 Answers
NullReferenceException on getComponent 1 Answer
C# - Cannnot access variable in another script unless I get the component everytime. 1 Answer
C# > Camera tagged MainCamera > GetComponent<[ScriptClassHere]>() returns null ? 0 Answers