Bugs (?) with lists

I think i have encountered some bugs while i was using lists. Here are my scripts:

The script where i define the list:

public class MyBox {
	
	public string objectName;
	public int objectWeight;

	public MyBox(string newObjectName, int newObjectWeight)
	{
		objectName = newObjectName;
		objectWeight = newObjectWeight;
	}
}

And now i have a script where i add things in the list and do some bug-finding

public class ObjectList : MonoBehaviour {
	List<MyBox> objectList = new List<MyBox> ();
	public MyBox sword = new MyBox("Sword", 50);
	public MyBox phone = new MyBox("Phone", 10);
	void Start () {
		// Init
		objectList.Add(sword);
		objectList.Add (phone);
	}
	void Update()
	{
                print(objectList.Count);
	}
	
}

(I know the names ended up weird…)

It prints nothing…
I tried to do “objectList.Contains(sword)” to check if there are any swords in the list and if yes, print something. It printed nothing.
This is a bug… or im doing something wrong.
Note: Im using Unity 2017.4.0f1

Hello there,

• There is nothing wrong with your code above. As mentioned by Hellium, check that your list isn’t being reset somewhere. You might also want to check that your Start() is getting called by printing the list count right after adding the items to it.

• If you are using Visual studio, click on objectList and then hit shift + F12; this will give you a list of all the instances where it is used. Since it’s private, it should all be contained within this same class.

• And finally, when you say it prints “nothing”, you mean 0, right? Just making sure…

• Also, and this is just because I don’t remember exactly how this works: could you try doing sword = new MyBox("Sword", 50); and phone = new MyBox("Phone", 10); in Start() instead, right before adding them to the list?

• Also also, try adding [System.Serializable] above you MyBox class definition, and try putting [SerializeField] in front of your List declaration. That way, you’ll be able to see the list and all of its items in the inspector directly, instead of having to print it out.


Hope that helps!

Cheers,

~LegendBacon