- Home /
Unity add a item to a list?
Hey guys. So im having some trouble.
What im trying to do is add a item called testCanteen from my assets into a list called inventory.
list:
List<GameObject> inventory = new List<GameObject>();
adding item:
inventory.Add(new GameObject("canteenTest"));
Now im pretty sure with the quotes it wont create the object i need as it says it doesnt exist.
So what im wandering is how do i add a item from the assets bar into a list so i can then instantiate it and parent it to the players camera?
Answer by MarksTeq · Oct 22, 2014 at 11:44 PM
Create a canteen prefab.
Code something like:
using UnityEngine; using System.Collections; using System.Collections.Generic;
public class Canteen : MonoBehaviour { List inventory = new List(); } Drag your canteen prefab into an object slot:
This should allow you to instantiate any prefab in the list.
Then instantiating and parenting to camera can look something like:
void MakeCanteen()
{
Instantiate(inventory[0]);
inventory[0].GetComponent<Transform>().parent = Camera.main.transform;
}
Ignore my previous comment, I didn't use my eyes correctly, This was the perfect solution. Thank you VERY much!
You can do this faster by just adding the prefabs to a public list directly via the inspector.
@Bored$$anonymous$$ormon You sir are a genius and a scholar! Edited :)
TIL: unity answers will sometimes refresh the comments on an answer, but not the answer itself.
Answer by Habitablaba · Oct 22, 2014 at 11:36 PM
Drag the object you want into the edit area and tweak it to be like you want it.
Then, drag it back to the project pane in order to turn it into a prefab.
Now remove the object you put into the scene, as you don't need it any more.
Next, in the script, add a member variable of type GameObject, and drag the prefab over to it.
Finally, call Instantiate() to create a new version of the prefab, twiddle the bits to get it how you want it for this instance, and shove that into your list.
I mean a variable at class scope. If this is something foreign to you, I strongly suggest you spend some time watching tutorials and reading up on the basics of program$$anonymous$$g in modern languages like C#