0

Hello, I am trying to do time rewind in unity, but every time I am holding the action button it gives me this error:

ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of collection. Parameter name: index

and here's the c# code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TimeBody : MonoBehaviour
{

public bool isRewinding = false;
List<Vector3> positions;

void Start()
{
    positions = new List<Vector3>();
}

void Update()
{
    if (Input.GetKey(KeyCode.Mouse0))
        StartRewind();
    if (Input.GetKeyUp(KeyCode.Mouse0))
        StopRewind();
}

private void FixedUpdate()
{
    if (isRewinding)
        Rewind();
    else
        Record();
}

void Rewind()
{
        transform.position = positions[0];
        positions.RemoveAt(0);
}

void Record()
{
    positions.Insert(0, transform.position);
}

void StartRewind()
{
    isRewinding = true;
}

void StopRewind()
{
    isRewinding = false;
}
}

Please help I don't know where the error is

Aw0led
  • 1
  • 2
    You should check if the collection is not empty in `Rewind` method. – Bukk94 Feb 20 '20 at 14:10
  • Welcome to Stackoverflow, Where you exactly face this error?! on calling `Rewind` method ?! – Hamed Moghadasi Feb 20 '20 at 14:10
  • 2
    It's happening because you called `Rewind()` without having called `Record()` first, so `positions` is empty and therefore you cannot access `positions[0]`. – Matthew Watson Feb 20 '20 at 14:12
  • as already stated you have positions as a new List, and haven't put any value here at the start, so rewinding raises index error with index 0 – Atreyagaurav Feb 20 '20 at 14:14

0 Answers0