Scripting the CoinPickup Component

We’re going to create a Component that we can attach to our coins so that the player can interact with them. With one of the coin Prefabs selected, create a new script and name it “CoinPickup.” Enter the code shown in Listing 8.3.

Listing 8.3 The CoinPickup Script

public class CoinPickup : MonoBehaviour{  public int coinValue = 1;  void OnTriggerEnter2D(Collider2D collider)  {    if(collider.tag == "Player")    {      Destroy(this.gameObject);    }  }}

Our script will check to see when the player enters the trigger and will destroy the coin, giving the appearance that it has been “picked up.” The public variable also allows us to set the value of the coin, which will come into ...

Get Learning 2D Game Development with Unity®: A Hands-On Guide to Game Creation now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.