- Home /
Add Value into Array between two elements
Well just as the title reads, I want to know if it is possible adding a new value into an array but instead of just building onto it I want to be able to pinpoint a current element (which I already have) and insert a new value into there while pushing the value that use to be there and all the remaining values after it up one level. So for example:
Original Array: "Mike","John","Dan","Steve";
I click on John which gives me it position and insert a new value pushing all the values after it up one.
New Array: "Mike","Arthur","John","Dan","Steve";
Answer by yoyo · Jan 12, 2011 at 10:34 PM
This is a general programming question, not really Unity. You didn't specify the language, so I'm going to assume C# (to improve my odds of a correct answer ;) for which the System.Array docs on MSDN are relevant.
Arrays are fixed length structures that do not support the dynamic insertion of new entries. If you want to insert into an array, you need to write the code to do it yourself.
A simple (but inefficient) way is something like this, assuming entries are strings, as in your example ...
List<string> mylist = new List<string>(myarray);
mylist.Insert(index, mynewstring);
myarray = mylist.ToArray();
This works because List does support dynamic insertion, and there are helper methods to convert between lists and arrays.
Note that you'll need to add "using System.Collections.Generic;" at the top of your script.
Anyone else want to take a crack at the javascript version?
Thanks a lot for your answer and sorry about being vague on the program$$anonymous$$g language. I am actually using Javascript. I am not that great at C# so is there like a Javascript equivalent to what you have done here?
This answer should help with translation ... http://answers.unity3d.com/questions/35939/help-on-translating-this-c-to-javascript
Answer by Justin Warner · Jan 12, 2011 at 10:33 PM
Check out ArrayList's, you can use the .add command to add in an object... I do think ArrayList's only use objects, but not 100. Check this for more info. Best I can do. Hope it helps!
As of .NET 2.0 it's generally preferable to use List -- all the benefits of ArrayList, plus type-safety.
I'm going by what we've learned in school, right now were doing objects with ArrayList's so that's why I mentioned it...
ArrayList is a valid approach, just a little dated ... not sure it deserves the downvote.