ACTIVITY 4: How to create a simple coin counter in your Unity game?

So guys, today I made a game by collecting coins and converting it as score on a gameplay. So still, we have to apply the previous scripts that we had already done. We modified the Player Controller's script, which I will tell you in a moment. So for now let's get start.

Maybe you also want to check out my previous unity game blog,

here is the link: HOW TO MOVE AND ROTATE AN OBJECT IN UNITY

So the objective of the game is to collect coins before the enemy obtains even one. You have to head start and to defeat that by just bumping and destroying the enemy which will add extra points, otherwise you'll get a low score in game. And that is what were going to do, to create a coin counter game using Unity in 2D.

To start things out, we must first get our sprites. We'll be using a Spaceship as our Player, while replacing the obstacles with coins. And we also add an additional Object, a UFO as our enemy for the player which will deduced the score once it had collected a coin. So to get perfect points, you must be ahead and chase the UFO, the UFO will be destroyed once it has bumped with your ship which adds 20pts. Added with that difficulty, we have a special coin, if obtained it will add a score, if not - it will deduce your score, and the rest of the coins if obtained will add score, otherwise if the UFO had obtain 1 or more, each ordinary coin is equivalent to 1 or -1 of what is collected by our UFO . That equates to 50 pts in total, 25 ordinary coins named in numerical order as "coin 1-25" and 1 special coin named "coin pt5".








Once we had place our assets and sprites and also the background and barrier or boarder, were going to apply a code to our Player, which again is a Player Controller. The difference is that the score counter for the player was also joined and included inside of player control later. For now well just add components to our player, coins, boarders and enemy (Rigidbody2D - all except boarders, CircleCollider2D - only for the coins, BoxCollider2D - for Player and UFO only). 





If you're done with that, then we must work with our Score to appear in our interface. First we have to go to Hierarchy - right click - UI - text, then name text as ScoreText, put on the text window "Score : " this will now appear on the Canvas, make sure you adjust the color and font size. After that you'll see a canvas in our interface which also is indicated in the Hierarchy panel. On the canvas, you can click and drag to position the textbox containing "Score : ", you may put it on the top center of the Canvas, or put it where you like. 









Once done, we have to make a script for our ScoreText, to count and add points.


Here's the script for Score:


using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using UnityEngine.UI;


public class Score : MonoBehaviour

{

    public static int scoreAmount;

    private Text scoreText;

    

    void Start()

    {

        scoreText = GetComponent<Text>();

        scoreAmount = 0;

    }

    

    void Update()

    {

        scoreText.text = "Score : " + scoreAmount;

    }

}



Then now I'll let you know what did I and why I change the PlayerController.

Why did I joined Player Controller with Score Amount? well because when I did compiled Score Manager separate, I came to a hard situation where the Player can't touch the coin and just overlays and even though I set the coin in trigger and also named as what is also in our code, both codes are in placed in our Player, but still the coin hasn't been destroyed and even add a score, it just overlays, even after checking if the Player was in a different layer, which is not (they were layered the same). 

So I think that it might be ok if I join the two scripts. So I copied a part of the Score Amount script and put it on our PlayerController under private void, when I tried to put just the OnTriggerEnter2D script to Player Controller, the code work and the Player can now touch the coin and destroy it while adding a point in our score. So I was relieved by that. 

With that said, we can change what point does an object equates to. For example coin 1 = 1pt, while coin pt5 = 5pts, and UFO is = to 20pts. We just need to change the scoreAmount = N so that we can adjust our pointers or score. 

About the OnTriggerEnter2D script, we have to put cases (all named by the name of the sprites) by duplicating it. On coins 1-25, I put 1pt for each, while coin pt5 has 5pts, and lastly the UFO with 20pts.


Code for PlayerController(with ScoreAmounts): *you may just copy one of the coins scripts, then name it to your coin or object.*


using System.Collections;

using System.Collections.Generic;

using UnityEngine;


public class PlayerController : MonoBehaviour

{

    public float speed;

    private Rigidbody2D rb2d;

    private Vector2 moveVelocity;


    void Start()

    {

        rb2d = GetComponent<Rigidbody2D>();

    }


    void Update()

    {

        Vector2 moveInput = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));

        moveVelocity = moveInput.normalized * speed;

    }

    void FixedUpdate()

    {

        rb2d.MovePosition(rb2d.position + moveVelocity * Time.fixedDeltaTime);

    }

    private void OnTriggerEnter2D(Collider2D collision)

    {

        switch (collision.name)

        {

            case "coin 1":

                Score.scoreAmount += 1;

                Destroy(collision.gameObject);

                break;

            case "coin 2":

                Score.scoreAmount += 1;

                Destroy(collision.gameObject);

                break;

            case "coin 3":

                Score.scoreAmount += 1;

                Destroy(collision.gameObject);

                break;

            case "coin 4":

                Score.scoreAmount += 1;

                Destroy(collision.gameObject);

                break;

            case "coin 5":

                Score.scoreAmount += 1;

                Destroy(collision.gameObject);

                break;

            case "coin 6":

                Score.scoreAmount += 1;

                Destroy(collision.gameObject);

                break;

            case "coin 7":

                Score.scoreAmount += 1;

                Destroy(collision.gameObject);

                break;

            case "coin 8":

                Score.scoreAmount += 1;

                Destroy(collision.gameObject);

                break;

            case "coin 9":

                Score.scoreAmount += 1;

                Destroy(collision.gameObject);

                break;

            case "coin 10":

                Score.scoreAmount += 1;

                Destroy(collision.gameObject);

                break;

            case "coin 11":

                Score.scoreAmount += 1;

                Destroy(collision.gameObject);

                break;

            case "coin 12":

                Score.scoreAmount += 1;

                Destroy(collision.gameObject);

                break;

            case "coin 13":

                Score.scoreAmount += 1;

                Destroy(collision.gameObject);

                break;

            case "coin 14":

                Score.scoreAmount += 1;

                Destroy(collision.gameObject);

                break;

            case "coin 15":

                Score.scoreAmount += 1;

                Destroy(collision.gameObject);

                break;

            case "coin 16":

                Score.scoreAmount += 1;

                Destroy(collision.gameObject);

                break;

            case "coin 17":

                Score.scoreAmount += 1;

                Destroy(collision.gameObject);

                break;

            case "coin 18":

                Score.scoreAmount += 1;

                Destroy(collision.gameObject);

                break;

            case "coin 19":

                Score.scoreAmount += 1;

                Destroy(collision.gameObject);

                break;

            case "coin 20":

                Score.scoreAmount += 1;

                Destroy(collision.gameObject);

                break;

            case "coin 21":

                Score.scoreAmount += 1;

                Destroy(collision.gameObject);

                break;

            case "coin 22":

                Score.scoreAmount += 1;

                Destroy(collision.gameObject);

                break;

            case "coin 23":

                Score.scoreAmount += 1;

                Destroy(collision.gameObject);

                break;

            case "coin 24":

                Score.scoreAmount += 1;

                Destroy(collision.gameObject);

                break;

            case "coin 25":

                Score.scoreAmount += 1;

                Destroy(collision.gameObject);

                break;

            case "coin pt5":

                Score.scoreAmount += 5;

                Destroy(collision.gameObject);

                break;

            case "UFO":

                Score.scoreAmount += 20;

                Destroy(collision.gameObject);

                break;


        }

    }

}


The next code to apply is for our UFO, so the code allows us to make an object move independently in random directions. But the UFO must not only just move around and do nothing, it also as an enemy must snitch our points, on that regard I mean snitch your coins and points. So to allow that we'll also add a scoreAmount to it but instead of adding points when it hits a coin, it deduces the points or score. Which means to put a negative number to each coin, and special coin on script.

Same with the case with our PlayerController, we will merging two codes, one is the code for the ObjectMove and the other is our OnTriggerEnter2D from scoreAmounts to put as UFO score script. You may also adjust the movement duration, and delay of the UFO on the script. I also added a move script to it to mimic teleportation effect by adjusting aptitude and frequency although on a different script.




Code for ObjectMove(with ScoreAmounts)  *you may just copy one of the coins scripts, then name it to your coin or object.*


using System.Collections;

using System.Collections.Generic;

using UnityEngine;


public class ObjectMove : MonoBehaviour

{

    private float movementDuration = 3.5f;

    private float waitBeforeMoving = 2.5f;

    private bool hasArrived = false;

    private Coroutine moveCoroutine = null;


    private void Update()

    {

        if (!hasArrived)

        {

            hasArrived = true;

            float randX = Random.Range(-6.0f, 6.0f);

            float randZ = Random.Range(-6.0f, 6.0f);

            moveCoroutine = StartCoroutine(MoveToPoint(new Vector3(randX, -1.504f, randZ)));

        }

        if (Input.GetMouseButtonDown(0))

            StopMovement();

    }


    private IEnumerator MoveToPoint(Vector3 targetPos)

    {

        float timer = 0.0f;

        Vector3 startPos = transform.position;


        while (timer < movementDuration)

        {

            timer += Time.deltaTime;

            float t = timer / movementDuration;

            t = t * t * t * (t * (6f * t - 15f) + 10f);

            transform.position = Vector3.Lerp(startPos, targetPos, t);


            yield return null;

        }


        yield return new WaitForSeconds(waitBeforeMoving);

        hasArrived = false;

    }


    private void StopMovement()

    {

        if (moveCoroutine != null)

            StopCoroutine(moveCoroutine);

    }


    public void OnCollisionEnter(Collision collision)

    {

        if (collision.gameObject.CompareTag("sphereTag"))

            StopMovement();

    }

    private void OnTriggerEnter2D(Collider2D collision)

    {

        switch (collision.name)

        {

            case "coin 1":

                Score.scoreAmount += -1;

                Destroy(collision.gameObject);

                break;

            case "coin 2":

                Score.scoreAmount += -1;

                Destroy(collision.gameObject);

                break;

            case "coin 3":

                Score.scoreAmount += -1;

                Destroy(collision.gameObject);

                break;

            case "coin 4":

                Score.scoreAmount += -1;

                Destroy(collision.gameObject);

                break;

            case "coin 5":

                Score.scoreAmount += -1;

                Destroy(collision.gameObject);

                break;

            case "coin 6":

                Score.scoreAmount += -1;

                Destroy(collision.gameObject);

                break;

            case "coin 7":

                Score.scoreAmount += -1;

                Destroy(collision.gameObject);

                break;

            case "coin 8":

                Score.scoreAmount += -1;

                Destroy(collision.gameObject);

                break;

            case "coin 9":

                Score.scoreAmount += -1;

                Destroy(collision.gameObject);

                break;

            case "coin 10":

                Score.scoreAmount += -1;

                Destroy(collision.gameObject);

                break;

            case "coin 11":

                Score.scoreAmount += -1;

                Destroy(collision.gameObject);

                break;

            case "coin 12":

                Score.scoreAmount += -1;

                Destroy(collision.gameObject);

                break;

            case "coin 13":

                Score.scoreAmount += -1;

                Destroy(collision.gameObject);

                break;

            case "coin 14":

                Score.scoreAmount += -1;

                Destroy(collision.gameObject);

                break;

            case "coin 15":

                Score.scoreAmount += -1;

                Destroy(collision.gameObject);

                break;

            case "coin 16":

                Score.scoreAmount += -1;

                Destroy(collision.gameObject);

                break;

            case "coin 17":

                Score.scoreAmount += -1;

                Destroy(collision.gameObject);

                break;

            case "coin 18":

                Score.scoreAmount += -1;

                Destroy(collision.gameObject);

                break;

            case "coin 19":

                Score.scoreAmount += -1;

                Destroy(collision.gameObject);

                break;

            case "coin 20":

                Score.scoreAmount += -1;

                Destroy(collision.gameObject);

                break;

            case "coin 21":

                Score.scoreAmount += -1;

                Destroy(collision.gameObject);

                break;

            case "coin 22":

                Score.scoreAmount += -1;

                Destroy(collision.gameObject);

                break;

            case "coin 23":

                Score.scoreAmount += -1;

                Destroy(collision.gameObject);

                break;

            case "coin 24":

                Score.scoreAmount += -1;

                Destroy(collision.gameObject);

                break;

            case "coin 25":

                Score.scoreAmount += -1;

                Destroy(collision.gameObject);

                break;

            case "coin pt5":

                Score.scoreAmount += -10;

                Destroy(collision.gameObject);

                break;

        }

    }

}



Last code to apply is for the special coin. So I decided to put a previous code for its movement. I want that coin to move up and down which the code allows us to do. I also change the hue to green to make the coin stand out and look different from other coins.





Here's a code for Move(for the special coin, and to be also added to our UFO for teleportation effect):


using System.Collections;

using System.Collections.Generic;

using UnityEngine;



public class Move : MonoBehaviour

{

    public float freq;

    public float amp;

    Vector3 posOffset = new Vector3();

    Vector3 tempPos = new Vector3();

    void Start()

    {

        freq = Random.Range(freq - 1, freq + 1);

        amp = Random.Range(amp - 1, amp + 1);

        posOffset = transform.position;

    }

    void Update()

    {

        tempPos = posOffset;



        transform.position = new Vector3(transform.position.x, tempPos.y + Mathf.Sin(Time.fixedTime * Mathf.PI * freq) * amp, transform.position.z);

    }


}


If applied, then check if the sprites has rigidbody2D and circlecollider2D(for our coins only) and boxcollider2D on our Player and UFO.





Try playing it to check the speed of the Player and how the UFO and the special coin moves, and if the coins are being collected and added as points. Then were done, we have now a coin counter 2D game in Unity.


WATCH THE VIDEO BELOW




Comments

Popular Posts