Unity游戏分数

时间:2017-04-23 21:32:47

标签: c# unity3d 2d

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

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

    }

}

1 个答案:

答案 0 :(得分:0)

这真的很容易。创建一个检测ClickObjects上的点击的脚本。您可以使用OnPointerClick。从该脚本获取Score脚本的实例,然后在调用OnPointerClick时增加分数变量。

务必将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()功能。有关详细信息,请参阅here