UCA Unity Scripting & Programming 3 — Questions and Answers
Question 1: Which of the following correctly declares a C# property with a private setter in a Unity script?
- public int Health { get; private set; } (Correct answer)
- public int Health { get; set; } private
- private public int Health { get; set; }
- public int Health { readonly get; set; }
Correct answer: public int Health { get; private set; }
Auto-properties in C# support access modifier asymmetry using 'public int Health { get; private set; }' syntax.
Question 2: What is the primary purpose of Unity's ScriptableObject?
- To attach scripts to scene GameObjects
- To store shared data assets independent of scene instances (Correct answer)
- To replace MonoBehaviour for all scripts
- To define custom physics materials
Correct answer: To store shared data assets independent of scene instances
ScriptableObjects are data containers saved as project assets, allowing data sharing across scenes without scene coupling.
Question 3: How do you correctly unsubscribe a method from a C# event in Unity to prevent memory leaks?
- event += Method;
- event.Remove(Method);
- event -= Method; (Correct answer)
- event.Clear();
Correct answer: event -= Method;
Using -= removes a delegate from an event, which is essential in OnDisable() or OnDestroy() to prevent memory leaks.
Question 4: What does the 'yield return new WaitForSeconds(2f)' statement do inside a Unity coroutine?
- Pauses execution of the coroutine for 2 seconds before continuing (Correct answer)
- Stops the coroutine permanently after 2 seconds
- Waits for 2 physics frames
- Delays the Start() method by 2 seconds
Correct answer: Pauses execution of the coroutine for 2 seconds before continuing
WaitForSeconds suspends coroutine execution for the specified duration then resumes from that point.
Question 5: In Unity, which method of the Input class checks if a key was pressed during this frame only?
- Input.GetKey()
- Input.GetKeyDown() (Correct answer)
- Input.GetKeyUp()
- Input.GetKeyPressed()
Correct answer: Input.GetKeyDown()
Input.GetKeyDown() returns true only on the single frame when the key transitions from up to down.
Question 6: What is the output of the following C# snippet: Debug.Log(10 / 3); in Unity?
- 3.333...
- 3 (Correct answer)
- 3f
- Error: integer division not allowed
Correct answer: 3
Integer division in C# truncates the decimal, so 10 / 3 equals 3, not 3.333.
Question 7: Which Unity class provides methods like Lerp() and Clamp() commonly used in game scripts?
- Vector3
- Transform
- Mathf (Correct answer)
- Physics
Correct answer: Mathf
Mathf is Unity's math utility class containing Lerp(), Clamp(), Abs(), and many other common math functions.
Which of the following correctly declares a C# property with a private setter in a Unity script?