x


Undo/back system using a List/Array

In my game the player can only move between MoveNodes. On colliding with the node, it adds the node name to a List. So as I travel around I amass a large list of previously visited MoveNodes.

On certain nodes a "back" button appears, which should send the player back to the 2nd most recent MoveNode in the List. How do I do this? Do I get the Length - 1 or something?

Also, can I clear anything but the most recent 5 objects in the list so it doesn't get so big?

more ▼

asked May 21 '11 at 02:13 PM

Stardog gravatar image

Stardog
224 21 29 36

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

Something like this (i'm assuming your array is called nodes):

var targetNodeIndex : int;
var targetNode : GameObject;

//the function called by your back button
function GoBack()
{
  targetNodeIndex = nodes.length - 2;
  //retrieves the second to last node. Eg in a 5 node array - this returns node 4.
  targetNode = nodes[targetNodeIndex];
}

We use "length-2" because nodes.length will return the length of the array BUT in a 5 node length array the elements will be in indexes 0,1,2,3, and 4. So to get at the second to last node we need to access the index that is 2 less than the length.

Once you have retrieved your node just set the players transform to the same as the node trnasform.

more ▼

answered May 21 '11 at 02:55 PM

GesterX gravatar image

GesterX
2.1k 13 16 37

Thanks. My back button runs this code now:

allPreviousLocations[0].transform.position

I'll work on improving the functionality with those variables.

May 21 '11 at 04:08 PM Stardog
(comments are locked)
10|3000 characters needed characters left

You can create a List of MoveNodes, then use the List functions Add, Remove, etc. and its property Item for managing and accessing the items as you want. You can see an example here:

http://forum.unity3d.com/threads/79760-How-to-use-generics-in-unity-javascript?p=510611#post510611

The reference for the List methods and properties is here:

http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx

more ▼

answered May 21 '11 at 02:54 PM

Edy gravatar image

Edy
637 2 5 17

Thanks, this let me limit the size: if list.Count > 2 list.RemoveRange(0, 1)

May 21 '11 at 04:06 PM Stardog
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1358
x356
x355
x29
x28
x22

asked: May 21 '11 at 02:13 PM

Seen: 978 times

Last Updated: May 21 '11 at 04:08 PM