0

I want to use static variables to provide Gui-text's to other scripts. In the script where I declare those variables as static everything works fine- in all other scripts I get a NullReferenceException .

Here the code of the Outputscript:

public class OutputScript : MonoBehaviour {
   public static UnityEngine.UI.Text CommandText;
   public UnityEngine.UI.Text ct1;
   void Start()
   {
           CommandText = ct1;
           Debug.Log("static output's set");
   }
}

Here is a method of another script which accesses it:

void OnTriggerExit()
{
    OutputScript.CommandText.text = "";//nullRefException
}

If I try this in the OutputScript, there's no exception

void Start()
{
  CommandText = ct1;
  OutputScript.CommandText.text = "";//works fine
  Debug.Log("static output's set");
}

If I check in the other scripts for null it returns true .

I know what a NullReferenceException is, but in this case I've set the public static variable, but its value is only not null in this script which isn't logical for me. I really have no idea what's going on there.

For people who don't know Unity3d Scipt enigne:

  • the Start() method gets called always first
  • the OnTriggerExit() method gets executed after Start()
leAthlon
  • 684
  • 1
  • 8
  • 20
  • you are instantiating CommandText in Start(). Thats why it works. You are not instantiating it for the other scripts. Probably if you run start() and after that other scripts your other scripts will run too. – Uwe Hafner Jun 07 '15 at 10:22
  • if so- the exception should raise only once? – leAthlon Jun 07 '15 at 10:24
  • The exception gets thrown until you instantiate the variable as often as you access it. – Uwe Hafner Jun 07 '15 at 10:42
  • means I have to instatiate it in every script? – leAthlon Jun 07 '15 at 11:05
  • No. It is static. You only have to instantiate it once. But before any scripts want to access it. I can't post code good in comments but look for: Singleton Pattern in c# with static variables on stackoverflow/google or write: public static UnitiyEngine.UI.Text CommandText = new Text(); or whatever the class wants for instantiating. – Uwe Hafner Jun 07 '15 at 11:09
  • I want the value of the static variable to be a Text I created in the editor- how can I put the object from the editor in a static variable? – leAthlon Jun 07 '15 at 11:11
  • Like in your void Start() you have to assign it somewhere in code before you use it. Possibly the moment you accept the value in your editor on leaving the editor control or on button click. Depends on your use case. – Uwe Hafner Jun 07 '15 at 11:21
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/79887/discussion-between-leathlon-and-uwe). – leAthlon Jun 07 '15 at 11:22

0 Answers0