- Home /
Random Spawn, Random Prefab
Hey, I have made 9 spawn-points in my game, and i want to randomly spawn 1 of 4 prefabs! I don't really know how to script it, that the code isn't around 100 lines. Can anyone help me?
THX lixpoxx
P.S.:It would also be very nice if you can tell me how to make it, that the spawner sends a new Prefab if the old is ca. 1 Coordinate away!
Answer by YoungDeveloper · Sep 11, 2013 at 05:21 PM
Create a public array of 9 Transforms (or whatever depending on your teleport), and public array of 4 prefebs (GameObject). Generate two random number, like this:
int teleport = Random.Range(0,8);
int prefeb = Random.Range(0,3);
Then spawn it using "Instantiate": http://docs.unity3d.com/Documentation/ScriptReference/Object.Instantiate.html
Instantiate(gameobject_array[prefeb], teleport.position, teleport.rotation );
Save it, and add 9 transforms and 4 prefebs in inspector.
I don't know much about arrays, can you show me how you would do it?
public Transform[] teleport;
public GameObject[] prefeb;
void Start(){ //this will spawn only one prefeb, if you want call it many time, create a new function and call it or create for loop
int tele_num = Random.Range(0,8);
int prefeb_num = Random.Range(0,3);
Instantiate(prefeb[prefeb_num], teleport[tele_num].position, teleport[tele_num].rotation );
}
//And remember to asign all teleport transforms and prefebs in inspector
Answer by nithu · Nov 21, 2015 at 11:58 AM
using UnityEngine; using System.Collections;
public class spawner : MonoBehaviour {
// Use this for initialization
int m_CurrentSpawnCount=0,SpawnCount = 10;
public GameObject Enemy;
void Start () {
StartCoroutine("delayCall");
}
// Update is called once per frame
IEnumerator delayCall () {
//if(m_CurrentSpawnCount < SpawnCount)
{
for(int i = 0 ; i < 10 ; i++) // try 50 times. Brute force approach, randomly try to spawn and make sure its in the Spawnable zone.
{
Vector3 position = transform.position + Random.insideUnitSphere * 100;
position.y = this.transform.position.y;
RaycastHit hitInfo;
if(Physics.Raycast(position + new Vector3(0,1,0), Vector3.down,out hitInfo,10)&& hitInfo.collider.tag == "Spawnable")
{
Instantiate(Enemy,position,Quaternion.identity);
yield return new WaitForSeconds(1);
StartCoroutine("delayCall");
break;
}
}
}
}
}
Your answer
Follow this Question
Related Questions
How To Random Range a Float? 2 Answers
How to randomly spawn object without spawning the previous object in a row? 0 Answers
Random Prefab Spawner C# 2 Answers
Prefab script values do not update 2 Answers