Menu
CoddyTech

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 icon

Challenge

Hard

Write a coin magnet that pulls in the coins within range.

  1. Move with Input.GetAxisRaw: Horizontal on x, Vertical on z, at speed.
  2. Each object tagged Coin closer than range moves toward the player with Vector3.MoveTowards at pullSpeed.
  3. 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

Practice on your own: Unity playground