Coin Magnet
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 81 of 85.
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 a coin magnet that pulls in the coins within range.
- Move with
Input.GetAxisRaw: Horizontal on x, Vertical on z, atspeed. - Each object tagged
Coincloser thanrangemoves toward the player withVector3.MoveTowardsatpullSpeed. - Closer than
0.5, it is collected: destroy it, count it and log"Coins: " + count.
Press Play and sweep the field. 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()
{
}
}
All lessons in Unity Scripting Basics
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground