UCA Unity Scripting & Programming 2 — Questions and Answers
Question 1: Which Unity method is called once per physics update, making it ideal for rigidbody force applications?
- Update()
- LateUpdate()
- FixedUpdate() (Correct answer)
- OnCollisionEnter()
Correct answer: FixedUpdate()
FixedUpdate() runs at a fixed timestep aligned with the physics engine, ensuring consistent physics calculations.
Question 2: What does the 'ref' keyword do when passed to a C# method in a Unity script?
- Creates a copy of the variable
- Passes the variable by reference allowing modification (Correct answer)
- Marks the variable as read-only
- Converts the variable to a pointer
Correct answer: Passes the variable by reference allowing modification
The 'ref' keyword passes a variable by reference, so changes inside the method affect the original variable.
Question 3: Which attribute prevents a field from appearing in the Unity Inspector while still keeping it public?
- [HideInInspector] (Correct answer)
- [NonSerialized]
- [System.NonPublic]
- [EditorOnly]
Correct answer: [HideInInspector]
[HideInInspector] hides a public serialized field from the Inspector without removing its public accessibility.
Question 4: What is the correct way to cache a component reference efficiently in Unity?
- Call GetComponent<T>() every frame in Update()
- Store the result of GetComponent<T>() in Awake() or Start() (Correct answer)
- Use FindObjectOfType<T>() each frame
- Declare the component as static
Correct answer: Store the result of GetComponent<T>() in Awake() or Start()
Caching component references in Awake() or Start() avoids the overhead of calling GetComponent<T>() every frame.
Question 5: In Unity, what does 'Instantiate()' return?
- A Transform reference only
- A GameObject reference only
- A reference to the same type as the passed object (Correct answer)
- void
Correct answer: A reference to the same type as the passed object
Instantiate() returns an Object of the same type as the argument passed, which can be cast to the appropriate type.
Question 6: Which C# keyword is used to prevent a Unity MonoBehaviour class from being inherited?
- static
- abstract
- sealed (Correct answer)
- readonly
Correct answer: sealed
The 'sealed' keyword prevents other classes from inheriting from the marked class.
Question 7: What happens if you call Destroy(gameObject) inside OnDestroy()?
- It causes infinite recursion
- It is ignored since destruction is already in progress (Correct answer)
- It destroys the object twice
- It throws a NullReferenceException
Correct answer: It is ignored since destruction is already in progress
Calling Destroy() on an object already being destroyed is safely ignored by Unity.
Which Unity method is called once per physics update, making it ideal for rigidbody force applications?