Skip to content

Lesson 4

Collect coins

Find out when the player touches a coin, then make the coin disappear.

25 minDraft

Draft lesson: nobody has followed it from start to finish in the editor yet, so a step may not match what you see.

Video coming soon

We are making a video for this lesson. For now, follow the steps below!

In this lesson you will

  • Know when two things touch
  • Make a GameObject disappear
  • Use one script on many coins

What you will make

Coins that disappear when the player touches them.

1. Make a coin

  1. Make a sprite called Coin, with a coin picture.
  2. Add a Circle Collider. That is its shape.

Do not give it a Physics Body. The coin floats, and the player can go through it.

2. Add a script to the coin

Click Add Component, type Coin and choose Create script "Coin". Replace its code with this:

export default class Coin {
  private readonly mGameObject: GameObject;

  constructor(gameObject: GameObject) {
    this.mGameObject = gameObject;
  }

  initialize(): void { }

  update(args: NUpdateArgs): void { }

  onCollisionEnter(other: Collider): void {
    if (other.GameObject.Name === 'Player') {
      GameObject.Destroy(this.mGameObject);
    }
  }

  destroy(): void { }
}

Save, then Play. Walk into the coin. It's gone!

How does it work?

  • onCollisionEnter runs when something starts touching the coin.
  • other is the shape that touched it. We check that it is the Player.
  • GameObject.Destroy(...) removes the coin from the game.

Many coins

Click the coin and press Ctrl + D a few times. Move the copies around. Every copy has the same script, so every coin works!

Picture coming soonMany coins in the Game panel

Try this

  • Make a path of coins that goes up a hill.
  • Make a coin that only disappears when you jump into it. (Hard!)

Try it here

Coming soon

Your mission

Put three coins in the level, then collect them all.

Soon, a small piece of the editor will be right here, so you can practise without leaving the lesson. For now, try it in the editor!