- Home /
The question is answered, right answer was accepted
instantiating prefabs from array
hi, am trying to instantiate prefabs from array. i don't get any errors in the script, but when i run the script the prefabs assigned in the inspector displays empty. need help on how to use arrays. thanks in advance.
using UnityEngine;
using System.Collections;
public class spawner : MonoBehaviour {
//public GameObject card;
//public GameObject card2;
public GameObject[] prefabPool;
// Use this for initialization
void Start () {
prefabPool = new GameObject[prefabPool.Length];
//int index = Random.Range(0,prefabPool.Length);
prefabCreation ();
}
// Update is called once per frame
void Update () {
}
public void prefabCreation()
{
for(int i = 0; i >= 4; i++)
{
for(int j = 0; j >= 4; j++)
{
//Instantiate(prefabPool[prefabIndex]);
Instantiate(prefabPool[prefabPool.Length]);
}
}
}
}
just remove the line no 14 prefabPool = new GameObject[prefabPool.Length];
Hope it will works
Also not sure what you are trying to do inside your PrefabCreation() method since:
Instantiate(prefabPool[prefabPool.Length]);
will result in Index Out of Range Exception. Plus looks like you are trying to achieve a grid based instantiation looking at your two for loops. If so you might also want to change the position at which the prefabs are instantiated based off the values of 'i' and 'j'.
prefabPool = new GameObject[prefabPool.Length]; => your array is empty!
am trying to do a matchup the cards type game, where i have to match two similar cards having same image. initially iam trying to test the code with 2 prefabs. i need to instantiate these prefabs initially two pairs of each(4) so i could match them. need help on the script how to instantiate from an array.
Answer by NikunjPopat · May 25, 2015 at 10:53 AM
public int numberOfPrefabs=5;
public GameObject[] prefabPool;
void Start()
{
prefabPool=new GameObject[numberOfPrefabs];
prefabCreation();
}
public void prefabCreation(){
for(int i=0;i<prefabPool.Length;i++){
Instantiate(prepfabPool[i]);
}
}
also need another help. i want all the prefabs to be instantiated at the center of the screen. do u have any idea how to do this. for example if i spawn at 0th point in the screen the following prefabs will spawn adding next to the first resulting in going out of camera.
Follow this Question
Related Questions
transform.rotation = Quaternion.Slerp "freaks out doesn't acutely track game object. 1 Answer
Script error about the semicolon. 1 Answer
how to instantiate gameobjects in a 2d array. 2 Answers
need help on prefab spawning 1 Answer
Can someone reshape my script so that it is more clean and tidy? it works just looks ugly 3 Answers