adding objects to an list

Hello,

I’m trying to add object names to a list if the object is clicked and remove it from the list if the object is clicked again.
But it seems like it’s always a new list if I click on an object. If I click an object and print the list, it only contains the clicked object even if I have clicked other objects before and if I click an object again, it says the list was already empty. I’m not sure how I can avoid this and permanently store the object names in one list.
That’s what I have right now:

private bool b = false;
List<string> itemList;

    public void Start()
    {
        itemList = new List<string>();
    }

    public void OnMouseClick()
    {
        if (b == false)
        {
            itemList.Add(this.name);
            b = true;
        } else
        {
            if (!itemList.Any())
            {
                Debug.Log("Empty List");
            } else
            {
                itemList.Remove(this.name);
            }
            b = false;
        }

//print elements on console
        if (!itemList.Any())
        {
            Debug.Log("Empty List");
        } else
        {
            Debug.Log("Not empty List: ");
            foreach (string s in itemList)
            {
                print(s);
            }
        }

looks to me like you have this script on every clickable object, which is why only one object is ever in the list, because it is one list for every object.

You need to create a separate script which holds the list:

public class ItemList : MonoBehaviour
{
    bool b;
    public List<string> itemList = new List<string>();

    public void AddOrRemove(string s)
    {
        if (itemList.Contains(s))
            itemList.Remove(s);
        else
            itemList.Add(s);

        // debug only
        print("List holds " + itemList.Count + " strings");
        foreach (string str in itemList)
            print(str);
    }
}

and a script (attached to every clickable object):

using UnityEngine;

public class Item : MonoBehaviour
{
    public ItemList list;

    public void OnMouseClick()
    {
        list.AddOrRemove(name);
    }
}
1 Like

Then I get the NullReferenceException “Object reference not set to an instance of an object”

You need to drag in a reference to the ItemList for each Item component.

yes add the itemList script to an empty game object, and the item script to every clickable object.
And then, like Kwinten said, drag the empty game object with the itemList script attached into the public “list” field of every clickable object.

or you could give the empty game object with the itemList script a tag and let the item script find it by tag in the start method.

How do I do that? What public “list” field do you mean?