- Home /
Question by
Miso-c9 · Feb 17, 2018 at 07:36 AM ·
instantiatearrayrandom.range
how to have an array in instantiate function
heres my code btw i have 3 errors.. xD
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class powerUpManager : MonoBehaviour {
public GameObject[] powerUpPrefab;
public Vector3 center;
public Vector3 size;
void Start()
{
InvokeRepeating("SpawnFood",5f,5f);
}
void SpawnFood()
{
Vector3 pos =center+ new Vector3(Random.Range(-size.x/2,size.x/2),Random.Range(-size.y/2,size.y/2),Random.Range(-size.z/2,size.z/2));
Instantiate (Random.Range(0,powerUpPrefab), pos, Quaternion.identity);
}
void OnDrawGizmosSelected()
{
Gizmos.color = new Color (0, 1, 0, 0.5f);
Gizmos.DrawCube (center, size);
}
}
Comment
You say u have 3 errors, but you didn't write WHERE the errors are..
For first look I see mistake there
Instantiate (Random.Range(0,powerUpPrefab), pos, Quaternion.identity);
You mean powerUpPrefab.Length, hm? And you don't refer to array, just length of array.
Best Answer
Answer by yummy81 · Feb 17, 2018 at 09:17 AM
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class powerUpManager : MonoBehaviour {
public GameObject[] powerUpPrefab;
public Vector3 center;
public Vector3 size;
void Start()
{
InvokeRepeating("SpawnFood",0.5f,0.5f);
}
void SpawnFood()
{
Vector3 pos =center+ new Vector3(Random.Range(-size.x/2,size.x/2),Random.Range(-size.y/2,size.y/2),Random.Range(-size.z/2,size.z/2));
//Modify the line below as follows, and everything will work fine:
Instantiate (powerUpPrefab[Random.Range(0,powerUpPrefab.Length)], pos, Quaternion.identity);
}
void OnDrawGizmosSelected()
{
Gizmos.color = new Color (0, 1, 0, 0.5f);
Gizmos.DrawCube (center, size);
}
}
Answer by Jasmin1347 · Feb 17, 2018 at 07:47 AM
public GameObject[] powerUpPrefab;
int temp = Random.Range (0,powerUpPrefab.Length);
void spwanobj()
{
GameObject objs;
objs=Instantiate(powerUpPrefab[temp],pos,powerUpPrefab[temp].transform.rotation);
}