Reputation: 11
I'm trying to make a simple explosion using Unity Prefabs but it keeps saying
error CS0021: Cannot apply indexing with [] to an expression of type `UnityEngine.GameObject'
I checked the code and I can't find the problem. Here is what I tried:
public GameObject[] ParticlePrefab;
public int amountOfPartcles = 3;
// Use this for initialization
void Start ()
{
for(int i = 0; i<amountOfPartcles; i++)
{
GameObject ParticlePrefab = Instantiate(ParticlePrefab[Random.Range(0,amountOfPartcles)]);
ParticlePrefab.transform.position = transform.position;
}
}
Upvotes: 0
Views: 2791
Reputation: 4112
The problem is that you use the same name (ParticlePrefab
) twice.
Also, are you sure that you want to the amount of particles variable to choose the particle. The way you do it, it could randomly crash if you have less different perfabs than the amount of particles needed.
Here is how you could do your start method:
void Start ()
{
const int numberOfPrefabs = ParticlePrefab.Length;
for(int i = 0; i<amountOfPartcles; i++)
{
GameObject particle = Instantiate(ParticlePrefab[Random.Range(0,numberOfPrefabs)]);
particle.transform.position = transform.position;
}
}
Upvotes: 1