从另一个类中统一获取一个类的bool值

时间:2016-08-31 07:06:01

标签: unity3d

我有一个类(PowerUp),其中我有一个公开声明的bool Mag

当我尝试从另一个类(结果)访问该bool时

                     // class Result

      if(PowerUP.Mag)// need to return the bool value from class PowerUp
  {
              // code to run if powerup.mag is true

        CoinCollectedCounter ++;
        CoinCounterText.text = ""+CoinCollectedCounter;
        col.gameObject.SetActive(false);
  }

我没有得到bool值...实际上它返回null

2 个答案:

答案 0 :(得分:1)

当您的脚本附加到场景中的游戏对象时:

GameObject.Find("MyGameObject").GetComponent<PowerUp>().Mag;

未附加脚本时:

PowerUp powerUp; // creating object
powerUp.Mag; // getting variable

答案 1 :(得分:-2)

要访问另一个类的bool,它应该声明为static

在课堂通电中,bool Mag应该被声明为

public static bool Mag;

所以在此声明之后代码可以正常工作

      // class Result

  if(PowerUP.Mag)// need to return the bool value from class PowerUp
  {
          // code to run if powerup.mag is true

    CoinCollectedCounter ++;
    CoinCounterText.text = ""+CoinCollectedCounter;
    col.gameObject.SetActive(false);
  }