Reputation: 35
I want to instantiate a prefab before another prefab on the same place chosen randomly by a random number generator in Unity but when I start it, it creates the first prefab on different place. I guess I should change the scope of spawnIndex, but It doesn't allow me to put it on top of everything. Here is my code :
public Transform[] SpawnPoints;
public Transform[] EffectPoints;
public float spawnTime = 1.5f;
public float effectSpawnTime = 1f;
public GameObject Coins;
public GameObject Effect;
int a = Random.Range(0, 4);
// Use this for initialization
void Start()
{
InvokeRepeating("SpawnParticle", effectSpawnTime, effectSpawnTime);
InvokeRepeating("SpawnCoins", spawnTime, spawnTime);
}
// Update is called once per frame
void Update()
{
}
void SpawnCoins()
{
int spawnIndex = Random.Range(0, 4);
Instantiate(Coins, SpawnPoints[spawnIndex].position, SpawnPoints[spawnIndex].rotation);
}
void SpawnParticle()
{
int spawnIndex = Random.Range(0, 4);
Instantiate(Effect, EffectPoints[spawnIndex].position, EffectPoints[spawnIndex].rotation);
}
Upvotes: 0
Views: 521
Reputation: 4283
The code you posted have a couple of errors:
int a
must be on Start
, or awake
, but not in the class constructor, or you will get an error, also you don't need 2 variables to accomplish what you want, so I deleted int a
and use the same index "spawnIndex" for everything.So if we apply all the changes that I mentioned, the result code will be:
using UnityEngine;
public class Test : MonoBehaviour {
public Transform[] SpawnPoints;
public Transform[] EffectPoints;
public float spawnTime = 1.5f;
public float effectSpawnTime = 1f;
public GameObject Coins;
public GameObject Effect;
int spawnIndex = 0;
int maximumRandomRange = 0;
// Use this for initialization
void Start()
{
//Initialize the variable
spawnIndex = Random.Range(0, maximumRandomRange);
maximumRandomRange = SpawnPoints.Length; //or EffectPoints.Length, as they got the same
InvokeRepeating("SpawnParticle", effectSpawnTime, effectSpawnTime);
InvokeRepeating("SpawnCoins", spawnTime, spawnTime);
}
void SpawnCoins()
{
Instantiate(Coins, SpawnPoints[spawnIndex].position, SpawnPoints[spawnIndex].rotation);
}
void SpawnParticle()
{
spawnIndex = Random.Range(0, maximumRandomRange); //You only need to call it here again, as it is the function which is called faster
Instantiate(Effect, EffectPoints[spawnIndex].position, EffectPoints[spawnIndex].rotation);
}
}
Upvotes: 4