统一游戏分数

Unity Game Score

我知道有很多关于统一分数等的问题,但是我发现很难真正为我的游戏构建代码并且已经查看了大量的 YouTube 教程和博客帖子。我想知道是否有人可以帮助我添加一个分数,这样每次我在我的隐藏对象游戏中单击我的一个对象时它都会提供一个分数。我真的很感激。到目前为止,我已经添加了一个名为Score.cs的单独脚本。代码如下所示。然后我将它添加到我的背景图片并将脚本包含到每个对象中我的分数文本在 canvas 内,目前不计算任何被点击的对象。

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

public class Score : MonoBehaviour {

    public Text scoreText;
    public int gameObject;

    private int score;
    // Use this for initialization

    void Start () {
        score = 0;
        UpdateScore ();
    }
    void OnMouseDown () {
        score += gameObject;
        UpdateScore ();
    }
    // Update is called once per frame
    void UpdateScore () {
        scoreText.text = "Score:\n" + score;

    }
}

!***** 编辑 (Score.cs) *****!

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

public class Score : MonoBehaviour {

    public Text scoreText;
    public int gameObject;

    public int score;
    // Use this for initialization

    void Start () {
        score = 0;
        UpdateScore ();
    }
    void OnMouseDown () {
        score += gameObject;
        UpdateScore ();
    }
    // Update is called once per frame
    void UpdateScore () {
        scoreText.text = "Score:\n" + score;

    }
}

!****** Clicker.cs ******!

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

public class Clicker : MonoBehaviour, IPointerClickHandler
 {

    Score score;

    void Start()
    {
        addPhysics2DRaycaster();
        //Get Score Script Instance
        string scoreObject = "gameObject";
        score = GameObject.Find(scoreObject).GetComponent<Score>();
    }
    void addPhysics2DRaycaster()
    {
        Physics2DRaycaster physicsRaycaster = GameObject.FindObjectOfType<Physics2DRaycaster>();
        if (physicsRaycaster == null)
        {
            Camera.main.gameObject.AddComponent<Physics2DRaycaster>();
        }
    }

    public void OnPointerClick(PointerEventData eventData)
    {
        //Click detected. Increment score
        score.score++;
        Debug.Log("Clicked: " + eventData.pointerCurrentRaycast.gameObject.name);

    }

}

这真的很简单。创建一个脚本来检测您的 GameObjects 上的点击。您可以为此使用 OnPointerClick。从该脚本获取 Score 脚本的实例,然后在调用 OnPointerClick 时递增 score 变量。

确保将 private int score; 更改为 public int score;

将脚本附加到每个要检测点击的对象。

public class Clicker : MonoBehaviour, IPointerClickHandler
{
    Score score;

    void Start()
    {
        //Get Score Script Instance
        string scoreObject = "GameObjectScoreIsAttachedTo";
        score = GameObject.Find(scoreObject).GetComponent<Score>();
    }

    public void OnPointerClick(PointerEventData eventData)
    {
        //Click detected. Increment score
        score.score++;

    }
}

如果您的对象是2D,您将需要添加addPhysics2DRaycaster()功能。如果是 3D 则需要添加 addPhysicsRaycaster() 函数。有关详细信息,请参阅