Coin Magnet
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 65 of 67.
The player walks around a field with five coins on it, carrying a magnet. A coin that comes within the magnet's range flies toward the player, and a coin that reaches the player is collected and counted. Coins farther away stay where they are until the player comes near them.
Write the whole game in one script, Magnet, on the player.
Challenge
HardWrite the Magnet script on the Player. The Inspector sets speed (5), range (3) and pullSpeed (8).
- While an arrow is held, the player moves at
speedunits per second: left and right along x, up and down along z. - The coins are the objects tagged
Coin. - Every frame, each coin closer than
rangeto the player moves toward the player atpullSpeedunits per second. Coins farther away do not move. - A coin closer than 0.5 to the player is collected: destroy it, add 1 to a count and log the count as
Coins: 1,Coins: 2and so on.
Press Play and sweep up the coins, then Check.
Try it yourself
using System.Collections.Generic;
using UnityEngine;
public class Magnet : MonoBehaviour
{
[SerializeField] private float speed = 5f;
[SerializeField] private float range = 3f;
[SerializeField] private float pullSpeed = 8f;
void Start()
{
}
void Update()
{
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Unity Scripting Basics
1Your First Script
Hello, UnityPlace the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube4Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot7Project: Catch the Star
The CatcherA Falling Star5Transforms and Hierarchy
Parents and ChildrenScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon