hmirza
hmirza

Reputation: 3

How to create a Score counter in Unity C#?

I am trying to create a Score counter for this Test game I am making in Unity using C#, but am getting stuck with some of the code...

Here's the code in question

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Script : MonoBehaviour
{

    void OnCollisionEnter(Collision collision)
    { 

        for(int i =0; i<3; i++)
            if (collision.collider.CompareTag("coin"))
            {
                Destroy(collision.gameObject);
                Debug.Log("Coins collected: " + i);
            }

    }

}

I want the Debug.Log to record the number of coins I am collecting eg. if the character in the game hits a coin I want debug.log to record it. If he hits another coin, I want the debug.log to increment the sum by 1.

I know I am doing the code wrong. Anyone know how to correct it?

Upvotes: 0

Views: 3376

Answers (1)

mahdi gholami
mahdi gholami

Reputation: 492

Try this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Script : MonoBehaviour
{
    int count = 0;
    void OnCollisionEnter(Collision collision)
    { 

    
        if (collision.collider.CompareTag("coin"))
        {
            count++;
            Destroy(collision.gameObject);
            Debug.Log("Coins collected: " + count );
        }

    }

}

Upvotes: 0

Related Questions