I am having troubles with a list. im adding an item, but after i add it, im trying to change certain values in the item i just added (its a list based off of a class with a string and a float) how do i access the newly created item?
Show us the CODE! ![]()
public void AddItem (string _name, float _weight) {
inventory.Add(new Item());
}
The you can do…
inventory[inventory.Count-1].whatever_your_variable_names_are = whatever;
…for the last item in the list (item just added) or what ever index number you wish to use.
A list works just like an Array.
If you need to manipulate the instance after adding it you would be better off with something like this, also why dont you set the name and weight at creation time?
public Item AddItem (string _name, float _weight)
{
var item = new Item(_name, _weight);
// var item = new Item() {Name = _name, Weight = _weight };
inventory.Add(item);
return item;
}
I think this about structs.
Lets say you have this:
List<Vector3> list = new List<Vector3>();
//add an item
list.Add(new Vector3(10.0f, 20.0f, 30.0f));
//lets say we want to change a member of the vector3 struct
list[0].x = 30; //this doesn't work :(
//you need to do this: (thats why I don't like structs in C#)
Vector3 tempVector = list[0];
tempVector.x = 30;
list[0] = tempVector;
Anyway the above is the solution I found to this error:
Cannot modify the return value of ‘System.Collections.Generic.List<UnityEngine.Vector3>.this[int]’ because it is not a variable
Edit: Apparently this behavior that is impossible in a List IS possible in a normal array.
Vector3[] array...
array[0].x = 30 //will work
Damn those value types ![]()
yeah, i got it working with this
private Item AddItem (string _name, float _weight) {
Item newItem = new Item() {name = _name, weight = _weight};
inventory.Add(newItem);
gameObject.GetComponent<MoveInfo>().SpeedMulti -= _weight / 10;
return newItem;
}[code/] (hopefully it works when i test it) thanks for all of your guy's help