Reputation: 317
I am making my first game, and I am having trouble updating a bool value using a toggle button.
This is the button:
using UnityEngine;
using Assets.Code.Interfaces;
using Assets.Code.Scripts;
using Assets.Code.PowerPlants;
namespace Assets.Code.States
public void ShowIt()
{
HydroElectric.t1Bool = GUI.Toggle (new Rect (25, 55, 100, 50), HydroElectric.t1Bool, "Turbina 2 MW");
GUI.Box (new Rect (Screen.width - 100, 60, 80, 25), HydroElectric.prod.ToString ()); // PRODUCED ENERGY
}
This is where I have the if condition:
using System;
namespace Assets.Code.PowerPlants
public class HydroElectric
{
public static bool t1Bool = true;
public int turbina1;
public static float prod = 0;
public HydroElectric ()
{
if (t1Bool == true)
{
turbina1 = 2;
}
else
{
turbina1 =0;
}
prod = turbina1;
}
}
I have no errors on the console, the bool value is changing (I used debug) but the value of turbina1 is not changing (when I debug it from the first script). I have no idea why its value is not changing along with the true or false condition. Any idea?
Upvotes: 0
Views: 630
Reputation: 2943
public HydroElectric ()
is a default constructor. It is executed only when you instantiate a new HydroElectric instance using new HydroElectric()
. You never do it. This is why the code inside this function is never actually called.
Furthermore, not in general case but specifically with MonoBehaviour, it is not a good practice to use constructors at all since in best case it will be called once and then immediately overwritten by scene serialization. See more: http://answers.unity3d.com/questions/32413/using-constructors-in-unity-c.html
If what you want to achieve is executing your code each time you change t1Bool for example, you can make it a property:
public class HydroElectric
{
//.... Your other code
//....
public static bool T1Bool {
get{
return t1Bool;
}
set{
t1Bool = value;
if (t1Bool == true)
{
turbina1 = 2;
}
else
{
turbina1 =0;
}
prod = turbina1;
}
}
}
//...
// Usage
HydroElectric.T1Bool = GUI.Toggle (new Rect (25, 55, 100, 50), HydroElectric.T1Bool, "Turbina 2 MW");
Upvotes: 1