Как сделать рандом в unity

Random

class in UnityEngine

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.

Submission 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.

Description

Easily generate random data for games.

This static class provides several easy game-oriented ways of generating pseudorandom numbers.

The generator is an Xorshift 128 algorithm, based on the paper Xorshift RNGs by George Marsaglia. It is statically initialized with a high-entropy seed from the operating system, and stored in native memory where it will survive domain reloads. This means that the generator is seeded exactly once on process start, and after that is left entirely under script control.

For more details on the seed, including how to manage it yourself, see InitState. To learn how to save and restore the state of Random, see state.

Versus System.Random

Static vs instanced
UnityEngine.Random is a static class, and so its state is globally shared. Getting random numbers is easy, because there is no need to new an instance and manage its storage. However, static state is problematic when working with threads or jobs (the generator will error if used outside the main thread), or if multiple independent random number generators are required. In those cases, managing instances of System.Random would be a better option.

Float upper bounds are inclusive
All properties and methods in UnityEngine.Random that work with or derive work from float-based randomness (for example value or ColorHSV) will use an inclusive upper bound. This means that it is possible, though as rare as any other given value, for the max to be randomly returned. In contrast, System.Random.NextDouble() has an exclusive maximum, and will never return the maximum value, but only a number slightly below it.

Static Properties

insideUnitCircleReturns a random point inside or on a circle with radius 1.0 (Read Only).
insideUnitSphereReturns a random point inside or on a sphere with radius 1.0 (Read Only).
onUnitSphereReturns a random point on the surface of a sphere with radius 1.0 (Read Only).
rotationReturns a random rotation (Read Only).
rotationUniformReturns a random rotation with uniform distribution (Read Only).
stateGets or sets the full internal state of the random number generator.
valueReturns a random float within [0.0..1.0] (range is inclusive) (Read Only).

Static Methods

ColorHSVGenerates a random color from HSV and alpha ranges.
InitStateInitializes the random number generator state with a seed.
RangeReturns a random float within [minInclusive..maxInclusive] (range is inclusive).

Is something described here not working as you expect it to? It might be a Known Issue. Please check with the Issue Tracker at issuetracker.unity3d.com.

Copyright ©2021 Unity Technologies. Publication Date: 2021-12-17.

Источник

Добавление случайных элементов в игру

Случайно выбираемые значения или предметы являются важной частью множества игр. В этих разделах показаны способы использования встроенного в Unity функционала генерации случайных значений для реализации некоторых основных игровых механик.

Выбор случайного элемента в массиве

Выбор случайного элемента массива водится к выбору случайного значения в диапазоне от нуля до максимального значения индекса в массиве (который на 1 меньше длины массива). Это сделать довольно просто, используя встроенный метод Random.Range:-

Учтите, что диапазон, из которого метод Random.Range возвращает значение, включает первый аргумент, но не включает второй аргумент. Так что, если в качестве второго аргумента передавать myArray.Length, вы получите правильный результат.

Выбор элементов с разной вероятностью

Иногда, вам требуется случайно выбрать элементы, но при этом некоторые из них должны выбираться с большей вероятностью, чем другие. Например, NPC может реагировать по-разному при встрече с игроком:-

Вы можете представить эти разные реакции в качестве отрезков, каждый из которых занимает определённую площадь на кусочке бумажной ленты, в сумме занимая всю площадь кусочка. Занимаемая отрезком площадь эквивалентна вероятности реакции, соответствующей данному отрезку. Совершение выбора в таком случае эквивалентно указанию на случайную точку на протяжении всего кусочка бумажной ленты (так сказать, бросанию дротика) с последующим выяснением того, в какой секции находится эта точка.

Как сделать рандом в unity. Смотреть фото Как сделать рандом в unity. Смотреть картинку Как сделать рандом в unity. Картинка про Как сделать рандом в unity. Фото Как сделать рандом в unity

Заметьте, что в данном случае необходимо наличие последнего оператора возврата, т.к. Random.value может вернуть 1 и тогда поиск никогда не найдёт случайно выбранную точку. Изменение строки

