0

I have this script:

        public  PlayState ()
        {
              HydroElectric ec = new HydroElectric();
        }
        public void ShowIt()
        {
            ec.t1Bool = GUI.Toggle (new Rect (25, 55, 100, 50), ec.t1Bool, "Turbina 2 MW");

            ec.t2Bool = GUI.Toggle (new Rect (25, 95, 100, 50), ec.t2Bool, "Turbina 3 MW");

            ec.t3Bool = GUI.Toggle (new Rect (25, 135, 100, 50), ec.t3Bool, "Turbina 1 MW");



            GUI.Box (new Rect (Screen.width - 100, 60, 80, 25), ec.prod.ToString ());      // PRODUCED ENERGY                             

            GUI.Box (new Rect (Screen.width - 650, 10, 100, 25), TimeManager.gametime.ToString() );  // GAME TIME HOURS

            float test;

            if (LoadDiagram.diagramaCarga.TryGetValue(TimeManager.gametime, out test)) // Returns true.
            {
                GUI.Box (new Rect (Screen.width - 650, 275, 50, 25),  test.ToString ());
            }
        }

The problem is that I had to remove the Hydroelectric object out of the "ShowIt" method because it was being created everytime the toogle button was created, so I created a constructor to create the object, but now, the variable 'ec' is not recognized, what am I missing here?

1 Answer 1

2

Now the variable only exists in the constructor:

public PlayState ()
{
    HydroElectric ec = new HydroElectric();
}

Which means that it's created, and then immediately lost as soon as the constructor is finished. It sounds like you want it to be a class-level member:

private HydroElectric ec;

public PlayState ()
{
    ec = new HydroElectric();
}

That would make it available throughout the class, and would maintain a single instance of the variable for the instance of the class.

Sign up to request clarification or add additional context in comments.

2 Comments

Got it, so I should not create variables in the constructor, just initialize them right/
@ClaudioA: You certainly can create variables in the constructor, just like in any method. But they follow the same rules as any other method-scoped variables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.