The Essential Guide to GetComponentInParent in Unity
Do you want to get the component from a parent game object? Of course you do. As a Unity developer, I need to do this all the time. Sometimes, I need to notify the parent about a change. Alternatively, I may want to avoid setting components in the inspector. In either case, this method is a core tool in Unity. This method helps me make games faster. It can help you, too.
:::info What you need to know
- GetComponentInParent recurses up the hierarchy to find the specific component.
- This method returns the first result it finds.
- It does not search in a defined order.
- If you need all parents with the component, use GetComponentsInParent instead.
- Avoid binding a component in the inspector.
- Get a reference to a component that you create during runtime.
:::
I have a lot to say about GetComponentInParent. Before we get there, I want to set you up with some context. To do that, I will first introduce you to GameObjects. Then, we will talk about Components. After that, we will cover the hierarchy in Unity. And finally, we will come to the method itself.
What is a GameObject?
In Unity, you use GameObjects to represent an object in your game. You can use a game object to represent anything. I will provide some concrete examples. You can use a game object to represent a character, an item, or an obstacle.
But, you can also use GameObjects to represent an arbitrary concept. For example, you can use a game object to represent the concept of a section or a group. A GameObject contains all the properties and features of that object in your game.
What are components in Unity?
You can add a component to a game object. A component is a building block. It gives the game object its characteristics or features.
Every game object starts with a Transform component. This component gives the GameObject a position in space, a rotation, and a scale.
You can add more components to give the GameObject more features or properties.
I will give a few examples. A component can enable a GameObject to…
- Move or rotate
- Detect when it is touched
- Change its color
These are just a few examples. A component is the core building block in Unity. If something happens in a Unity game, it happens because of a component.
Is there a limit to the number of components on a game object?
No. You can assign an infinite number of components to a game object in Unity. When you add a component, you add a feature to that object. Components can work together to make your game flexible and modular. But, you need to create lightweight, single-responsibility components.
What is the Unity hierarchy?
In Unity, your world is made up of a hierarchy of game objects. The hierarchy is like a family tree.
- You can set an object to act as the child of another object.
- An object can have any number of children.
- An object can have only one parent.
- A child object can also have its own children.
With this hierarchy system, you can have nested objects in your project. So, where does GetComponentInParent come in? Well, you tell this method to look for a specific component. Then, the method searches up the family tree to find that component.
What is the GetComponentInParent method?
GetComponentInParent is a UnityEngine.Component method. You specify a component to look for. Then, it recurses up the hierarchy to find the matching component. It doesn’t matter how deep your object is in the tree. This method will search all the way up to the top level. If this method does not find any matching component, then it will return null.
:::warning GetComponentInParent gets component on itself
I will explain a common misconception. If you do not know this, you will think that GetComponentInParent is not working as expected.
Quick pop quiz.
Let’s say that you call GetComponentInParent. You ask it to look for a Transform component. Can it return the transform of the caller?
- Yes.
- No.
The correct answer is A - Yes.
GetComponentInParent checks the caller. This is confusing.
You can exclude the source object. To do so, call GetComponentInParent from the parent. You can call it via the parent from the object itself. Here’s how: transform.parent.GetComponentInParent.
Confusing? Yes. Good to know? Also yes.
:::
How do I use GetComponentInParent?
The syntax of GetComponentInParent is as follows:
`T myComponent = GetComponentInParent<T>()`
Here, T represents a generic. It means that you can search for any type. In practice, you replace the generic. You replace it with the type of the component you want. For example, you may replace it with Transform, Rigidbody, or a custom component.
I will give a quick example. Let’s say that you’re looking for a Rigidbody in a parent. Here’s how you would do that:
`Rigidbody myParentRigibody = GetComponentInParent<Rigidbody>();`
Practical usage example to get a component in a parent object
Let’s say you have a game where the player collects coins.
Each coin has a “CollectableCoin” component. When the player touches the coin, here’s what should happen:
- The player gets an extra coin
- The coin disappears
To implement this feature, we set every coin to be a child of a single “Coin Holder” object. The “Coin Holder” will track how many coins the player has picked up. It takes care of this with a new component. We will call that component the CoinHolder.
When the player touches a coin,
- The coin looks for the CoinHolder component.
- The coin notifies the CoinHolder that the Player picked it up.
- The coin destroys itself
When the Coin notifies the CoinHolder:
- The CoinHolder adds a coin to the player’s bank.
Now, let’s walk through the implementation of this feature.
Step 1: Create the CollectableCoin component
Create a new C# script. Name it "CollectableCoin". Then, attach it to your Coin object.
You will see a few errors while we set up the rest of the scaffolding for your project.
using UnityEngine;
public class CollectableCoin : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
if (other.GetComponent<IsPlayer>() != null)
{
CoinHolder coinHolder = GetComponentInParent<CoinHolder>();
if (coinHolder != null)
{
coinHolder.CollectCoin();
}
Destroy(gameObject);
}
}
}
Step 2: Create the CoinHolder component
Create another C# script. Name it "CoinHolder". Then, attach it to the CoinHolder object.
using UnityEngine;
public class CoinHolder : MonoBehaviour
{
public int currentCoins = 0;
public void CollectCoin()
{
currentCoins++;
Debug.Log($"I have {currentCoins} coins!");
}
}
Step 3: Create your IsPlayer component
Create another C# script. Name it “IsPlayer”. Then, attach it to your Player GameObject. We use this component to identify your player from the CollectableCoin component.
- Why do we use a component here?: Using tags to identify an object is risky. You define the tag with a string value. If you change the string value, the tag system breaks. Using layers is not ideal. The layer system is designed for Physics interactions. It is safer and more consistent to use components for this.
using UnityEngine;
public class IsPlayer : MonoBehaviour { }
Step 4: Set up your hierarchy, colliders, and trigger settings
Create your GameObjects. Then, add the Collider and Rigidbody components. Finally, configure the components. I will leave this up to you. Not familiar with OnTriggerEnter? Read our comprehensive guide to the physics interactions in Unity.
Micro-project summary
In this example, we attached the CollectableCoin component to the coin. Here’s what CollectableCoin is doing:
- Calls OnTriggerEnter when a collision occurs.
- Checks if the collision is from a player.
- Uses GetComponentInParent to find the CoinHolder.
- Calls CollectCoin to give the player a coin.
Don’t forget to set up your project:
- Create any GameObjects you need in the Editor.
- Add Collider and Rigidbody components.
- Set the trigger options.
It is crucial that you configure your project correctly. Otherwise, the collision detection will not work.
When should I use this method?
Nested Hierarchies
You will use it when you work with a nested hierarchy. Unity organizes GameObjects in a parent child relationship. A GameObject can have one or more children. And, each child can have their own child GameObjects. This forms a tree data structure in the scene.
Flexible Code without Bound Dependencies
You can make your project more flexible with GetComponentInParent. Sometimes.
Unfortunately, your code depends on your hierarchy structure.
Fortunately, you don’t need to hardcode specific references to parent GameObjects.
This can be really helpful. For example, imagine that you create your hierarchy during runtime. In this situation, it is hard to bind a reference in the inspector. If you use this method, you can get the reference easily during runtime.
Extending our practical example
Let’s revisit our coin example. Imagine that you want to add multiplayer to your game. When you add multiplayer, you can have two players in the same game world.
The new player can also pick up coins. Player 1 still has their set of coins to pick up. Player 2 gets their own new set of coins to pick up.
You will need to make a few changes to support this feature.
First, you need your CollectableCoin to identify which player can pick it up. Second, you need it to notify the correct CoinHolder based on who picked it up. To set this up, you can make these changes:
- Change your IsPlayer script. It should have an integer field, playerId. You will use this field to identify the player character.
- Change your CoinHolder script. It should have an integer field, whichPlayerCanPickMeUp. You will use this field to match the player ID.
- Change your CollectableCoin script. When it registers a collision with an IsPlayer component, it needs to take an extra step. It needs to get the value of whichPlayerCanPickMeUp from your CoinHolder. If the value of this field and the playerId match, then it can give the player a coin.
- Create one CoinHolder for Player 1 and one CoinHolder for Player 2
Now you have two CoinHolders. Each CoinHolder has a set of coins.
- Player 1 can pick up coins under CoinHolder 1.
- Player 2 can pick up coins under CoinHolder 2.
Our strategy for how we developed this was great. If you want to move a coin from CoinHolder 1 to CoinHolder 2, it is easy. Drag and drop the Coin to the correct CoinHolder. If you move a coin from CoinHolder 1 to Coin Holder 2, it just works.
You can extend this project even further.
Apply yourself
- Imagine that you wanted to add 2 more players to the game.
- What would you need to change?
- Think about it for a few minutes.
- Write down your plan.
GetComponentInParent makes it easy for your code to respond to changes in your project hierarchy. When you move or add objects, you don’t need to re-assign GameObjects in the Inspector. You don’t even need to change your code! This will help you to develop your project faster.
Try it yourself
It’s time to take your Unity skills to the next level with a hands-on task. Let’s dive into a specific game scenario:
- Imagine you’re creating a platformer game where the player controls a character. This character can collect various power-ups.
- Each power-up is represented by a unique GameObject with its own functionality.
- Additionally, you have a “PowerUpHolder” GameObject that holds all the collected power-ups.
- Now use the GetComponentInParent method. Activate the collected power-ups when the player character collides with them.
Conclusion
The GetComponentInParent method in Unity is useful. It is a great tool to enable your code to integrate with your hierarchy. This helps you build new features faster. Whether you want to neater code or faster development, this method will help. Remember these important points: it’s a versatile method, it improves your code organization. And, one of the most important ones, it can handle complex hierarchies with ease.
Recommended reading
To continue learning about GetComponentInParent and GetComponentsInParent, I recommend the following resources:
Start with the Unity docs on GetComponentInParent.
Then, review GetComponentsInParent.
Finally, shape up your understanding of the Unity hierarchy. Read my comprehensive guide on how to get all the children of a transform.
Apply yourself
- When would you use GetComponentsInParent?
- When would you use GetComponentInParent?
- Spend a few minutes thinking about it. Come up with a few examples. Write them down.