如何链接我的C#脚本,以便项目计数影响Unity游戏中的得分?

时间:2018-10-06 02:46:51

标签: c# unity3d

我正在努力做到这一点,以便收集物品会导致分数增加。在仔细阅读Unity文档之后,我编写了以下C#脚本。 CollectableItem.cs附加到游戏中的项目。 ScoreBoard.cs附加到UI显示。我收到错误消息,“'ScoreBoard.score'由于其保护级别而无法访问。”如果我将ScoreBoard.cs中的变量设为公共,则会收到另一条错误消息:“非静态字段,方法或属性'ScoreBoard.score'需要对象引用。”

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

public class CollectibleItem : MonoBehaviour {

    [SerializeField] private string itemName;
    [SerializeField] private int pointsValue;

    void OnTriggerEnter(Collider other) {
        Managers.Inventory.AddItem(itemName);
        Destroy(this.gameObject);
        ScoreBoard.score += pointsValue;
    }
}


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

public class ScoreBoard : MonoBehaviour {

    [SerializeField] private Text scoreLabel;
    private int score;

    void Start () {
        score = 0;
    }

    void Update () {
        scoreLabel.text = "Score: " + score.ToString();
    }
}

更新:这是CollectibleItem.cs上的2。现在,我被告知在当前上下文中不存在“木板” ...

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

public class CollectibleItem : MonoBehaviour {
    [SerializeField] private string itemName;
    [SerializeField] private int pointsValue;

    void Start() {
        var uiObject = GameObject.Find("Timer");
        ScoreBoard board = uiObject.GetComponent<ScoreBoard>();
    }

    void OnTriggerEnter(Collider other) {
        Managers.Inventory.AddItem(itemName);
        Destroy(this.gameObject);
        board.score += pointsValue;
    }
}

1 个答案:

答案 0 :(得分:2)

这不起作用,因为您对ScoreBoard类进行了静态访问。这意味着您尝试更改ScoreBoard类的变量。您要做的是更改实例之一上的变量。创建UI对象时,将创建ScoreBoard-Script类的实例。就像每个项目都有自己的CollectibleItem实例一样。 您可以通过以下方式获取实例:

var uiObject = GameObject.Find("Name of UI Object");
ScoreBoard board = uiObject.GetComponent<ScoreBoard>();

您可以在Start()中执行此操作,并将ScoreBoard变量保存在其他私有变量所在的脚本中,并稍后在触发器中使用它,也可以直接在Trigger函数中执行此操作并直接设置得分: / p>

board.score += pointsValue;

编辑:您必须将记分板的声明放置在类中:

ScoreBoard board;

void Start ()
...

或者将代码从头开始放入OnTriggerEnter。