Sti*_*fpy 0 c# unity-game-engine
我正在使用System.Random函数为随机数创建/生成种子,然后使用Next()来跟踪数字,但很像c ++,"rng"每次都会得到相同的随机数结果.但是在c ++中通过清除c ++中的种子来解决这个问题,所以我想知道c#中是否也可以这样做?
您很可能Random每次都使用新的实例.您不应该new Random(seed_here)重复实例化.
Random r = new Random(); //Do this once - keep it as a (static if needed) class field
for (int i = 0; i < 10; i++) {
Console.WriteLine($"{r.Next()}");
}
Run Code Online (Sandbox Code Playgroud)
这是一个更复杂的例子:
class MyClass
{
//You should use a better seed, 1234 is here just for the example
Random r1 = new Random(1234); // You may even make it `static readonly`
public void BadMethod()
{
// new Random everytime we call the method = bad (in most cases)
Random r2 = new Random(1234);
for (int i = 0; i < 3; i++)
{
Console.WriteLine($"{i + 1}. {r2.Next()}");
}
}
public void GoodMethod()
{
for (int i = 0; i < 3; i++)
{
Console.WriteLine($"{i+1}. {r1.Next()}");
}
}
}
class Program
{
static void Main(string[] args)
{
var m = new MyClass();
m.BadMethod();
m.BadMethod();
m.GoodMethod();
m.GoodMethod();
}
}
Run Code Online (Sandbox Code Playgroud)
产量
1. 857019877
2. 1923929452
3. 685483091
1. 857019877 <--- Repeats
2. 1923929452
3. 685483091
1. 857019877
2. 1923929452
3. 685483091
1. 2033103372 <--- Phew! It's a new number
2. 728933312
3. 2037485757
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
66 次 |
| 最近记录: |