简体   繁体   中英

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

I'm working a unity 3d game and I've ran into a problem:

I have two boxes called breakableBox and breakableBox_2 . When the player collides with them, they add to the player's score variable playerScore and the box hides itself. 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

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].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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