Hi there, I am using the following code to generate some prefabs to spawn and that works great however I would love it for the spawning to be random across the entire screen. I only need it to be random in the X and Y direction as it's a 2d game. Below is my current spawning code. Is there a way to use Random Range to randomly spawn the positioning of the object. Thank you Code (CSharp): using UnityEngine; using System.Collections; public class SpawnScript : MonoBehaviour { public GameObject[] obj; public float spawnMin = 1f; public float spawnMax = 2f; void Start () { Spawn(); } void Spawn () { Instantiate(obj[Random.Range (0, obj.GetLength(0))], transform.position, Quaternion.Euler(0, 0, -360)); Invoke ("Spawn", Random.Range (spawnMin, spawnMax)); } }
Random.range gives you one random number between a low number and a high number. You just need to call it twice, once for x coordinate and once for y coordinate. Then spawn at those coordinates. E.g. random.range(0,Screen.width-1) And Random.range(0,Screen.height-1)
depends on your coordinate system and scale though as to how much coordinates cover the screen. you can do random.value()*width whatever the units is.
Basically got it working with this. Values need tweaking but its giving a decent result so far. Code (CSharp): public GameObject[] obj; public float spawnMin = 1f; public float spawnMax = 2f; public float horizontalMin = 1f; public float horizontalMax = 5f; public float verticalMin = -2f; public float verticalMax = 2f; private Vector2 originPosition; private Vector2 originDimentions; void Start () { originDimentions = transform.localScale; originPosition = transform.position; Spawn(); } void Spawn () { Vector2 randomPosition = originPosition + new Vector2(Random.Range(horizontalMin, horizontalMax), Random.Range(verticalMin, verticalMax)); Instantiate(obj[Random.Range (0, obj.GetLength(0))], randomPosition, Quaternion.Euler(0, 0, -360)); originPosition = randomPosition; Invoke ("Spawn", Random.Range (spawnMin, spawnMax)); }