- Home /
Question by
ansh93 · Jul 23, 2012 at 04:34 PM ·
javascriptinstantiate
How to Select between two prefabs randomly ?
#pragma strict
function Start () {
}
var enemy1 : GameObject ;
var prefab: GameObject ;
var prefab2 : GameObject ;
function Update ()
{
}
function OnTriggerEnter(Trigger : Collider)
{
if(Trigger.tag == "Player")
{
var instance : GameObject = Instantiate (enemy1,transform.position + Vector3(20,0,0),transform.rotation);
var instance2 : GameObject = Instantiate (prefab,Vector3(Random.Range(transform.position.x,transform.position.x+20),3,0),transform.rotation);
}
}
This the the code I am using to instantiate triggers. My Doubt is that in line 20 i.e
var : instance2 : GameObject = Instantiate (prefab,Vector3(Random.Range(transform.position.x,transform.position.x+20),3,0),transform.rotation);
is there any way that the Instantiate function selects one of the two GameObjects i.e "prefab and prefab2" randomly instead of directly using "prefab"
Comment
Best Answer
Answer by fafase · Jul 23, 2012 at 04:43 PM
Create an array of game object and fill it with the prefabs. You can also drag them in the inspector instead of declaring them in the script.
var go = new GameObject[3];
var enemy1 : GameObject ;
var prefab: GameObject ;
var prefab2 : GameObject ;
function Start(){
go[0]= enemy1;
go[1]=prefab;
go[2]=prefab2;
}
then call like this:
var instance : GameObject = Instantiate (go[Random.Range(0,3)],transform.position + Vector3(20,0,0),transform.rotation);
Your answer
Follow this Question
Related Questions
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Setting Scroll View Width GUILayout 1 Answer
Putting instantiate inside a variable 2 Answers
Instantiate prefab on a grid pattern? 1 Answer
instantiate at mouse problems 0 Answers