- Home /
noobHell, prefab arrays, GameObjects, Random Spawning
I have the basics of my game working. Random GameObjects from an array are instantiated as clones and do their thing. But, I keep reading that it's best to use prefabs, which seem limited to me because they can't pass variables very well and I'm having the hardest time making an array work with prefabs.
Does using prefabs cut down on clones and improve performance?
Here's my code, trying to make an array of prefabs from a folder, then instantiate a random one using a switch:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameControllerPrefabs : MonoBehaviour
{
//array of enemies
public GameObject[] allenemies;
//where to spawn
float enemyrandX;
public Vector2 enemywhereToSpawn;
//when to spawn
public float enemyspawnRate;
float enemynextSpawn = 0f;
//what enemy to spawn
int whatEnemyToSpawn;
void Start()
{
//This works with tags
//allenemies = GameObject.FindGameObjectsWithTag("Enemies");
//This does not work
allenemies = Resources.LoadAll("Enemies") as GameObject[];
}
// Update is called once per frame
void Update()
{
//set what to spawn when
enemyspawnRate = Random.Range(1f, 3f);
whatEnemyToSpawn = Random.Range(0, allenemies.Length);
if (Time.time > enemynextSpawn)
{
enemynextSpawn = Time.time + enemyspawnRate;
enemyrandX = Random.Range(7f, -7f);
enemywhereToSpawn = new Vector2(enemyrandX, transform.position.y);
switch (whatEnemyToSpawn)
{
case 0:
Instantiate(allenemies[0], enemywhereToSpawn, Quaternion.identity);
break;
case 1:
Instantiate(allenemies[1], enemywhereToSpawn, Quaternion.identity);
break;
case 2:
Instantiate(allenemies[2], enemywhereToSpawn, Quaternion.identity);
break;
case 3:
Instantiate(allenemies[3], enemywhereToSpawn, Quaternion.identity);
break;
case 4:
Instantiate(allenemies[4], enemywhereToSpawn, Quaternion.identity);
break;
}
}
}
}
Many thanks!
Answer by dan_wipf · Nov 23, 2018 at 08:20 PM
prefabs do not increase decrease performance, because they’re just like saved templates from a gameobject, might read the docs about prefabs.
alltough they increase workflow
Your answer
Follow this Question
Related Questions
When should I use prefabs? 2 Answers
Moving Gameobject and Reseting Issues 3 Answers
Drag and Drop onto Array of Custom Objects 0 Answers
How can I store different number of values using lists and arrays? 0 Answers