简体   繁体   中英

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?

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 );
        }

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM