Hello
I am trying to access a variable from another script and then display it on OnGUI.
In one script called Career_Variables I have 6 variables : Fame, Fame_level, money, Races_Completed, Races_won, Races_lost.
I have already been able to access the variables from Career_Variables in another script so I dont think that its a problem with gameobject.FindObject.GetComponent
Here’s the code of the script with the GUI
using UnityEngine;
using System.Collections;
public class Career_GUI : Career_Variables {
Texture StartRacing;
GUIStyle bigger_option_GUI_Style;
GUIStyle smaller_option_GUI_Style;
GUIStyle two_smaller_option_GUI_Style;
void Start () {
}
void Update () {
Career_Variables career = GameObject.Find("Background Camera").GetComponent<Career_Variables>();
}
void OnGUI()
{
GUI.Label(new Rect(605, 8, 20, 20), money.ToString());
GUI.Label(new Rect(850, 100, 20, 20), Races_Completed.ToString(), smaller_option_GUI_Style);
GUI.Label(new Rect(1155, 130, 20, 20), Fame.ToString(), two_smaller_option_GUI_Style);
GUI.Label(new Rect(1319, 100, 20, 20), Races_won.ToString(), two_smaller_option_GUI_Style);
if (GUI.Button(new Rect(5,140,265,180), StartRacing))
Application.LoadLevel ("Level Select");
}
}
And this is the code of the class that holds the variables
using UnityEngine;
using System.Collections;
public class Career_Variables : MonoBehaviour {
static public int Fame;
static public int Fame_level;
static public int money = 20000;
static public int Races_Completed;
static public int Races_won;
static public int Races_lost;
void Start () {
}
void Update () {
}
}
I keep getting the errors
NullReferenceException: Object reference not set to an instance of an object
UnityEngine.GUI.Label (Rect position, UnityEngine.GUIContent content, UnityEngine.GUIStyle style)
UnityEngine.GUI.Label (Rect position, System.String text, UnityEngine.GUIStyle style)
Career_GUI.OnGUI () (at Assets/Scripts/CSharpScripts/Career_GUI.cs:27)
and
UnityException: You are not allowed to call this function when declaring a variable.
Move it to the line after without a variable declaration.
If you are using C# don’t use this function in the constructor or field initializers, Instead move initialization to the Awake or Start function.
Career_GUI…ctor ()
I’ve tried to decode these errors but i’m totally confused.
All help will be appreciated
Thank you in Advance