我想实例化一个预制件,然后在由Unity中的随机数生成器随机选择的同一位置的另一个预制件之前实例化,但是当我启动它时,它将在不同位置创建第一个预制件。我想我应该更改spawnIndex的范围,但是它不允许我将其放在所有内容之上。这是我的代码:
window
答案 0 :(得分:4)
您发布的代码有几个错误:
int a
的声明必须在Start
或awake
上,但不能在类构造函数中,否则您将得到一个错误,也不会需要2个变量来完成所需的操作,因此我删除了int a
,并为所有内容使用了相同的索引“ spawnIndex”。因此,如果我们应用我提到的所有更改,则结果代码将为:
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);
}
}