'm trying to instantiate a GameObject that is inside of a list, but in order to instantiate it i have to know it’s index. How do i do this?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Inventory : MonoBehaviour {
public GameObject stick;
public GameObject stone;
private GameObject[] itemIndex;
private List<GameObject> inventory;
/*
Item 0 = stick
Item 1 = stone
*/
void Start () {
itemIndex = new GameObject[] {stick, stone};
inventory = new List<GameObject> {};
}
public List<GameObject> addItem (int i) {
inventory.Add (itemIndex*);*
you would have to use a Predicate <GameObject>
to find your desired GameObject so try this:
public List<GameObject> dropObject(GameObject gameObjectYouWantToDrop) {
//if you want to find the gameObject itself, just replace FindIndex with Find
Vector3 myLocation = new Vector3 (x,y,z);
int indexOfYourGameObject = inventory.FindIndex(x => x.Equals(gameObjectYouWantToDrop));
Instantiate (inventory[indexOfYourGameObject] , myLocation);
inventory.RemoveAt(indexOfYourGameObject);
return inventory;
}
int stickIndex,stoneIndex;
void Update () {
stickIndex = inventory.FindIndex(d => d == stick.gameObject);
stoneIndex = inventory.FindIndex(d => d == stone.gameObject);
}
or you can put the code any where if not necessary in Update.
Might be beyond what you are trying to achieve, but situation arises that you are accruing multiple of the same kind of object, so you might eventually want to consolidate your inventory, e.g you are carrying 45 stones, and 50 sticks, you want to drop that item, it doesn’t really matter where in the inventory it is located, you just want to remove a specified item from it.
Consider using a Dictionary
Dictionary<GameObject, List<GameObject>> inventory = new Dictionary<GameObject, List<GameObject>>();
public void AddItem(GameObject item)
{
if (!inventory.ContainsKey(item))
{
inventory.Add(item, new List<GameObject>(){item});
}
else
{
inventory[item].Add(item);
}
}
public void DropObject(GameObject item)
{
if (inventory.ContainsKey(item))
{
Instantiate(item);
inventory[item].RemoveAt(0);
if (inventory[item].Count == 0)
{
inventory.Remove(item);
}
}
}
So if the item you are picking up doesn’t exist already in the dictionary, add it to the dictionary, if the gameobject key already exists in the dictionary it gets added to gameobject list for that key.
When you remove it, if it doesn’t exist in the dictionary, it won’t do anything. If it does it will subtract it from the gameobject list associated to that key associated to that gameobject, if the list becomes empty when you remove it, it the key gets removed from the dictionary.