Get int value from one method to another C#

时间:2017-04-13 14:52:58

标签: c# unity3d methods int

Here is the code. I would want to use this value of int randomIndex from SpwanArrow method in the Update method. Any ideas?

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

}

3 个答案:

答案 0 :(得分:0)

在班级中将其设为全局变量

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,因为它不会影响您的更新功能。

答案 1 :(得分:0)

您可以将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
}

答案 2 :(得分:0)

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

    }