Dhoni
Dhoni

Reputation: 1234

How to have two states of randomness in unity3d, c#?

I am trying to achieve something like two states of random number generates

Example , one instance with seed and other with default randomness:

UnityEngine.Random.InitState(255);

I need this because i have a part of my_game as multiplayer with game_a and my_game has some additional features which also uses randomness.

How can I achieve this?

Upvotes: 1

Views: 325

Answers (2)

TheSkimek
TheSkimek

Reputation: 342

You can use two instances of the Random class.

Define that you want to use the System.Random instead of UnityEngine.Random:

using RNG = System.Random;

and then

RNG rand1 = new RNG(); 
RNG rand2 = new RNG(5);

The first one will use a seed that is depending on the time your game is started, so it will always be different. The second one has a set seed and should always produce the same sequence of random numbers

EDIT to show the usage of C# Random over UnityEngine Random

Upvotes: 2

Kell
Kell

Reputation: 3317

Use an instance of the Random class as documented here: https://msdn.microsoft.com/en-us/library/ctssatww(v=vs.110).aspx

using System;
using System.Threading;

public class Example
{
   public static void Main()
   {
      Random rand1 = new Random((int) DateTime.Now.Ticks & 0x0000FFFF);
      Random rand2 = new Random((int) DateTime.Now.Ticks & 0x0000FFFF);
      Thread.Sleep(20);
      Random rand3 = new Random((int) DateTime.Now.Ticks & 0x0000FFFF);
      ShowRandomNumbers(rand1);
      ShowRandomNumbers(rand2);
      ShowRandomNumbers(rand3);
   }

   private static void ShowRandomNumbers(Random rand)
   {
      Console.WriteLine();
      byte[] values = new byte[4];
      rand.NextBytes(values);
      foreach (var value in values)
         Console.Write("{0, 5}", value);

      Console.WriteLine(); 
   }
}

Upvotes: 2

Related Questions