Limit Instantiation?

I’m trying to make something where you click on a button, and a set of spheres pop up. The problem is, when you click multiple times, a 2nd,3rd,etc. Set of spheres are instantiated. What’s a good way to limit it, like to check if the spheres are already instantiated?

And in clicking off the button, it should “destroy” the spheres… but Unity’s not letting me destroy them for some reason.

Generally:

Keep track of how many spheres you’ve instantiated. Stop creating more once you’ve hit a limit.

Keep track of the individual spheres, too, so that you can call Destroy() on them.

An example in C#:

using UnityEngine;
using System.Collections.Generic;

public class Limit : MonoBehaviour {
	List<GameObject> spheres = new List<GameObject>();
	
	public int maxSpheres = 5;
	public GameObject spherePrefab; //populate in inspector!
	
	void OnGUI() {
		//allow user to make a new sphere (up to limit)
		if (GUILayout.Button("Make sphere")) {
			if (spheres.Count < maxSpheres) {
				GameObject sphere = (GameObject)Instantiate(spherePrefab);
				spheres.Add(sphere);
			}
			else {
				Debug.Log("Already at max spheres");
			}
		}
		
		//allow user to destroy all spheres
		if (GUILayout.Button("Destroy spheres")) {
			foreach (GameObject sphere in spheres) {
				Destroy(sphere);
			}
			spheres.Clear();
		}
	}
}

Note the use of if statements to control program logic.

I use a List to store references to spheres I’ve created. You could use other collection types.