- Home /
C# Timer and Spawning Prefabs - 2d Sidescroller
Hello,
I'm trying to work on my first unity game. It will be a side Scroller. For the Level i want to creat random Prefabs (about 10-15 different prefabs) every 5 seconds. Can you help me please?
This is my Code at the moment.
using UnityEngine;
using System.Collections;
public class GameManager : MonoBehaviour {
public float timer = 0f;
public GameObject TileSet1;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
timer += Time.time;
if (timer > 5f) //This wont call...
{
Instantiate(Resources.Load("TileSet1", typeof(GameObject)));
timer = 0f;
}
}
}
Answer by vptb · May 28, 2014 at 11:45 AM
Before asking a question you should search for similar questions, and when asking a question present your problem, in your question you only say what you want to create and then you pasted your code, you didn't say what is wrong with your code.
You can just add this to your script:
public List<GameObject> prefabs;
private void Start(){
InvokeRepeating("SpawnPrefab",0, 5.0f);
}
private void SpawnPrefab(){
//This will spawn them at (0,0,0) with (0,0,0) rotation
Instantiate(prefabs[Random.Range(0, prefabs.Count)], Vector3.zero, Quaternion.identity);
}
When you add your script to an object it will have a property on the inspector where you can add all your prefabs.
PS: Don't forget to add "using System.Collections.Generic;"
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
Spawning objects around a point 1 Answer
How to realize accurate time counter (millisecond precision) 3 Answers
Start timer on mouse0 click 1 Answer