Consider the following Unity C# script attached to a GameObject. What will be printed in the console when the game starts?
using UnityEngine; public class Communicator : MonoBehaviour { void Start() { var other = GetComponent<OtherComponent>(); if (other != null) { Debug.Log(other.GetMessage()); } else { Debug.Log("No OtherComponent found"); } } } public class OtherComponent : MonoBehaviour { public string GetMessage() { return "Hello from OtherComponent!"; } }
Think about whether both components are on the same GameObject.
The GetComponent<OtherComponent>() call looks for the OtherComponent on the same GameObject. Since both scripts are attached, it finds it and calls GetMessage(), printing the returned string.
Given two components on the same GameObject, what will be printed when SendMessage is called?
using UnityEngine; public class Sender : MonoBehaviour { void Start() { SendMessage("ReceiveMessage", "Hi there!"); } } public class Receiver : MonoBehaviour { void ReceiveMessage(string msg) { Debug.Log("Received: " + msg); } }
SendMessage calls methods by name on the same GameObject's components.
SendMessage calls ReceiveMessage on all components attached to the same GameObject. The method exists and takes a string, so it prints the message.
Examine the code below. Why does it throw a NullReferenceException at runtime?
using UnityEngine; public class Finder : MonoBehaviour { void Start() { var other = GameObject.Find("OtherObject").GetComponent<OtherComponent>(); Debug.Log(other.GetData()); } } public class OtherComponent : MonoBehaviour { public string GetData() => "Data"; }
Check if the GameObject with the given name exists in the scene.
If GameObject.Find("OtherObject") returns null, calling GetComponent on null causes a NullReferenceException. This happens if no GameObject named "OtherObject" is present.
Choose the correct code to get a component of type ChildComponent from a child GameObject.
Use transform.Find to locate a child by name, then get its component.
transform.Find("Child") finds the child Transform named "Child". Then GetComponent<ChildComponent>() gets the component from that child GameObject. Other options either get components from the current GameObject or search incorrectly.
You want to send a message from one component to another component on a different GameObject in the scene. Which approach is best to avoid runtime errors and ensure the message is received?
Think about how to find a GameObject safely and check for component presence.
Using GameObject.Find to locate the other GameObject, then GetComponent to get the component, and checking for null before calling methods is the safest way. It avoids null reference errors and ensures the component exists.