Unity: GetComponentInSibling

Sharing components among siblings

In Unity, we can make good use of the following functions, when we want to get a component at runtime. This is especially interesting, if you want to structure your scripts in a certain way in the hierarchy and do not want to drag-and-drop the references (which can be easily forgotten):

  • GetComponent<T>()
  • GetComponentInChildren<T>()
  • GetComponentInParent<T>()

Additionally, there are the plural forms of it. They are part of Unity’s Component-Class. Each MonoBehaviour is also a Component, which is why you can always access these functions and look for a component on the same Game Object, or in the children/parent of the Game Object (GO) in the hierarchy.


But what if you want to get the component in a sibling (child of the same parent) in the hierarchy? For example, in the current context of Volley Brawl we are looking to find an easy mechanism to group scripts by layers using empty GOs in the hierarchy. For example: we have both Navigation and Tactics as children of Interactive Player Agent:


In both GOs we have defined scripts which would like to interact with each other, i.e. IPA Navigation needs a reference to IPA Tactics and vice versa:


Extension Method

The best way to extend an existing class, which you cannot edit (obviously, we will not be able to change Unity’s Component-Class) is in C# the extension method. This is the simplest way we could think of:


Now, in order to use it, there is only one little drawback: we cannot use the function in the context of MonoBehaviour without a keyword. This is probably due to the nature of extension methods, which require the first parameter to be typed in front of the method call.

Coming back to our example, this is how we call the extension method in Volley Brawl:

GetComponentInSibling also finds scripts on the same GO, so it imitates GetComponent (as long as there is not a second script in a sibling). That means you can freely rearrange the scripts within the second level of the hierarchy.


The little drawback of putting the this-keyword in front of the new function is bearable. With GetComponentInSibling we have written a simple but effective way which fits our strategy of putting components into the hierarchy where we think it makes sense and is good to read in the Unity Editor.

Don’t forget to try the current version of Volley Brawl!

Your Fantasy Arts Team

Share on FacebookShare on Google+Tweet about this on TwitterShare on TumblrShare on LinkedInEmail this to someone

Leave a comment

Your email address will not be published.