C# 我想把球的价值从1到100随机分配
如何将ballValue从随机范围1随机分配到100,以便每个球都具有不同的值 对象的随机值C# 我想把球的价值从1到100随机分配,c#,C#,如何将ballValue从随机范围1随机分配到100,以便每个球都具有不同的值 对象的随机值 using UnityEngine; using System.Collections; public class HT_Score : MonoBehaviour { public GUIText scoreText; public int ballValue; private int score; void Start () { score =
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;
}
}
你的函数应该是
void GetRandomBallValue()
{
ballValue=new Random().Next(1,100);
}
void OnCollisionEnter2D (Collision2D collision) {
if (collision.gameObject.tag == "Bomb") {
GetRandomBallValue();
score =ballValue * 2;
UpdateScore ();
}
}
你不应该每次都调用newrandom 每次执行新的随机操作时,都会使用时钟对其进行初始化。这意味着在一个紧密的循环中,你会多次得到相同的值。您应该保留一个随机实例,并在同一实例上继续使用Next。 请看这里:
你还必须考虑,下一个随机数从1到100,不包括100。如果你想把100包括在内,你需要打电话给NEXT1101
我建议以以下方式实施: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 ();
}
}
我给你一个提示:搜索Random。可能重复的我不想随机得分想要随机球值