2014-07-01 51 views
-3

如何從隨機範圍1隨機ballValue爲100,每個球帶有不同價值 隨機值對象我想從範圍1隨機ballValue至100

using UnityEngine; 
using System.Collections; 

public class HT_Score : MonoBehaviour { 

    public GUIText scoreText; 
    public int ballValue; 
    private int score; 

    void Start() { 
     score = 0; 
     UpdateScore(); 
    } 

    void OnTriggerEnter2D (Collider2D other) { 
     score += ballValue; 
     UpdateScore(); 
    } 

    void OnCollisionEnter2D (Collision2D collision) { 
     if (collision.gameObject.tag == "Bomb") { 
      score -= ballValue * 2; 
      UpdateScore(); 
     } 
    } 

    void UpdateScore() { 
     scoreText.text = "SCORE:\n" + score; 
    } 
} 
+3

我給你一個提示:搜索'Random'。 –

+0

可能的重複[如何在C#中使用隨機數?](http://stackoverflow.com/questions/3217651/how-do-i-use-random-numbers-in-c) – InitLipton

回答

0

你的函數shoule來看看像

void GetRandomBallValue() 
{ 
ballValue=new Random().Next(1,100); 
} 
    void OnCollisionEnter2D (Collision2D collision) { 
     if (collision.gameObject.tag == "Bomb") { 
      GetRandomBallValue(); 
      score =ballValue * 2; 
      UpdateScore(); 
     } 
    } 
+0

我不想要以隨機分數想要隨機ballValue –

+0

看到我更新的答案。 –

0

你不應該每次調用新的Random()。

「每次你做新的Random()它都會使用時鐘進行初始化,這意味着在一個緊密的循環中你會得到相同的值很多次,你應該保留一個Random實例,並繼續使用Next實例「。 請看這裏: Random number generator only generating one random number

你還必須考慮,next()返回從1到100(不包括100)的隨機數。如果你想包含100,你需要調用next(1,101)。

我建議來實現它的方式如下:

Random rnd = new Random(); 
void GetRandomBallValue() 
{ 
    ballValue=rnd.Next(1,101); //excluding 101 - if you do not need 100, call Next(1,100); 
} 

void OnCollisionEnter2D (Collision2D collision) { 
    if (collision.gameObject.tag == "Bomb") { 
     GetRandomBallValue(); 
     score =ballValue * 2; 
     UpdateScore(); 
    } 
}