When using input, array.Add replaces the last member

Hello, I have been trying to figure out a simple inventory script for a game I have been working on.

I want all the items in the inventory to be stored in a array. I am using the default java arrays.

It seems whenever I try to add a object to the array on a button trigger, it replaces the last member of the array.

function Update () {
      var tempInventory = new Array("first object");
      /*adding objects like this works fine*/
      tempInventory.Add("second object");

      /*if I do it this way, "second object" is replaced by third object*/
             tempInventory.Add("third object");


I have messed about with this for a while, I can’t see any reason why this should be happening. If anyone knows I would greatly appreciate it!


You’re creating a new array every frame in Update. You must create it outside Update to prevent this. Anyway, you’d be better off in the long run if you just pretend the Array class doesn’t exist…use built-in arrays if it’s fixed-size, or else generic List otherwise (such as in this case). Also, Unity doesn’t use Java. Java is not shorthand for Javascript, it’s a different language entirely.