.. на проверку меньше-или-равно ( Как сделать рандом в unity. Смотреть фото Как сделать рандом в unity. Смотреть картинку Как сделать рандом в unity. Картинка про Как сделать рандом в unity. Фото Как сделать рандом в unityA linear curve does not weight values at all; the horizontal coordinate is equal to the vertical coordinate for each point on the curve. Как сделать рандом в unity. Смотреть фото Как сделать рандом в unity. Смотреть картинку Как сделать рандом в unity. Картинка про Как сделать рандом в unity. Фото Как сделать рандом в unityThis curve is shallower at the beginning, and then steeper at the end, so it has a greater chance of low values and a reduced chance of high values. You can see that the height of the curve on the line where x=0.5 is at about 0.25, which means there’s a 50% chance of getting a value between 0 and 0.25. Как сделать рандом в unity. Смотреть фото Как сделать рандом в unity. Смотреть картинку Как сделать рандом в unity. Картинка про Как сделать рандом в unity. Фото Как сделать рандом в unityThis curve is shallow at both the beginning and the end, making values close to the extremes more common, and steep in the middle which will make those values rare. Notice also that with this curve, the height values have been shifted up: the bottom of the curve is at 1, and the top of the curve is at 10, which means the values produced by the curve will be in the 1–10 range, instead of 0–1 like the previous curves.

Notice that these curves are not probability distribution curves like you might find in a guide to probability theory, but are more like inverse cumulative probability curves.

By defining a public AnimationCurve variable on one of your scripts, you will be able to see and edit the curve through the Inspector window visually, instead of needing to calculate values.

Перемешивание списка

Выбор элементов из набора без повторений

Заметьте, что хоть выбор осуществляется случайно, порядок выбранных элементов будет таким же, как и в оригинальном массиве. Если элементы будут использоваться по очереди, один за другим, то их порядок может сделать их частично предсказуемыми, поэтому может потребоваться перемешивание массива перед использованием.

Случайные точки в пространстве

Можно присвоить каждой компоненте Vector3 случайное значение, возвращаемое Random.value для получения случайной точки в пространстве куба:-

Это даст вам точку в кубе с ребром длиной в одну условную единицу. Куб можно масштабировать просто умножая X, Y и Z компоненты вектора на требуемые длины сторон. Если одна из осей имеет нулевое значение, точка всегда будет лежать на плоскости. Например, получение случайно точки “на земле” обычно достигается с помощью получения случайных компонент X и Z с установкой Y компоненты в ноль.

Источник

Добавление случайных элементов в игру

Случайно выбираемые значения или предметы являются важной частью множества игр. В этих разделах показаны способы использования встроенного в Unity функционала генерации случайных значений для реализации некоторых основных игровых механик.

Выбор случайного элемента в массиве

Выбор случайного элемента массива водится к выбору случайного значения в диапазоне от нуля до максимального значения индекса в массиве (который на 1 меньше длины массива). Это сделать довольно просто, используя встроенный метод Random.Range:-

Учтите, что диапазон, из которого метод Random.Range возвращает значение, включает первый аргумент, но не включает второй аргумент. Так что, если в качестве второго аргумента передавать myArray.Length, вы получите правильный результат.

Выбор элементов с разной вероятностью

Иногда, вам требуется случайно выбрать элементы, но при этом некоторые из них должны выбираться с большей вероятностью, чем другие. Например, NPC может реагировать по-разному при встрече с игроком:-

Вы можете представить эти разные реакции в качестве отрезков, каждый из которых занимает определённую площадь на кусочке бумажной ленты, в сумме занимая всю площадь кусочка. Занимаемая отрезком площадь эквивалентна вероятности реакции, соответствующей данному отрезку. Совершение выбора в таком случае эквивалентно указанию на случайную точку на протяжении всего кусочка бумажной ленты (так сказать, бросанию дротика) с последующим выяснением того, в какой секции находится эта точка.

Как сделать рандом в unity. Смотреть фото Как сделать рандом в unity. Смотреть картинку Как сделать рандом в unity. Картинка про Как сделать рандом в unity. Фото Как сделать рандом в unity

Заметьте, что в данном случае необходимо наличие последнего оператора возврата, т.к. Random.value может вернуть 1 и тогда поиск никогда не найдёт случайно выбранную точку. Изменение строки

.. на проверку меньше-или-равно ( Как сделать рандом в unity. Смотреть фото Как сделать рандом в unity. Смотреть картинку Как сделать рандом в unity. Картинка про Как сделать рандом в unity. Фото Как сделать рандом в unityA linear curve does not weight values at all; the horizontal coordinate is equal to the vertical coordinate for each point on the curve. Как сделать рандом в unity. Смотреть фото Как сделать рандом в unity. Смотреть картинку Как сделать рандом в unity. Картинка про Как сделать рандом в unity. Фото Как сделать рандом в unityThis curve is shallower at the beginning, and then steeper at the end, so it has a greater chance of low values and a reduced chance of high values. You can see that the height of the curve on the line where x=0.5 is at about 0.25, which means there’s a 50% chance of getting a value between 0 and 0.25. Как сделать рандом в unity. Смотреть фото Как сделать рандом в unity. Смотреть картинку Как сделать рандом в unity. Картинка про Как сделать рандом в unity. Фото Как сделать рандом в unityThis curve is shallow at both the beginning and the end, making values close to the extremes more common, and steep in the middle which will make those values rare. Notice also that with this curve, the height values have been shifted up: the bottom of the curve is at 1, and the top of the curve is at 10, which means the values produced by the curve will be in the 1–10 range, instead of 0–1 like the previous curves.

Notice that these curves are not probability distribution curves like you might find in a guide to probability theory, but are more like inverse cumulative probability curves.

By defining a public AnimationCurve variable on one of your scripts, you will be able to see and edit the curve through the Inspector window visually, instead of needing to calculate values.

Перемешивание списка

Выбор элементов из набора без повторений

Заметьте, что хоть выбор осуществляется случайно, порядок выбранных элементов будет таким же, как и в оригинальном массиве. Если элементы будут использоваться по очереди, один за другим, то их порядок может сделать их частично предсказуемыми, поэтому может потребоваться перемешивание массива перед использованием.

Случайные точки в пространстве

Можно присвоить каждой компоненте Vector3 случайное значение, возвращаемое Random.value для получения случайной точки в пространстве куба:-

Это даст вам точку в кубе с ребром длиной в одну условную единицу. Куб можно масштабировать просто умножая X, Y и Z компоненты вектора на требуемые длины сторон. Если одна из осей имеет нулевое значение, точка всегда будет лежать на плоскости. Например, получение случайно точки “на земле” обычно достигается с помощью получения случайных компонент X и Z с установкой Y компоненты в ноль.

Источник

The Random class provides you with easy ways of generating various commonly required types of random values.

This page provides an overview of the Random class and its common uses when scripting with it. For an exhaustive reference of every member of the Random class and further technical details about it, see the Random script reference.

Follow the links below for further details and examples of these useful methods.

Simple random numbers

Random.value gives you a random floating point number between 0.0 and 1.0. A common usage is to convert it to a number between zero and a range of your choosing by multiplying the result.

Random.Range gives you a random number between a minimum and maximum value that you provide. It returns either an integer or a float, depending on whether the min and max values provided are integers or floats.

Random points within Circles or Spheres

Random.insideUnitCircle returns a randomly selected point inside a circle with a radius of 1 (Again you can multiply the result to get a random point within a circle of any size).

Random.insideUnitSphere returns a randomly selected point inside a sphere with a radius of 1.

Random.onUnitSphere returns a randomly selected point on the surface of a sphere with a radius of 1.

Other types of random values

Unity’s random class also offers a few other types of random value.

Choosing a Random Item from an Array

Picking an array element at random boils down to choosing a random integer between zero and the array’s maximum index value (which is equal to the length of the array minus one). This is easily done using the built-in Random.Range function:-

Note that Random.Range returns a value from a range that includes the first parameter but excludes the second, so using myArray.Length here gives the correct result.

Choosing Items with Different Probabilities

Sometimes, you need to choose items at random but with some items more likely to be chosen than others. For example, an NPC may react in several different ways when it encounters a player:-

You can visualize these different outcomes as a paper strip divided into sections each of which occupies a fraction of the strip’s total length. The fraction occupied is equal to the probability of that outcome being chosen. Making the choice is equivalent to picking a random point along the strip’s length (say by throwing a dart) and then seeing which section it is in.

Как сделать рандом в unity. Смотреть фото Как сделать рандом в unity. Смотреть картинку Как сделать рандом в unity. Картинка про Как сделать рандом в unity. Фото Как сделать рандом в unity

In the script, the paper strip is actually an array of floats that contain the different probabilities for the items in order. The random point is obtained by multiplying Random.value by the total of all the floats in the array (they need not add up to 1; the significant thing is the relative size of the different values). To find which array element the point is “in”, firstly check to see if it is less than the value in the first element. If so, then the first element is the one selected. Otherwise, subtract the first element’s value from the point value and compare that to the second element and so on until the correct element is found. In code, this would look something like the following:-

Note that the final return statement is necessary because Random.value can return a result of 1. In this case, the search will not find the random point anywhere. Changing the line

…to a less-than-or-equal test would avoid the extra return statement but would also allow an item to be chosen occasionally even when its probability is zero.

Weighting continuous random values

A better approach for continuous results is to use an AnimationCurve to transform a ‘raw’ random value into a ‘weighted’ one; by drawing different curve shapes, you can produce different weightings. The code is also simpler to write:

Как сделать рандом в unity. Смотреть фото Как сделать рандом в unity. Смотреть картинку Как сделать рандом в unity. Картинка про Как сделать рандом в unity. Фото Как сделать рандом в unityA linear curve does not weight values at all; the horizontal coordinate is equal to the vertical coordinate for each point on the curve. Как сделать рандом в unity. Смотреть фото Как сделать рандом в unity. Смотреть картинку Как сделать рандом в unity. Картинка про Как сделать рандом в unity. Фото Как сделать рандом в unityThis curve is shallower at the beginning, and then steeper at the end, so it has a greater chance of low values and a reduced chance of high values. You can see that the height of the curve on the line where x=0.5 is at about 0.25, which means there’s a 50% chance of getting a value between 0 and 0.25. Как сделать рандом в unity. Смотреть фото Как сделать рандом в unity. Смотреть картинку Как сделать рандом в unity. Картинка про Как сделать рандом в unity. Фото Как сделать рандом в unityThis curve is shallow at both the beginning and the end, making values close to the extremes more common, and steep in the middle which will make those values rare. Notice also that with this curve, the height values have been shifted up: the bottom of the curve is at 1, and the top of the curve is at 10, which means the values produced by the curve will be in the 1–10 range, instead of 0–1 like the previous curves.

Notice that these curves are not probability distribution curves like you might find in a guide to probability theory, but are more like inverse cumulative probability curves.

Shuffling a List

A common game mechanic is to choose from a known set of items but have them arrive in random order. For example, a deck of cards is typically shuffled so they are not drawn in a predictable sequence. You can shuffle the items in an array by visiting each element and swapping it with another element at a random index in the array:-

Choosing from a Set of Items Without Repetition

A common task is to pick a number of items randomly from a set without picking the same one more than once. For example, you may want to generate a number of NPCs at random spawn points but be sure that only one NPC gets generated at each point. This can be done by iterating through the items in sequence, making a random decision for each as to whether or not it gets added to the chosen set. As each item is visited, the probability of its being chosen is equal to the number of items still needed divided by the number still left to choose from.

As an example, suppose that ten spawn points are available but only five must be chosen. The probability of the first item being chosen will be 5 / 10 or 0.5. If it is chosen then the probability for the second item will be 4 / 9 or 0.44 (ie, four items still needed, nine left to choose from). However, if the first was not chosen then the probability for the second will be 5 / 9 or 0.56 (ie, five still needed, nine left to choose from). This continues until the set contains the five items required. You could accomplish this in code as follows:-

Note that although the selection is random, items in the chosen set will be in the same order they had in the original array. If the items are to be used one at a time in sequence then the ordering can make them partly predictable, so it may be necessary to shuffle the array before use.

Random Points in Space

A random point in a cubic volume can be chosen by setting each component of a Vector3 to a value returned by Random.value :-

This gives a point inside a cube with sides one unit long. The cube can be scaled simply by multiplying the X, Y and Z components of the vector by the desired side lengths. If one of the axes is set to zero, the point will always lie within a single plane. For example, picking a random point on the “ground” is usually a matter of setting the X and Z components randomly and setting the Y component to zero.

Источник

Random.Range

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.

Submission 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.

Declaration

Description

Returns a random float within [minInclusive..maxInclusive] (range is inclusive).

Important: Both the lower and upper bounds are inclusive. Any given float value between them, including both minInclusive and maxInclusive, will appear on average approximately once every ten million random samples.

There is an int overload of this function that operates slightly differently, especially regarding the range maximum. See its docs below.

See Random for details on the algorithm, and for examples of how UnityEngine.Random may be different from other random number generators.

Declaration

Description

Return a random int within [minInclusive..maxExclusive) (Read Only).

This method will behave in the following ways:

There is a float overload of this function that operates slightly differently, especially regarding the range maximum. See its docs above.

See Random for details on the algorithm, and for examples of how UnityEngine.Random may be different from other random number generators.

Is something described here not working as you expect it to? It might be a Known Issue. Please check with the Issue Tracker at issuetracker.unity3d.com.

Copyright ©2021 Unity Technologies. Publication Date: 2021-12-17.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *