Thomas Slade
Thomas Slade

Reputation: 177

Moving an array element from [1] to [0]

You'd think it'd be the easiest thing in the world, but I can't find any solutions that don't involve complications that I don't need or use approaches that I don't understand.

I have an array of objects in unity, with three positions in the array. Each time the script is run, among other things, the cube in question is set to [1], a new cube is created in front of this cube and set to [2], and the previous cube, if there is one, is set to [0]. As a result of this, the array should be constantly updating so that cubes activated by the player are shifting down the array. It works fine in all respects except that [0] keeps returning null on the debug.

Since the cube before the one in question will already be set to [1], the first step in the code is to change this to [0]/ I've been trying to do this with;

objectList[0] = objectList[1];  // Demotes current object[1] to [0].

I understand that many people have been writing their own functions and using the splice method to avoid running out of array space, but I really don't need this kind of complexity. I just need to set the object in position [1] to position [0]. I hope I'm not missing a simple keyword in the API or anything.

Upvotes: 0

Views: 311

Answers (1)

user229044
user229044

Reputation: 239240

I think you're just trying to remove the front-most item, and "reindex" the array, so that what was at index 1 is now at index 0. If that's the case, you just want array.shift. It removes the front-most item.

var items = [1,2,3]

alert(items[0]); // 1

items.shift()

alert(items[0]); // 2

items.shift()

alert(items[0]); // 3

Upvotes: 3

Related Questions