RandomSingleton.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using UnityEngine;
  2. using System.Collections;
  3. /// <summary>
  4. /// This singleton is responsible for keeping an instance of System.Random which we can reset to a specific seed.
  5. /// This is important for replaying the exact same sequence of pseudo-random numbers.
  6. /// </summary>
  7. public class RandomSingleton
  8. {
  9. #region Singleton
  10. private static RandomSingleton instance;
  11. public static RandomSingleton Instance
  12. {
  13. get
  14. {
  15. if (instance == null)
  16. {
  17. instance = new RandomSingleton();
  18. }
  19. return instance;
  20. }
  21. }
  22. #endregion
  23. System.Random _random;
  24. RandomSingleton()
  25. {
  26. SetSeed(0);
  27. }
  28. public void SetSeed(int seed)
  29. {
  30. AVDebug.Log("Random Singleton Seed set to "+seed);
  31. _random = new System.Random(seed);
  32. }
  33. public int NextInt()
  34. {
  35. int r = _random.Next();
  36. //AVDebug.Log("!!!Got Random int "+r);
  37. return r;
  38. }
  39. public int NextInt(int min, int max)
  40. {
  41. AVDebug.Assert(max >= min, "Max must be >= min");
  42. int range = max - min;
  43. int r = min + (int)(_random.NextDouble() * range);
  44. //AVDebug.Log("!!!Got Random int from range "+r);
  45. return r;
  46. }
  47. public float NextFloat()
  48. {
  49. float r = (float)_random.NextDouble();
  50. //AVDebug.Log("!!!Got Random float "+r);
  51. return r;
  52. }
  53. public float NextFloat(float min, float max)
  54. {
  55. AVDebug.Assert(max >= min, "Max must be >= min");
  56. float range = max - min;
  57. float r = min + (float)(_random.NextDouble() * range);
  58. //AVDebug.Log("!!!Got Random float from range "+r);
  59. return r;
  60. }
  61. }