How to sense the amount of spots in an array not being used

So recently, I have tried to create a system that will detect when an object touches a cup, and then it will be stored in an array so that I can show it visibly and detect how many slots are holding something. The problem is that I don’t know how to detect how many spots in my array are being used, and then fill or deny filling the next slot. For example, lets say I let a tomato touch the cup, it will sense it, then fill the first spot in the array after it knows that currently, 0 spots are being used.

I currently have a system that detects whether the touching object is allowed to be stored, but don’t know how to figure out how many spots are being used. My array can store up to 3 GameObjects.

How can I detect how many spots are storing data in an array?

This is the first script I am currently using (creates the array):

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class IngredientStorer : MonoBehaviour
{
    public GameObject[] SmallCupIngredientArray = new GameObject[3];
}

This is the second script I am using:

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class IngredientDetection : MonoBehaviour
{
    public IngredientStorer ingStore;

    public GameObject ingAdded;

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.layer == 7)
        {
            Debug.Log("Ingredient detected");

            ingAdded = other.gameObject;

            if (ingStore.SmallCupIngredientArray. == 0) //Don't know what to put here to sense how many spots are taken in the array
            {
                ingStore.SmallCupIngredientArray[0] = ingAdded;
                Debug.Log("Ingredient " +  ingAdded.name + " added to array slot 0/2");
            }
        }
    }
}

Thanks! :slightly_smiling_face: As you can probably tell, i’m not the greatest at Unity, and help would be greatly appreciated.

1 Answer

1

An array has a fixed size. The only way to determine how many slots are “used” are to 1) manually keep track as you add/remove items or 2) search through the array.

You may be better off using a List.

Lists have a Count property which reports the number of elements in the list. You can also add or remove items based on their index or based on their value.

List<GameObject> myList = new List<GameObject>();

myList.Add(obj1);
myList.Add(obj2);
myList.Add(obj3);

//will print "3"
Debug.Log(myList.Count);

//remove the first entry equal to obj3
myList.Remove(obj3);

//remove the entry at index 0
myList.Remove(0);

//You can access the List with [] just like an array
Debug.Log(myList[0].name);

Thanks, I think that using a List will definitely work better for me.