简体   繁体   English

不能从另一个C#脚本统一访问变量

[英]Can't access variable from another C# script in unity

I'm working a unity 3d game and I've ran into a problem: 我正在开发一个统一的3D游戏,但遇到了一个问题:

I have two boxes called breakableBox and breakableBox_2 . 我有两个框,称为breakableBoxbreakableBox_2 When the player collides with them, they add to the player's score variable playerScore and the box hides itself. 当玩家与他们发生碰撞时,它们会添加到玩家的得分变量playerScore并且该框会隐藏起来。 Here's the code that both of the boxes use: 这是两个盒子都使用的代码:

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour
{
    public static int playerScore;

    public Renderer rend;

    void Start()
    {
        rend = GetComponent<Renderer>();
        rend.enabled = true;
    }

    void OnTriggerEnter(Collider other)
    {
        rend.enabled = false;
        playerScore++;
    }



}

And then in order to show the score, I have this script attached to the player camera: 然后为了显示分数,我将此脚本附加到了播放器摄像机上:

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

public class Points : MonoBehaviour {
    int score = ExampleClass.playerScore;
    void OnGUI()
    {
        GUIStyle style = new GUIStyle(GUI.skin.button);
        style.fontSize = 24;
        GUI.Label(new Rect(1, 1, 150, 30), score.ToString() + " points", style);
    }
}

However, the score stays at zero, even when in the console I can see that it added the points to the variable. 但是,即使在控制台中,我仍然可以看到分数将分数添加到了变量中,所以分数始终保持为零。 If anyone knows how to help me fix this, that would be great. 如果有人知道如何帮助我解决此问题,那就太好了。

You are not updating the score int in your Points class, try this 您还没有更新score在你点类int,试试这个

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

public class Points : MonoBehaviour {

    void OnGUI()
    {
        int score = ExampleClass.playerScore;
        GUIStyle style = new GUIStyle(GUI.skin.button);
        style.fontSize = 24;
        GUI.Label(new Rect(1, 1, 150, 30), score.ToString() + " points", style);
    }
}

Edit: as @MXD mentioned in the comment, it's better to not update values in OnGUI and do it in Update() Instead [or FixedUpdate() since your score system is physics reliant]. 编辑:正如评论中提到的@MXD一样,最好不要在OnGUI更新值,而应在Update()执行此操作,而最好是[或FixedUpdate()因为您的计分系统是物理依赖的]。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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