Consider a Unity GameObject with a Rigidbody component attached. What will the following code print in the console?
void Start() {
Rigidbody rb = GetComponent<Rigidbody>();
if (rb != null) {
Debug.Log("Rigidbody found");
} else {
Debug.Log("No Rigidbody");
}
}Think about whether the Rigidbody component is attached to the same GameObject.
If the Rigidbody component is attached to the same GameObject, GetComponent<Rigidbody>() returns it, so the message "Rigidbody found" is printed.
What will this code print if the GameObject does NOT have a BoxCollider component?
void Start() {
BoxCollider box = GetComponent<BoxCollider>();
if (box == null) {
Debug.Log("BoxCollider missing");
} else {
Debug.Log("BoxCollider found");
}
}GetComponent returns null if the component is not found.
If the component is missing, GetComponent returns null, so the code prints "BoxCollider missing".
Given this code in a parent GameObject, what will it print if the child has a Light component but the parent does not?
void Start() {
Light lightComp = GetComponent<Light>();
if (lightComp != null) {
Debug.Log("Light found on parent");
} else {
Debug.Log("Light not found on parent");
}
}GetComponent only searches the GameObject it is called on, not children.
GetComponent does not search child GameObjects. Since the parent has no Light component, it returns null and prints "Light not found on parent".
What will this code print if the GameObject has a Camera component?
void Start() {
if (TryGetComponent<Camera>(out Camera cam)) {
Debug.Log("Camera found");
} else {
Debug.Log("Camera missing");
}
}TryGetComponent returns true if the component exists.
TryGetComponent returns true and outputs the component if it exists, so it prints "Camera found".
Suppose you have a component that implements an interface IMyInterface. Which statement about GetComponent<IMyInterface>() is true?
Unity supports GetComponent with interfaces implemented by components.
GetComponent can return a component that implements the requested interface if it exists on the GameObject. It returns null if none found.