Legacy Documentation: Version 5.4
LanguageEnglish
  • C#
  • JS

Script language

Select your preferred scripting language. All code snippets will be displayed in this language.

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

Sumbission failed

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

Close

Cancel

public static var state: Random.State;
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.

#pragma strict
function Start() {
	Random.InitState(255);
	PrintRandom("Step 1");
	PrintRandom("Step 2");
	var oldState: Random.State = 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");
}
function PrintRandom(label: String) {
	Debug.Log(String.Format("{0} - RandomValue {1}", label, Random.Range(1, 100)));
}
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.