【问题标题】:Get int value from one method to another C# [closed]从一种方法获取 int 值到另一种 C# [关闭]
【发布时间】:2017-09-09 18:25:14
【问题描述】:

这里是代码。我想在 Update 方法中使用 SpwanArrow 方法中的 int randomIndex 值。有什么想法吗?

void SpawnArrow()
{
    //some code here        
    int randomIndex = UnityEngine.Random.Range(0, arrows.Length);
    GameObject prefab = arrows[randomIndex];
    GameObject clone = Instantiate(prefab, new Vector3(0.02F, 2.18F, -1), 
    Quaternion.identity);
}

void Update()
{
   if (randomIndex == 1 && (Input.GetButtonDown("a") == true))
   {
       ScoreManager.score += scoreValue;
   }
   //and so on

}

【问题讨论】:

  • 使其成为类级变量。
  • 你想用randomIndex做什么?

标签: c# unity3d methods int


【解决方案1】:

在你的类中让它成为一个全局变量

int randomIndex = -1;

void SpawnArrow()
{
    //some code here        
    randomIndex = UnityEngine.Random.Range(0, arrows.Length);
    GameObject prefab = arrows[randomIndex];
    GameObject clone = Instantiate(prefab, new Vector3(0.02F, 2.18F, -1),
    Quaternion.identity);
}

void Update()
{
    if (randomIndex == 1 && (Input.GetButtonDown("a") == true))
    {
        ScoreManager.score += scoreValue;
    }
    //and so on

}

我已将其设置为 -1,以免影响您的更新功能。

【讨论】:

    【解决方案2】:

    您可以将 randomIndex 设为私有属性。这将允许您在课堂上的任何地方使用它。

    private int randomIndex { get; set; }
    
    void SpawnArrow()
    {
        //some code here        
        randomIndex = UnityEngine.Random.Range(0, arrows.Length);
        GameObject prefab = arrows[randomIndex];
        GameObject clone = Instantiate(prefab, new Vector3(0.02F, 2.18F, -1), Quaternion.identity);
    }
    
    void Update()
    {
        if (randomIndex == 1 && (Input.GetButtonDown("a") == true))
            ScoreManager.score += scoreValue;
        //and so on
    }
    

    【讨论】:

      【解决方案3】:
      int randomIndex;   
      
      void SpawnArrow()
          {
              //some code here        
              randomIndex = UnityEngine.Random.Range(0, arrows.Length); 
              GameObject prefab = arrows[randomIndex];
              GameObject clone = Instantiate(prefab, new Vector3(0.02F, 2.18F, -1), 
              Quaternion.identity);
          }
      
          void Update()
          {
             if (randomIndex == 1 && (Input.GetButtonDown("a") == true))
             {
                 ScoreManager.score += scoreValue;
             }
             //and so on
      
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-08
        • 2014-10-18
        相关资源
        最近更新 更多