Tenta Flashcards
Gravity only operates along a fixed world vector. How could you simulate a planet orbiting the sun?
Rotate the GameObject by obtaining
- The position of the sun
- The axis of rotation
- Angular speed
then
transform.RotateAround(sun.position, Vector3.up, orbitspeed * Time.DeltaTime)
What is the code for orbiting a planet around the sun?
public Transform sun;
public float orbitSpeed;
void Update{
transform.RotateAround(sun.position, Vector3.up, orbitspeed*Time.DeltaTime); }
How can we add a star orbiting the planet that’s orbiting the sun?
GameObject star;
star.transform.RotateAround(transform.position, vector3.up, orbitSpeed*Time.DeltaTime);
How can we use state machines to structure game logic?
It organises game logic into different states, each with specific behaviours. Transitions between states are managed systematically -> Improving code clarity and scalability. Use switch cases
enum GameState {MainMenu, Playing, Paused)
GameState currState = GameState.MainMenu
How does the garbage collection in unity work?
When the managed heap fills up, meaning that there isn’t a space big enough for a new allocation of data, the garbage collector will run to try to make room for it.
When this happens, Unity will examine the heap, and remove any old data that no longer has any references to it.
Then if, after running the garbage collector, there still isn’t a space big enough for the data allocation, the heap will expand to make more room.
How can you write low garbage code in unity?
- Use object pooling to avoid frequent instantiation and destruction of objects
- Avoid allocating memory in performance-critical methods like Update()
How would you display (and update) a score on the screen while a game is being played, using the unity GUI?
- Add text (or TextMeshPro) to canvas
- Get references to the text objects in the code
public TextMeshPro scoreText;
public int score;
public void addScore (int points){
score += points;
scoreText.text = “Score: “ + score.ToString(); }
Explain Mark And Sweep
Mark: Start from the root/global references and recursively visit all reachable objects, marking the accessible
Sweep: Pass through “all” objects and delete those not marked as accessible
No other processing can be done which leads to frame rate drop
(Try to minimise GC calls)
How can we determine if zombie can see the player?
float dot = Vector3.dot(vec1,vec2)
1. Obtain the normalised vector
a) Zombie facing direction
Zombie.transform.forward
b) Direction from zombie to player
Vector3 diff = p1-p2
Vector3 dir = diff.normalised
2. If dot of a) and b) is greater than 0 -> the zombie can see the player
Explain ScreenSpace: Overlay and ScreenSpace: Camera
Overlay: Canvas scaled to fit and then rendered without reference to the scene or camera (always drawn over other graphics)
Camera: Rendered as a plane A DISTANCE from the camera (objects will be rendered over it)
How can you spawn sparks using the parameters of a collision?
(In OnCollisionEnter)
for int i in collision.contacts.length{
ContactPoint cp = collision.contacts[i]
GameObject go = Instantiate(GameManager.instance, sparkEmitterPrefab)
go.transform.position = cp.point;
go.transform.LookAt(cp.point+cp.normal)
What is a coroutine in Unity?
Special functions that can pause their execution (not threads). When they are activated, they will execute up until the next yield statement and then pause until it’s resumed.
Good for:
-Making things happen step-by-step
-Writing routines that happen over time
- Wrirting routines that have to wait for another operation to finish
Explain colliders, triggers and rigidbodys
Collider components define the shape of an object for the purposes of physical collisions.
Colliders and rigidbodies will physically respons to impacts
Triggers will not not. Triggers enable game-logic interaction when you don’t want physical collision responses. Invisible components that are activated
(triggered) when a character or other object
passes inside them
Colliders (but not rigidbodies) will notify their impacts but not crash
Explain Screen Space, Viewport Space and World Space
Screen space: Bottom-left (0,0), top right (1,1). If using vector3, z-coordinate are world units in front of the camera (good for mouse positioning)
Viewport space: Normalised and relative to the camera (good for UI elements)
World space: Global coordinates
Example find mouse pos in world coord -> Camera.main.ScreenToWorldPoint(Input.mouseposition)
How could you rotate a gameobject a certain amount of degrees around WORLD y axis?
GameObject go:
go.Transform.Rotate(0f, xf, 0f, space.world)
If y-axis self it would be “space.self” instead
Move a GameObject 6 units downwards in the world’s coordinate system
gameObject.transform.position += Vector3.down * 6;
Move a GameObject 7 units directly towards another GameObject
Vector3 direction = (targetObject.transform.position - gameObject.transform.position).normalized;
gameObject.transform.position += direction * 7;
Move a GameObject 10 units forward in whatever direction it is facing:
go.transform.position += go.transform.forward*10;
OR
(if maybe global coordinates)
gameObject.transform.Translate(Vector3.forward * 10, Space.Self);
How can you find the distance between two GameObjects?
float distance = Vector3.Distance(obj.transform.position, pos);
OR
float distance = (go1.transform.position - go2.transform.position).magnitude
Explain The Object Pool pattern – why it’s useful and how it operates
The Object Pool pattern is a design approach used to efficiently manage the creation and reuse of objects that are expensive to instantiate and destroy. Instead of repeatedly allocating and deallocating objects, a pool of pre-instantiated objects is maintained. These objects can be reused when needed and returned to the pool when not in use
-Performance: Reduces the overhead of frequent object instantiation and garbage collection, which is critical in performance-sensitive environments like games.
-Memory Efficiency: Limits the total number of objects in memory by reusing instances.
-Consistency: Ensures stable performance, especially in scenarios with frequent object creation, like spawning bullets or enemies
-Create a pool of objects at initialization.
-When needed, retrieve an object from the pool (activate it).
-Once no longer required, return the object to the pool (deactivate it).
-Grow the pool dynamically if all objects are in use.
Under what circumstances does the OnCollisionEnter method get executed in a MonoBehaviour-derived script?
When Collider-To-Collider collides (interacts).
The Collider argument is simply a reference to the trigger component that interacted with ours
How does Coroutines integrate with the game loop?
When a Coroutine is started, Unity schedules its execution alongside the Game Loop. The yield keyword pauses the Coroutine and lets the Game Loop continue its normal operations. Once the condition specified by the yield statement is met (e.g., waiting for a frame, a condition, or a time delay), the Coroutine resumes from where it left off.
Write a Coroutine which carries out a sequence of actions over time:
- Gradually (frame by frame) moves its local game object at a speed of 1 metre
per second towards a Vector3 position.
- After the game object arrives at the position, waits 2 seconds.
- Then moves the game object in the same way to a second Vector3 position.
void Start() {
// Start the coroutine
StartCoroutine(MoveAndWaitCoroutine());
}
IEnumerator MoveAndWaitCoroutine() { // Move to the first position yield return StartCoroutine(MoveToPosition(position1)); // Wait for 2 seconds yield return new WaitForSeconds(2f); // Move to the second position yield return StartCoroutine(MoveToPosition(position2)); } IEnumerator MoveToPosition(Vector3 targetPosition) { // Continue moving until the GameObject is very close to the target while (Vector3.Distance(transform.position, targetPosition) > 0.01f) { // Move the GameObject closer to the target position at 1 meter/second transform.position = Vector3.MoveTowards( transform.position, targetPosition, 1f * Time.deltaTime ); // Wait for the next frame yield return null; } // Snap to the exact target position to avoid precision issues transform.position = targetPosition; }
Explain how Unity’s MonoBehaviour class provides tight integration with the Game Loop. Refer to appropriate methods of the MonoBehaviour class in your answer
Unity automatically calls these methods as part of its Game Loop, ensuring efficient execution of game logic at appropriate times. Developers don’t need to manually hook these methods into the loop, simplifying development and maintaining performance consistency
Start ()
Awake()
Update()
LateUpdate()
StartCoroutine()