Objects: Creation, Deletion and Time
Drive a hero with the mouse or keyboard, fire eggs, and keep ten enemies in the world. Along the way: prefabs, collisions, and frame time vs. real time. Due date: see the course website.
Objective
Now that you're more comfortable with the Unity editor, let's create and destroy game objects at run time, detect collisions between them, and get a feel for the difference between frame time and wall-clock (real) time.
Coverage
◆Prefabs
- Create a prefab in the editor
- Create (
Instantiate) and delete (Destroy) objects at run time
↻Transform
- Set position and rotation
- Move along an object's own
transform.up
⌨User interaction
- World position from the mouse
- Keyboard polling with the Input System
- On-screen status text (TextMeshPro)
✦Concepts
- The camera and the visible world bounds
- Frame time vs. real time; rates per second
- Collisions and responses; randomness
What to build
Play my solution first. There are three kinds of objects: the hero, the eggs it fires, and the enemies. All speeds and rates below are per second, so multiply them by Time.smoothDeltaTime each frame (see EX1 if you need a refresher).
Camera and sprites
- Main Camera: Orthographic, Size 100. The world spans y = −100 to +100.
- The hero, eggs and enemies must each be a sprite made from an image (Texture Type: Sprite (2D and UI)). Built-in shapes and 3D objects don't count.
- Sizes below are Transform Scale values, as in EX1. How big an object looks in world units also depends on its image's pixel size and Pixels Per Unit: my solution uses 128, so the 180-pixel hero at scale 5 is about 7 units wide.
Use any images you like, or the ones in my solution:
Hero
Transform Scale (5, 5, 1).
| Key | Behavior |
|---|---|
| M | Toggles between mouse and keyboard control. Mouse mode is the default (it's easy for me to test). |
| Mouse mode | The hero's position follows the mouse at all times. |
| Keyboard mode | The hero moves along its own transform.up. Its initial speed is 20 units/second. |
| W / S held | Keyboard mode: speed increases / decreases gradually at 10 units/second² (i.e., by 10 units/second every second held). Keep the speed within [0, 100]. |
| A / D held | Turns the hero left / right at 45°/second (in both modes). |
| Space held | Fires one egg every 0.2 seconds (in both modes). |
Eggs
- Transform Scale (1, 1, 1), created from a prefab at the hero's position.
- Aligned with the hero's
transform.upat the moment it's fired, and then travels along its owntransform.upat 40 units/second. - An egg is destroyed when it either leaves the world bounds or hits an enemy.
Enemies
- Transform Scale (5, 5, 1), created from a prefab. They don't move in this exercise.
- There are always exactly 10 enemies, each placed at a random position within the central 90% of the world bounds.
- As soon as an enemy is destroyed, spawn a new one under the same rules.
| When an enemy touches… | Response |
|---|---|
| the hero | The enemy is destroyed. |
| an egg | The egg is destroyed and the enemy loses 20% of its current energy: multiply its alpha by 0.8. The 4th egg hit destroys the enemy. |
Color is a struct, so GetComponent<SpriteRenderer>().color.a *= 0.8f; doesn't compile. Copy the color, change the copy, and assign it back:
SpriteRenderer r = GetComponent<SpriteRenderer>();
Color c = r.color;
c.a *= 0.8f;
r.color = c;
Status text and quitting
Show the application status on screen with a UI Text (TextMeshPro) object, updated every frame. It must include:
- Hero: control mode (Mouse/Keyboard), and the number of enemies the hero has touched
- Egg: the number of eggs currently in the world
- Enemy: the current enemy count (always 10), and the total number destroyed
For example:
HERO: Drive(Mouse) TouchedEnemy(3)
EGG: OnScreen(12)
ENEMY: Count(10) Destroyed(7)
Q quits the application. As in EX1, this only works in the built EXE.
Hints
using UnityEngine.InputSystem;
Vector3 p = Camera.main.ScreenToWorldPoint(Mouse.current.position.ReadValue());
p.z = 0f;
transform.localPosition = p;
Use Keyboard.current.wKey.isPressed for held keys and Keyboard.current.mKey.wasPressedThisFrame for toggles. Don't use Input.GetAxis(); it throws an exception in Unity 6 projects.
float dt = Time.smoothDeltaTime;
mSpeed += kAcceleration * dt; // W held: 10 units/second²
transform.Rotate(0f, 0f, kTurnRate * dt); // A held: 45 degrees/second
transform.localPosition += mSpeed * dt * transform.up;
Remember the time of the last shot (Time.time) and only fire again once 0.2 seconds have passed. Create the egg with Instantiate(eggPrefab, transform.position, transform.rotation) so it starts with the hero's orientation.
Follow Module 2.6. For OnTriggerEnter2D to be called, give the hero and egg a Rigidbody2D (Body Type Kinematic) and a BoxCollider2D with Is Trigger checked, and give the enemy a BoxCollider2D with Is Trigger checked.
The world is Camera.main.orthographicSize high on each side of the camera, and orthographicSize * Camera.main.aspect wide on each side.
A single Game Manager object (see Module 2.3) is a good place to keep the counts and spawn enemies. Eggs can report their creation and destruction to it from Start() and OnDestroy().
Stretch goal (optional, not graded)
- Keep the hero inside the world bounds in keyboard mode.
- Show the hero's current speed in the status text.
Submission
- A zip file named
YourNameEX2.zipcontaining your entire project: every file in Assets, Packages and ProjectSettings, and nothing more. - A separate folder with your PC EXE build. We'll double-click the EXE to run your project.
Self-check before you submit
- I unzipped my zip into a new, empty folder and opened it in Unity 6000.3.11f1. It opens and runs.
- The zip has only Assets, Packages and ProjectSettings.
- Double-clicking the EXE runs the game, and Q quits it.
- The hero, eggs and enemies are sprites made from images.
- Holding Space fires about 5 eggs per second.
- The egg count in the status text goes back to 0 once all eggs have left the world or hit enemies.
- Enemy count always shows 10; an enemy fades on each egg hit and disappears on the 4th.
- In keyboard mode, holding S stops the hero (speed 0) rather than reversing it.
- My hero script has the 2–3 sentence explanation comment at the top.
Credit distribution
| Item | Sub-item | Category |
|---|---|---|
| Camera setting: Orthographic, Size 100 | 5% | |
| Scene setup: hero (scale 5), egg and enemy prefabs, all image sprites | 5% | |
| Hero | 25% | |
| M toggles mouse/keyboard control (mouse is the default) | 3% | |
| Mouse mode: position follows the mouse | 4% | |
Keyboard mode: moves along transform.up, initial speed 20 units/second | 3% | |
| Keyboard mode: W/S change speed gradually at 10 units/second², within [0, 100] | 5% | |
| A/D turn at 45°/second | 5% | |
| Space fires one egg every 0.2 seconds | 5% | |
| Eggs | 15% | |
Scale 1, aligned with the hero's transform.up when fired | 5% | |
Travel along their transform.up at 40 units/second | 5% | |
| Destroyed on leaving the world bounds (checked with the egg count) | 5% | |
| Enemies | 25% | |
| Always exactly 10 in the world | 5% | |
| Spawned (and re-spawned) at random within 90% of the world bounds | 5% | |
| Destroyed on touching the hero | 5% | |
| Egg hit: egg destroyed, enemy alpha × 0.8 | 5% | |
| Destroyed by the 4th egg hit | 5% | |
| On-screen status text | 10% | |
| Hero: control mode and number of enemies touched | 4% | |
| Egg: number currently in the world | 3% | |
| Enemy: current count and number destroyed | 3% | |
| Q quits the application (in the EXE) | 5% | |
| Proper submission | 10% | |
| Zip unzips and runs in the editor, with only the four project folders | 5% | |
| Separate EXE folder; double-click runs the game | 5% | |
| Total | 100% |
Egg.png
Plane.png