- Home /
C# Adding to an Array
I have this problem in C# where when I try to add an item to an array, it simply makes the array blank. No error is produced.
My code for adding an item:
public void AddItem ( string itemName , int qty , string type ){
Item itemToAdd = new Item();
itemToAdd.name = itemName;
itemToAdd.quantity = qty;
itemToAdd.type = type;
ArrayList itemsResizeableArray = new ArrayList();
//Debug.Break();
if ( items != null && items.Length != 0 )
{
itemsResizeableArray = new ArrayList( items );
}
itemsResizeableArray.Add( itemToAdd );
items = itemsResizeableArray.ToArray() as Item[];
}
I would rather not use Lists because I would need to change a large portion of my Unity Project. I create the Array here:
public Item[] items;
and declare the class:
[System.Serializable]
public class Item
{
public string name = "";
public int quantity = 1;
public string type = "";
}
I would like help making my function actually add an Item to the array.
Thanks in advance.
Just use a generic List (not ArrayList, that's obsolete). The changes needed are $$anonymous$$imal and your project will be much better ins$$anonymous$$d of trying to hack arrays to do things they're not meant for.
Just to add to Eric5h5's comment, have a look at System.Collections.Generic.
Which line is it that is deleting your array? Isn't line 7 and 11 pretty redundant?
Answer by ArkaneX · Sep 18, 2013 at 07:50 AM
ArrayList.ToArray() returns object[]. You can't cast it to Item[], so using 'as' keyword causes items to be null again. To be able to accomplish this, you can change your line to:
items = itemsResizeableArray.ToArray(typeof(Item)) as Item[];
But, please DON'T do this, and instead change your variable definition to
public List<Item> items;
as @Eric5h5 suggested. With this change, instead of calling AddItem("x", 1, "y"), you can simply do
items.Add(new Item
{
name = "x",
quantity = 1,
type = "y"
});
or you can add proper constructor to your Item class, and just call
items.Add(new Item("x", 1, "y"));
You'd need to modify your code of course, but I strongly suggest doing it. Even if you use this variable in 100 lines, most of them won't require any change, and you can fix all in a matter of minutes.
I guess I'll have to transition to lists. Currently I'm transitioning to C# from UnityScript and I'm trying to keep everything pretty much exactly as I did it before until I finish converting my scripts. Thanks for the help!
i don't think you can use Add() in C# it didn't work for me
Your answer
Follow this Question
Related Questions
Error passing class in method c# 3 Answers
Writing an class array to disk? 1 Answer
[CLOSED] When I use this code that I made, it adds to the item catalogue too? [CLOSED] 1 Answer
Can't Assign Item In Array 1 Answer
Inventory AddItem help 1 Answer