c#Unity在构造函数中创建对象

本文关键字:创建对象 构造函数 c#Unity | 更新日期: 2023-09-27 18:28:06

我有这个脚本:

        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"方法中删除Hydropolic对象,因为每次创建toogle按钮时都会创建它,所以我创建了一个构造函数来创建该对象,但现在,变量"ec"无法识别,我缺少什么?

c#Unity在构造函数中创建对象

现在变量只存在于构造函数中:

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

这意味着它被创建了,然后在构造函数完成后立即丢失。听起来你想让它成为班级级别的成员:

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

这将使它在整个类中都可用,并为类的实例维护一个变量实例。