Question by
Creative Inventory · Aug 30, 2015 at 11:47 AM ·
spawningx-axis
My Spawning script not working
My spawning script for prefabs does't spawn my objects on the X axis randomly. I first made some cubes (at the bottom, top, left and right) outside of the main camera view, then added my spawning the prefabs at the same place instead of it being random, the top and bottom cubes seems fine (spawning randomly- working nicely) but after a few minutes, i notice a pattern and I want it to be random, but still out main camera's view (not to far)
Here's my spawning script:
pragma strict
// Variable to store the enemy prefab public var enemy : GameObject;
// Variable to know how fast we should create new enemies
public var spawnTime : float = 2;
function Start() {
// Call the 'addEnemy' function every 'spawnTime' seconds
InvokeRepeating("addEnemy", spawnTime, spawnTime);
}
// New function to spawn an enemy
function addEnemy() {
// Variables to store the X position of the spawn object
// See image below
var x1 = transform.position.x - GetComponent.<Renderer>().bounds.size.x/2;
var x2 = transform.position.x + GetComponent.<Renderer>().bounds.size.x/2;
// Randomly pick a point within the spawn object
var spawnPoint = new Vector2(Random.Range(x1, x2), transform.position.y);
// Create an enemy at the 'spawnPoint' position
Instantiate(enemy, spawnPoint, Quaternion.identity
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612002006im_/https://answers.unity.com/themes/thub/images/avi.jpg)