Version: 2018.4
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.

Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961