Version: 2018.3 (switch to 2019.1)
LanguageEnglish
  • C#

Random.state

Suggest a change

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Close

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Close

Cancel

public static Random.State state;

Description

Gets/Sets the full internal state of the random number generator.

This property is usually used to save and restore a previously saved state of the random number generator (RNG). The RNG state can also be initialized with a seed using the Random.InitState function, but the effect is quite different, as shown in the following example.

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour { void Start() { Random.InitState(255);

PrintRandom("Step 1"); PrintRandom("Step 2");

Random.State oldState = Random.state;

PrintRandom("Step 3"); PrintRandom("Step 4");

Random.state = oldState;

PrintRandom("Step 5"); PrintRandom("Step 6");

Random.InitState(255);

PrintRandom("Step 7"); PrintRandom("Step 8"); }

void PrintRandom(string label) { Debug.Log(string.Format("{0} - RandomValue {1}", label, Random.Range(1, 100))); } }

After running this script we will observe that the random values from step 5 and 6 will be equal to those from step 3 and 4 because the internal state of the RNG was restored by using Random.state property. Also, the random values from step 7 and 8 will be equal to the ones from step 1 and 2 because Random.InitState reinitializes the state of the RNG with the initial seed.

Did you find this page useful? Please give it a rating: