So I have a list. To this list I add gameObjects that I spawn with my spacebar. But I want to have a limit on how many you can spawn. So when the list reaches 4 gameObjects. Remove the first one and move every other gameobject in the list down one step.
But I’m having a problem trying to create a short and efficient way of doing this. The shortest way so far without having to use some kind of FindGameObjects is to put a script into the prefabs that spawns that counts up. But this seems a bit far fetched and I think that there is a better way to solve it.
The problem that I have now is that the Destroy method tries to destroy the entire prefab instead of the gameobject in the list even though I have specified the object in the list in the Destroy method.
This is what I got so far:
public class cubeShooter : MonoBehaviour {
public GameObject material;
public int materialSpawnLimit;
public List<GameObject> spawnedCount;
public Vector3 spawner;
// Use this for initialization
void Start () {
spawner = new Vector3(transform.position.x + 2, transform.position.y, transform.position.z);
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown("space")){
SpawnObject(material);
}
}
void SpawnObject(GameObject material){
spawnedCount.Add(material);
Instantiate(spawnedCount[spawnedCount.Count - 1], spawner, Quaternion.identity);
CheckSpawnedCount();
}
void CheckSpawnedCount(){
if(spawnedCount.Count > materialSpawnLimit){
for(int i = 0; i < spawnedCount.Count; i++){
if(i == 0){
Destroy(spawnedCount*);*
First of all, material is used as a Prefab, but it gets added to the spawnedCount list. Why? Wouldn’t make it more sense to add the instantiated clone to the list? This would also get rid of the problem that the prefab is destroyed. It’s also bad practice to use the same variable name for a variable in the main body of the script as well as a parameter name of a function, and I’m surprised you don’t get an error for that.
Since it’s a list, items don’t need to moved manually; if an item is removed, the list automatically shrinks.
Solved it myself by just adding 3 cubes into the scene and moving them around for the same effect. I put them under the map so that they’re not seen. This also shortened the code a lot.
public GameObject material;
public GameObject clone;
public int materialSpawnLimit;
public GameObject[] spawnedCount;
public int currentCube;
public Vector3 spawner;
// Use this for initialization
void Start () {
spawner = new Vector3(transform.position.x + 2, transform.position.y, transform.position.z);
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown("space")){
currentCube++;
if(currentCube > 2){
currentCube = 0;
}
SpawnObject(spawnedCount[currentCube]);
}
}
void SpawnObject(GameObject mat){
mat.GetComponent<Collider>().attachedRigidbody.useGravity = true;
mat.transform.position = spawner;
}