我想创建计分系统(Unity 2D)

时间:2018-12-04 17:50:25

标签: c# unity3d 2d scoreloop

我正在制作《吃豆人》这样的2D游戏。但是,我在创建评分系统时遇到了一些问题。

我想在吃豆人吃硬币时更新分数

我制作了名为“ ScoreManager”的C#脚本

这是代码

[INFO 2018-12-04 23:00:08,472 basehttp] "GET /health_check/ HTTP/1.1" 200 96
[<django.db.backends.mysql.base.DatabaseWrapper object at 0x7f2c5fb1a0b8>]
[INFO 2018-12-04 23:00:09,017 basehttp] "GET /health_check/ HTTP/1.1" 200 96
[<django.db.backends.mysql.base.DatabaseWrapper object at 0x7f2c5fa88d30>]

当我在Unity引擎中玩游戏时,此代码运行良好

但是,我不知道如何在Pacdot脚本中设置ScoreValue。

这是Pacdot代码

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

public class ScoreManager : MonoBehaviour {

    static int score = 0;

    public static void setScore(int value)
    {
        score += value;
    }

    public static int getScore()
    {
        return score;
    }

    void OnGUI ()
    {
        GUILayout.Label("Score: " + score.ToString());
    }
}

我还添加了C#脚本(Pacmanbehaviour)

using UnityEngine;
using System.Collections;

public class Pacdot : MonoBehaviour {

    public int score = 10;

    void OnTriggerEnter2D(Collider2D co) {
        if (co.name == "pacman")
        {           
            Destroy(gameObject);
        }

    }
}

1 个答案:

答案 0 :(得分:1)

ScoreManager script needs to live as a game object, or as a component in a game object. Then you can add it as a field in your Pacdot class.

It'll be something like this below, but finding the specific game object the script is attached to will depend on how you have it designed (the "find by tag" approach won't work unless you have a game object with ScoreManager attached, with that tag).

using UnityEngine;
using System.Collections;

public class Pacdot : MonoBehaviour {

    public int score = 10;
    private ScoreManager _score = GameObject.findGameObjectWithTag("scoreKeeper").GetComponent<ScoreManager>();

    void OnTriggerEnter2D(Collider2D co) {
        if (co.name == "pacman")
        {           
            _score.SetScore(score);
            Destroy(gameObject);
        }

    }
}

I would also look at the answer @derHugo linked to--a lot of ways to accomplish this, depending on your needs/design.