How do I retrieve a variable from another script?

I need to retreive the score value from this script

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

public class TriggerZone : MonoBehaviour {
  
  
  
    public Text MyText;
    public int score;
  
    // Use this for initialization
    void Start () {

        MyText.text = "";
      
    }
  

    // Update is called once per frame
    void Update () {
      
        MyText.text = "$" + score;
      
    }
  
    void OnTriggerEnter(Collider coll) {
      
        if (coll.CompareTag ("Pickable")){
            score = score + 1;
        }
      
        if (coll.CompareTag ("Pickable")) {
            Destroy (coll.gameObject);
        }
      
    }
  
}

So that this script…

using UnityEngine;
using System.Collections;

public class CountDownTimer : MonoBehaviour {

    public int score;
    float timeRemaining = 3;

    // Use this for initialization
    void Start () {
    }
  
    // Update is called once per frame
    void Update () {
        timeRemaining -= Time.deltaTime;
    }

    void OnGUI(){
        if (timeRemaining > 0) {
            GUI.Label(new Rect(100, 100, 200, 100), "Time Remaining: "+(int)timeRemaining);
        }
        else{
            score = GetComponent<score>();
            GUI.Label(new Rect(100, 100, 200, 100), "Times up your score was" + score);
            //Application.LoadLevel("Testing Grounds");
        }

}
}

…can use it. However I keep getting the error “CountDownTimer.score' is a field’ but a `type’ was expected”. What do I do?

Also if anyone could help me with this I would be grateful.

Hi,

GetComponent is incorrect. It should be GetComponent().score;

I suggest you take a tour of the learn zone, this is quite good for what your trying to do: http://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/communicating-between-components-gameobjects?playlist=17117

1 Like

That worked… partially. Now it’s saying that “NullReferenceException: Object reference not set to an instance of an object” from what I gather means that it’s trying to access nothing?

Yeah GetComponent will only work if the object is actually on the same gameobject else it will return null. Watch the video :wink:

I will watch the 1 hour video later, but for now I just watched the shorter GetComponent video. I made sure both scripts were attached the proper game object. It seems to be working as I want it, but it still gives me that error I had before.

I’ll have to look into it more later, but at least it’s functioning semi-properly now.