playMaker

Author Topic: ArrayGetNext iterates twice on last item before looping  (Read 568 times)

nickfourtimes

  • Playmaker Newbie
  • *
  • Posts: 27
    • View Profile
ArrayGetNext iterates twice on last item before looping
« on: May 23, 2018, 12:42:13 PM »
Hey folks, wasn't sure if this should be reported as a bug or a request, but it seemed more like unintended behaviour so I'm putting it here.

We've got an array of, say, five floats: 1, 2, 3, 4, 5. We were using ArrayGetNext to iterate through the list and print out the numbers in turn, but it always seems to print out the last item twice, as in:
1, 2, 3, 4, 5, 5, 1, 2, 3, 4, 5, 5, 1, 2, 3, 4, 5, 5, ...

We don't have a "finished" or "loop" event on the action, just letting the state finish naturally and loop back onto itself. On investigation in the ArrayGetNext script, the problem was at this line:
Code: [Select]
void DoGetNextItem()
{
// no more children?
// check first to avoid errors.

if (nextItemIndex >= array.Length)
{
nextItemIndex = 0;
currentIndex.Value = array.Length -1;
Fsm.Event(finishedEvent); // this "early out" is the problem
return;
}

// get next item

result.SetValue(array.Get(nextItemIndex));
...

Basically, if you reach the end of the array, this fires the finishedEvent and stops the action immediately, before changing the result value. So even though this action finishes and internally has reset to index 0, it doesn't update the exposed 'result' variable, which is why we have to run through it twice to start the array over.

I was able to fix this problem as follows:
Code: [Select]
void DoGetNextItem()
{
// no more children?
// check first to avoid errors.

if (nextItemIndex >= array.Length)
{
nextItemIndex = 0;
currentIndex.Value = array.Length -1;
if(null != finishedEvent)
{
Fsm.Event(finishedEvent);
return;
}
}

// get next item

result.SetValue(array.Get(nextItemIndex));
...

This way, if we don't have a finishedEvent, we'll update the result value as intended before finishing the action.

Again, I'm not sure if that's the intended behaviour, or if my hack is a safe fix – it worked in our case, but I don't know PlayMaker's idiosyncrasies well enough to know if this is wise. Anyway, thought I'd point it out.
« Last Edit: May 23, 2018, 12:44:05 PM by nickfourtimes »

djaydino

  • Administrator
  • Hero Member
  • *****
  • Posts: 4613
    • View Profile
    • jinxtergames
Re: ArrayGetNext iterates twice on last item before looping
« Reply #1 on: May 25, 2018, 07:48:26 AM »
Hi.
The "array get next" should be used with a loop and finish event.

Have a state connected with the loop event
In that state do what you need to do with the variable result from the array get next.
Then connect back to the state with the "array get next" action.

Connect the finished event to a state where it should go when the iterate is done.