Menu
CoddyTech

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 icon

Challenge

Hard

Write 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 speed units 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 range to the player moves toward the player at pullSpeed units 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: 2 and 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()
    {
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Scripting Basics