我有这个脚本:
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 ());
}
}
问题在于我不得不将水电对象移出" ShowIt"方法,因为它是在每次创建toogle按钮时创建的,所以我创建了一个构造函数来创建对象,但现在,变量' ec'不承认,我在这里缺少什么?
答案 0 :(得分:2)
现在变量只存在于构造函数中:
public PlayState ()
{
HydroElectric ec = new HydroElectric();
}
这意味着它已经创建,然后在构造函数完成后立即丢失。听起来你希望它成为一个班级成员:
private HydroElectric ec;
public PlayState ()
{
ec = new HydroElectric();
}
这将使它在整个类中可用,并且将为该类的实例维护变量的单个实例。