Unity Learn home
View Tutorial Content
Steps

GetComponent

Tutorial
Beginner
+10 XP
5 Mins
(2109)
Summary
How to use the GetComponent function to address properties of other scripts or components.
This tutorial is included in the Beginner Scripting project.
Previous: OnMouseDown
Select your Unity version
Last updated: November 17, 2023
2019.3
2019.2
2019.1
2018.4
2018.3
2018.2
2018.1
2017.4
2017.3
2017.2
2017.1
5.x
4.x
Language
English
Also included in

1.GetComponent

Video Player is loading.
Current Time 0:00
Duration 0:00
Loaded: 0%
Stream Type LIVE
Remaining Time 0:00
 
1x

UsingOtherComponents

using UnityEngine; using System.Collections; public class UsingOtherComponents : MonoBehaviour { public GameObject otherGameObject; private AnotherScript anotherScript; private YetAnotherScript yetAnotherScript; private BoxCollider boxCol; void Awake () { anotherScript = GetComponent<AnotherScript>(); yetAnotherScript = otherGameObject.GetComponent<YetAnotherScript>(); boxCol = otherGameObject.GetComponent<BoxCollider>(); } void Start () { boxCol.size = new Vector3(3,3,3); Debug.Log("The player's score is " + anotherScript.playerScore); Debug.Log("The player has died " + yetAnotherScript.numberOfPlayerDeaths + " times"); } }

AnotherScript

using UnityEngine; using System.Collections; public class AnotherScript : MonoBehaviour { public int playerScore = 9001; }

YetAnotherScript

using UnityEngine; using System.Collections; public class YetAnotherScript : MonoBehaviour { public int numberOfPlayerDeaths = 3; }

GetComponent
GetComponent
General Tutorial Discussion
10
3
1. GetComponent
30
12