- Home /
Question by
juancmaz · May 17, 2021 at 08:15 PM ·
scripting problemarraylist
How not to add an object to an array/list if there's already an identical one.
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[i].tag == newObject.tag)
{
Destroy(newObject);
}
else
{
objects.Add(newObject);
}
}
}
Comment
public List<GameObject> items = new List<GameObject>();
public void AddObject ( GameObject newObject )
{
for( int i=0 ; i<items.Count ; i++ )
if( items[i].tag==newObject.tag )
{ Destroy( newObject ); return; }
items.Add( newObject );
}
public Dictionary<string,GameObject> items = new Dictionary<string,GameObject>();
public void AddObject ( GameObject newObject )
{
if( items.ContainsKey(newObject.tag) ) Destroy( newObject );
else items.Add( newObject.tag , newObject );
}
Answer by logicandchaos · May 18, 2021 at 05:17 PM
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.
Answer by HellsHand · May 17, 2021 at 08:57 PM
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[i].tag == newObject.tag)
{
isNew = false;
break;
}
}
if (!isNew)
{
Destroy(newObject);
}
else
{
objects.Add(newObject);
}
}
Edit: Sorry missed the !
on the if
.