【问题标题】:Accessing a c# variable from another script. Unity从另一个脚本访问 c# 变量。统一
【发布时间】:2014-11-13 04:42:21
【问题描述】:

我一直在制作一个你可以死的游戏,我想要一个屏幕上的死亡计数器,所以我添加了这个:

// Death Counter
void OnGUI()
    {
        GUI.Label (Rect (0, 0, 100, 100), DeathCount);
    }

但我不断收到一条错误消息,指出名称 DeathCount 在当前上下文中不存在,我如何让它访问它,在 DeathCount 所在的脚本中我有这个:

 public static float DeathCount = 0f;

那为什么它没有在屏幕上弹出呢?

(我也有错误“UnityEngine.Rect 是一个‘类型’,但像‘变量’一样使用”,我也需要这方面的帮助,但我认为它可能会影响主要问题)。

对不起,如果这个问题已经回答了,我找了1个多小时还是找不到。

【问题讨论】:

    标签: c# variables unity3d


    【解决方案1】:

    这是 C#,它有关于如何创建新实例以及如何从数值中创建字符串的规则:

    // Death Counter
    void OnGUI()
    {
        GUI.Label ( new Rect (0, 0, 100, 100), DeathCount.ToString() );
    }
    

    【讨论】:

      【解决方案2】:
      public GameObject ObjectHaveScript;//asign in the inspector
      void OnGUI()
      {
      String DeathCount ObjectHaveScript.GetComponent<NameOfScript>().DeathCount;
      GUI.Label ( new Rect (0, 0, 100, 100), DeathCount );
      }
      

      这是官方文档http://docs.unity3d.com/ScriptReference/Component.GetComponent.html

      问候;

      【讨论】:

      • 它说我需要一个 ;在 ObjectHaveScript 中的 O 之前?我做错了吗?
      • String - 带小写字母 s ,p​​s。您使用的是 c# 还是 unityscript ?它适用于 c#;
      • 到目前为止我的脚本是: void OnGUI() { string DeathCount ObjectHavescript.GetComponent().DeathCount; GUI.Label ( new Rect (0, 0, 100, 100), DeathCount ); }
      【解决方案3】:

      假设 DeathCount 在一个像这样的名为 counter 的类中

       public class counter : MonoBehaviour {
            public static float DeathCount = 0f;
          }
      

      所以我们可以像这样从另一个类访问它,不要忘记你需要将一个字符串作为 GUI.Label 的第二个参数

         public class otherClass : MonoBehaviour {
          void OnGUI()
              {
                  GUI.Label (Rect (0, 0, 100, 100), counter.DeathCount.ToString());
              } 
          }
      

      【讨论】:

        【解决方案4】:

        试试这段代码,“myGameObject”是你要访问脚本的游戏对象的名称,“myScript”是脚本的名称

        private GameObject test = GameObject.Find("myGameObject");
        void OnGUI(){
            private float dead = test.GetComponent<myScript>.DeathCount;
            GUI.Label ( new Rect (0, 0, 100, 100), DeathCount.ToString() );
        }
        

        就是这样,不要犹豫,询问您是否需要更多帮助:)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-10-11
          • 1970-01-01
          • 1970-01-01
          • 2017-01-19
          • 2022-07-16
          • 1970-01-01
          相关资源
          最近更新 更多