- Home /
Objects not being randomly created
I need to randomly create gameObjects as the player moves though the track. I made this script and attached it to an empty gameObject:
using UnityEngine;
using System.Collections;
public class Spawn : MonoBehaviour
{
public GameObject block;
int blockNo;
public float maxPos = 2.2f;
public float delayTimer = 0.5f;
float timer;
// Use this for initialization
void Start()
{
timer = delayTimer;
}
// Update is called once per frame
void Update () {
timer -= Time.deltaTime;
if (timer <= 0)
{
Vector3 blockPos = new Vector3(Random.Range(-2.2f, 2.2f), transform.position.y, transform.position.z);
blockNo = Random.Range(0, 5);
Instantiate(block, blockPos, transform.rotation);
timer = delayTimer;
}
}
}
However new blocks are not being spawned, as there should be block copies showing up in the hierachy. Any ideas? Thanks
Comment
Answer by Kadenaa · Oct 05, 2015 at 11:57 PM
@legolas66 That script by itself should be working just fine. Are you sure you attached it to a gameobject in your scene?
Something you could try is setting the Instantiated object to be a child to the spawn object. Like so:
void Update(){
timer -= Time.deltaTime;
if (timer <= 0){
Vector3 blockPos = new Vector3(Random.Range(-maxPos, maxPos), transform.position.y, transform.position.z); //Will only randomize position along x-axis.
GameObject blockObject = Instantiate(block, blockPos, transform.rotation) as GameObject;
blockObject.transform.SetParent(transform, false);
blockNo = Random.Range(0, 5); //What is this used for?
timer = delayTimer;
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Add Special Events for Skills 1 Answer
Photon wont sync for the masterclient. 1 Answer
Unity Abstract Parent Class not in Build, but in Editor 0 Answers