Created
July 17, 2023 07:59
-
-
Save petitviolet/11de146087f4f3ad3d7ac73764723959 to your computer and use it in GitHub Desktop.
SeedRandom to deal with seed value of UnityEngine.Random
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
public class SeedRandom | |
{ | |
private UnityEngine.Random.State _randomState; | |
public static int DefaultSeed() | |
{ | |
return (int)System.DateTime.Now.Ticks; | |
} | |
public SeedRandom() : this(SeedRandom.DefaultSeed()) { } | |
public SeedRandom(int seed) | |
{ | |
var originalState = UnityEngine.Random.state; | |
UnityEngine.Random.InitState(seed); | |
_randomState = UnityEngine.Random.state; | |
UnityEngine.Random.state = originalState; | |
} | |
private T WithRandom<T>(Func<T> f) | |
{ | |
var originalState = UnityEngine.Random.state; | |
UnityEngine.Random.state = _randomState; | |
var result = f(); | |
_randomState = UnityEngine.Random.state; | |
UnityEngine.Random.state = originalState; | |
return result; | |
} | |
public int Range(int minInclusive, int maxExclusive) | |
{ | |
return WithRandom(() => UnityEngine.Random.Range(minInclusive, maxExclusive)); | |
} | |
public float Range(float minInclusive, float maxInclusive) | |
{ | |
return WithRandom(() => UnityEngine.Random.Range(minInclusive, maxInclusive)); | |
} | |
public float Value() | |
{ | |
return WithRandom(() => UnityEngine.Random.value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment