I am trying to create a game sort of like subway surfers and I want to Instantiate an obstacle every time a platform is Instantiated. There are going to be different types of platforms and different types of obstacles are going to spawn for each different platform. So, I created a gameobject array for Platforms and a gameobject array for the Obstacles. I don't know how I should go about this situation. I don't want to spawn an obstacle by using the start method from a script attached to each obstacle because I would need to use FindGameObjectsWithTag to get an obstacle array so I can instantiate an object because I'm pretty sure that FindGameObjectsWithTag uses quite a bit of cpu usage. Can you think of a way to insantiate an obstacle without using the start method?
[SerializeField] private GameObject[] platforms;
[SerializeField] private GameObject[] obstacles;
[SerializeField] private Transform playerTrans;
[SerializeField] private byte spawnAmount;
private List activePlatforms = new List();
private float spawnZ = 0f;
private float tileLength;
private int safeZone = 15;
private void Start()
{
platforms = GameObject.FindGameObjectsWithTag("Platform Prefab");
obstacles = GameObject.FindGameObjectsWithTag("Obstacle");
tileLength = platforms[0].transform.localScale.z;
Debug.Log(tileLength);
for (int i = 0; i < spawnAmount; i++)
_SpawnPlatform(0);
}
private void FixedUpdate()
{
if (playerTrans.position.z - safeZone > (spawnZ - spawnAmount * tileLength))
{
_SpawnPlatform(Random.Range(0, platforms.Length + 2));
DestroyPlatform();
}
}
private void _SpawnPlatform(int spawnIndex)
{
GameObject go = Instantiate(platforms[spawnIndex]) as GameObject;
go.transform.position = Vector3.forward * spawnZ;
go.transform.parent = transform;
go.transform.rotation = Quaternion.Euler(Vector3.zero);
spawnZ += tileLength;
activePlatforms.Add(go);
}
private void DestroyPlatform()
{
Destroy(activePlatforms[0]);
activePlatforms.RemoveAt(0);
}
}
↧