In my game, you can’t carry two objects of the same type. For example you can’t carry two identical weapons. The code i currently have is this one, which is not working:
public List <GameObject> objects;
public void AddObject(GameObject newObject)
{
for(int i = 0; i < objects.Count; i++)
{
if(objects*.tag == newObject.tag)*
{
Destroy(newObject);
}
else
{
objects.Add(newObject);
}
}
}
Check if it contains the object 1st
if(!items.Contains(item))
items.Add(item);
if the list already contains that object it will not add it. You can also use a dictionary instead of a list, you can not add duplicates to a dictionary.
Sorry that does not check for items of the same type, you would have to compare that.
Try this instead:
public List<GameObject> objects;
public void AddObject(GameObject newObject)
{
bool isNew = true;
for (int i = 0; i < objects.Count; i++)
{
if (objects*.tag == newObject.tag)*
{
isNew = false;
break;
}
}
if (!isNew)
{
Destroy(newObject);
}
else
{
objects.Add(newObject);
}
}
Edit: Sorry missed the ! on the if.
public List items = new List();
public void AddObject ( GameObject newObject )
{
for( int i=0 ; i<items.Count ; i++ )
if( items*.tag==newObject.tag )*