- Home /
Instantiate Random Help
My script is coming up with a error of Instantiate Prefab is Null, what am I doing wrong? I am trying to create a random game object.`
public GameObject Frigate1;
public GameObject Frigate2;
public GameObject Frigate3;
public GameObject Frigate4;
public GameObject Frigate5;
string FrigateSelector;
void Awake()
{
int randomNumber = Random.Range (1, 5);
Debug.Log (randomNumber);
FrigateSelector = "Frigate" + randomNumber;
Debug.Log (FrigateSelector);
Instantiate (GameObject.Find("FrigateSelector"), Vector3.zero, Quaternion.identity);
}`
Answer by sam2k13 · Jan 11, 2015 at 04:19 AM
Since FrigateSelector is a string, the quotation marks are not necessary.
This could be done much easier with the use of an array.
Try this:
public GameObject [] Frigate;
void Awake()
{
Instantiate (Frigate[Random.Range (0, 4)], Vector3.zero, Quaternion.identity);
}`
do you have a good tutorial on using array, I do not know how to use that.
Answer by DoubleIsLoveDoubleIsLife · Jan 11, 2015 at 04:38 AM
public GameObject Frigate1;
public GameObject Frigate2;
public GameObject Frigate3;
public GameObject Frigate4;
public GameObject Frigate5;
string FrigateSelector;
void Awake()
{
int randomNumber = Random.Range (1, 5);
Debug.Log (randomNumber);
FrigateSelector = "Frigate" + randomNumber.ToString();
Debug.Log (FrigateSelector);
Instantiate (GameObject.Find(FrigateSelector), Vector3.zero, Quaternion.identity);
}`
If your object is not in the scene, put Your prefabs in a 'Resources' folder and then use this script:
public GameObject Frigate1;
public GameObject Frigate2;
public GameObject Frigate3;
public GameObject Frigate4;
public GameObject Frigate5;
string FrigateSelector;
void Awake()
{
int randomNumber = Random.Range (1, 5);
Debug.Log (randomNumber);
FrigateSelector = "Frigate" + randomNumber;
Debug.Log (FrigateSelector);
Instantiate (Resources.Load(FrigateSelector), Vector3.zero, Quaternion.identity);
}`
Your answer
Follow this Question
Related Questions
spawn muzzle flash with random rotation? 2 Answers
Instantiate a random prefab at an objects location 3 Answers
Instantiating a random prefab from array. 1 Answer
How to instantiate prefabs between 2 objects like a path 0 Answers
Random instantiate at same frame with each instantiate having unique random direction 1 Answer