Unity, random function

introduce

In Unity, you can use the Random class to generate random numbers. The Random class provides several methods to generate different types of random numbers.


method

The following are some commonly used Random functions:

Random.Range(min, max): Generate a random number between min and max, including min and max.

Random.value: Generates a random number between 0 and 1.

Random.insideUnitSphere: Generates a random vector inside the unit sphere.

Random.insideUnitCircle: Generates a random vector inside the unit circle.

Random.onUnitSphere: Generates a random vector on the surface of a unit sphere.

When using the Random function, you need to pay attention to the following points:

Before using the random number generator, you need to call the Random.InitState(seed) function to initialize the random number seed, where seed is an integer value.

If you need to generate the same sequence of random numbers across multiple frames, you can use the same random number seed on each frame.

Random number generators may have different implementations on different platforms, so the sequence of random numbers generated may vary.

In some occasions that require high-quality random numbers, you can consider using more complex random number generators, such as the Mersenne Twister algorithm.


for example

Here is an example of a Unity script that uses the Random class to generate random numbers

using UnityEngine;

public class RandomExample : MonoBehaviour
{
    
    
    // 最小值
    public float min = 1f;
    // 最大值
    public float max = 10f;

    void Start()
    {
    
    
        // 生成一个介于min和max之间的随机数
        float randomValue = Random.Range(min, max);

        // 输出随机数
        Debug.Log("Generated random value: " + randomValue);
    }
}

Guess you like

Origin blog.csdn.net/qq_20179331/article/details/130036337