tomahawx
tomahawx

Reputation: 15

Accessing a c# variable from another script. Unity

I have been making a game where you can die, I want an on screen death counter so I added this:

// Death Counter
void OnGUI()
    {
        GUI.Label (Rect (0, 0, 100, 100), DeathCount);
    }

But I keep getting an error message saying the name DeathCount does not exist in the current context, how to I get it to access this, in the script where DeathCount is I have this:

 public static float DeathCount = 0f;

So why doesn't it pop up on screen?

(I also have the error "UnityEngine.Rect is a 'type' but used like 'variable'", I also need help on that but I thought that it might be affecting the main problem).

Sorry if this has already been answered I just couldn't find it after looking for over 1 hour.

Upvotes: 0

Views: 226

Answers (4)

Carlos Navas
Carlos Navas

Reputation: 82

Try this code, "myGameObject" is the name of the gameObject you want to access to the script, and "myScript" the name of the script

private GameObject test = GameObject.Find("myGameObject");
void OnGUI(){
    private float dead = test.GetComponent<myScript>.DeathCount;
    GUI.Label ( new Rect (0, 0, 100, 100), DeathCount.ToString() );
}

And that´s it, don´t hesitate to ask if you need more help :)

Upvotes: 0

Milad Qasemi
Milad Qasemi

Reputation: 3059

lets say DeathCount is in a class named counter like this

 public class counter : MonoBehaviour {
      public static float DeathCount = 0f;
    }

so we can access it from another class like this and dont forget you need to put a string as second argument of GUI.Lablel

   public class otherClass : MonoBehaviour {
    void OnGUI()
        {
            GUI.Label (Rect (0, 0, 100, 100), counter.DeathCount.ToString());
        } 
    }

Upvotes: 0

salvador angel
salvador angel

Reputation: 21

public GameObject ObjectHaveScript;//asign in the inspector
void OnGUI()
{
String DeathCount ObjectHaveScript.GetComponent<NameOfScript>().DeathCount;
GUI.Label ( new Rect (0, 0, 100, 100), DeathCount );
}

this is the Oficial doc http://docs.unity3d.com/ScriptReference/Component.GetComponent.html,

regards;

Upvotes: 0

Wiktor Zychla
Wiktor Zychla

Reputation: 48240

This is C# and it has its rules on how you create new instances and how you make strings out of numeric values:

// Death Counter
void OnGUI()
{
    GUI.Label ( new Rect (0, 0, 100, 100), DeathCount.ToString() );
}

Upvotes: 1

Related Questions