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

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.

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

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:

Как сделать рандом в юнити. Смотреть фото Как сделать рандом в юнити. Смотреть картинку Как сделать рандом в юнити. Картинка про Как сделать рандом в юнити. Фото Как сделать рандом в юнитиA linear curve does not weight values at all; the horizontal coordinate is equal to the vertical coordinate for each point on the curve. Как сделать рандом в юнити. Смотреть фото Как сделать рандом в юнити. Смотреть картинку Как сделать рандом в юнити. Картинка про Как сделать рандом в юнити. Фото Как сделать рандом в юнитиThis 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. Как сделать рандом в юнити. Смотреть фото Как сделать рандом в юнити. Смотреть картинку Как сделать рандом в юнити. Картинка про Как сделать рандом в юнити. Фото Как сделать рандом в юнитиThis 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

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 5. Рандомное появление объектов.

Как создать появление объектов в случайном месте при старте сцены.

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

Для начала подготовим сцену, создадим плоскость, на которой будем размещать наши объекты.

Изменим размеры плоскости, к примеру: 50,1,50.

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

Добавим два объекта сферу и куб, эти объекты и будут появляться на сцене в случайных местах.

Сохраним эти объекты в префаб.

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

Для отображения сцены можно добавить стандартного персонажа с камерой, а стандартную камеру удалить со сцены.

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

Добавим пустой объект, на нем будет находиться наш скрипт.

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

Создадим С# скрипт и назовем его SpownObject, напишем в нем такой код:

Добавим этот скрипт на пустышку и переместим в строки kub и sphere наши префабы куба и сферы. Зададим координаты центра 1,1,1. В строке size укажем координаты диапазона, в которых будут появляться объекты, к примеру: 10,0,10.

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

Можем запустить игру и проверить, при запуске сцены объект куб и сфера будут появляться в случайном месте в заданном диапазоне.

Источник

Как сделать случайную генерацию объектов по координатам заданным в массиве unity?

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

В общем то проще простого
— как создать объекты я так понимаю вы знаете.
— как создать список координат тоже

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

оо все похенько.
С чего вы взяли что js код у меня? Это все си шарп ваш любимый.

и что у вас со знанием структур данный. массив от списка чем отличается?? почитайте плиз где нибудь.
Я специально указал и расписал что используется СПИСОК, и что его размер по ходу дела УМЕНЬШАЕТСЯ.

public List spawnPoints;
и не забыть using System.GenericCollection;

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

и еще раз это не разовая генерация/расстановка врагов по точкам.

то вам надо по сути при создании врага запоминать куда он создался (может в скрипт врага записывать или куда еще)
и делать выборку из вашего списка с исключением уже занятых (запомненных, точек)

Except(МАССИВ УЖЕ ЗАНЯТЫХ ТРАНСФОРМОВ);

но это все лишь принципы, как это сделать, а вы судя по всему где то пропустили курс основ программирования как такового(

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

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

Даже со взвешенным рандомом легко может случиться так, что все враги заспавнятся в одном месте, поэтому лучше использовать какой-то алгоритм ротации точек спавна. Для этого можно использовать Shuffle Bag, либо можно просто выкидывать использованные точки спавна из списка.

Источник

soltveit.org

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

By ronny

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

How to do a Unity random number for integers and float. Let us go thru a few examples with random integer and random float using unity random range. To get a random number is an important part of almost every game.

Unity random number: integer

The range of int we will use in this example is from 0 to 10. We want to include 10 as a possible number to get. Let us draw 9 random numbers and have a look to see what they look like. I have created an empty game object to the scene and attached this little script.

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

Here is the script to create unity random number from 0 to 10.

This is what our output looks like.

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

If you run this several times you will get a different result every time. If you need to have the same procedure of random numbers, you will need to check out Random Seeds.

How to get float instead of integer

We will use the same project as we only need to make a small change in the script to make it generate random floats instead of integers. We also change the max number to 10 instead of 11. Here is the updated script snippet.

We just declare the variable as float instead of integer. And add an f to the numbers in the Random.Range method. That will give random floats instead of integers. Lets look what kind of output this will give us.

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

Syntax

This little example will find numbers in the same range. Remember when using integers you have to add 1 to the max numbers. That is the most important difference when using a random range in Unity.

Источник

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

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