c# – Unity spawner position
You can generate random numbers using Random.Range()
.
However, it’s highly uncommon to use pixel values for positioning Game Objects in the world. Unity uses its own measurement: 1 unit in Unity is equivalent to 1 meter in the game world.
Still, if you insist on using pixels, you can translate that to world coordinates using Camera.ScreenToWorldPoint()
. Note that the z value will have to go, as you can’t generate a 3-dimensional point on a 2-dimensional screen.
var x = Random.Range(-500, 508);
var y = Random.Range(-280, 290);
var screenPosition = new Vector2(x, y);
var worldPosition = Camera.main.ScreenToWorldPoint(screenPosition);
var enemyGameObject = Instantiate(Enemy, worldPosition, Quaternion.identity);
If those are not pixels but, in fact, very large world coordinate values, you can include the z value and skip the translation step.
var x = Random.Range(-500, 508);
var y = Random.Range(-280, 290);
var z = Random.Range(-374, 374);
var randomPosition = new Vector2(x, y, z);
var enemyGameObject = Instantiate(Enemy, randomPosition, Quaternion.identity);
Read more here: Source link