- Home /
instantiate a prefab from array and then changing it
i am trying to build a pickup item that when it instantiate it will randomly choose between 4 different prefabs and then will swap them randomly. The following script (JS) works well with changing the material of the game object, but i want it to do the same with prefabs as opposed to the materiel.
var materials : Material[];
var changeInterval = 1.0;
public var type:int;
var index : int = Time.time / changeInterval;
function Awake()
{
// set a random type to begin
SwapType();
}
function SwapType()
{
// generate a random number between 1 and 10
var random:float = Random.Range(1,100);
// set the type
if (random <= 25)
{
index = 0
}
else if (random >= 75)
{
index = 1;
}
else if (random >= 25 && random <= 50 )
{
index = 2;
}
else
{
index = 3;
}
}
function Update ()
{
if (materials.Length == 0)
return;
index = index % materials.Length;
// assign it to the renderer
renderer.sharedMaterial = materials[index];
}
//change type after time
// min and max times for type change
public var minTypeChange:int = 1;
public var maxTypeChange:int = 3;
function Start()
{
while (true)
{
// wait for X seconds
yield WaitForSeconds(Random.Range(minTypeChange, maxTypeChange));
// set a random type
SwapType();
}
}
Unfortunately, it is not very clear what you are asking to do. You can randomly pick a number and use that to deter$$anonymous$$e which prefab to instantiate.
It wasn't your question, but the SwapType() function can be replaced with just the line: index = Random.Range(0, materials.Length); assu$$anonymous$$g materials.Length > 0.
Answer by Rod-Green · Jan 02, 2012 at 04:35 AM
This will randomly Instantiate a prefab from a list .. however it is in c#
Add it to any object and set the prefab choices.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class RandomPrefab : MonoBehaviour
{
public List<GameObject> m_prefabChoices;
void Awake()
{
if(m_prefabChoices == null || m_prefabChoices.Count == 0)
return;
Instantiate(m_prefabChoices[Random.Range(0, m_prefabChoices.Count)], transform.position, transform.rotation);
DestroyImmediate(this.gameObject); // self descruct
}
}