Issued with adding a GameObject to a List

I have the following scripts:

using UnityEngine;
using System.Collections;

public class CubeInteraction : MonoBehaviour {
    protected static GameObject selectedCube;

    public void OnMouseDown() {
        GetComponent<SpriteRenderer>().color = Color.green;
  
        selectedCube = gameObject;
    }
}
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class CubeBehavior : CubeInteraction {
    private List<GameObject> selectedCubes;

    // Use this for initialization
    private void Start () {
        selectedCubes = new List<GameObject> ();
    }

    private void Update() {
        HandleSelectedCubes ();
    }

    private void HandleSelectedCubes() {
        if (selectedCube != null) {
            selectedCubes.Add (selectedCube);

            if (selectedCubes.Count == 4) {
                foreach (var cube in selectedCubes) {
                    Destroy(cube);
                }
            }
        }
//

    }
}

I want to get the GameObject that the first script is attached to and add it to a list. That works, but it continues adding it and never stops. Any idea why this happens?

Well, the reason it happens is because you keep calling .Add on it every frame. You can make it only have each one once using:

if (!selectedCubes.Contains(selectedCube) ) selectedCubes.Add(selectedCube);
1 Like

Thank you, that worked.