- Home /
ArgumentOutOfRangeException: Argument is out of range. Parameter name: index What am I doing wrong?
When I move in the game, I get "ArgumentOutOfRangeException: Argument is out of range. Parameter name: index" pointing towards the "Playerpos[0] = fx;" Line! I understand an easy fix would be to make Playerpos a vector2, but because I am serializing Playerpos, it can't be a Vector2, so I believe this is the only way. What I am wanting is Playerpos to look like a vector2 (x,y) without it looking like a record of the player moves.
Basically, I am asking how to replace an element (Playerpos[0]) with an x/y coordinate?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PlayerMovement : MonoBehaviour {
[HideInInspector]
public List<float> Playerpos;
private float x;
private float y;
private float fx;
private float fy;
private float speed;
private GameObject c;
private float cz;
[HideInInspector]
public Vector2 playerpos;
void Start(){
c = GameObject.Find("Main Camera");
cz = c.transform.position.z;
x = this.transform.position.x;
y = this.transform.position.y;}
void Update () {
if (Input.GetButtonDown("Horizontal") && Input.GetAxisRaw("Horizontal") > 0 && Physics.CheckSphere(new Vector2((x+1),y), 0)){
print("right");
fx += 1;
transform.position = new Vector3(fx, y, -2);
c.transform.position = new Vector3(fx, y,cz);
Playerpos[0]+= fx;
x = fx;}
else if (Input.GetButtonDown("Horizontal") && Input.GetAxisRaw("Horizontal") < 0 && Physics.CheckSphere(new Vector2((x-1), y), 0)){
print("left");
fx -= 1;
transform.position = new Vector3(fx, y, -2);
c.transform.position = new Vector3(fx, y, cz);
Playerpos[0] = fx;
print(Playerpos[1]);
x = fx;}
else if (Input.GetButtonDown("Vertical") && Input.GetAxisRaw("Vertical") > 0 && Physics.CheckSphere(new Vector2(x, (y+1)), 0)){
print("up");
fy += 1;
transform.position = new Vector3(x, fy, -2);
c.transform.position = new Vector3(x, fy, cz);
Playerpos.Insert(1, fy);
print(Playerpos);
y = fy;}
else if (Input.GetButtonDown("Vertical") && Input.GetAxisRaw("Vertical") < 0 && Physics.CheckSphere(new Vector2(x, (y-1)), 0)){
print("down");
fy -= 1;
transform.position = new Vector3(x, fy, -2);
c.transform.position = new Vector3(x, fy, cz);
Playerpos.Insert(1, fy);
y = fy;
print(Playerpos);
}
playerpos = new Vector2(x, y);
}
}
This is my first time using Unity Answers, so apologies if I am being dumb, and Thank you for the future help!
It clearly states that your PlayerPos list is empty and you have not initiaized the list as well. 1) Initialize the list with PlayerPos = new List(); 2) Check before accessing PlayerPos[0] that your List's Count > 0
Thank you so much! While Playerpos = new List(2) didn't work, You put me in the right direction!
Your answer

Follow this Question
Related Questions
A node in a childnode? 1 Answer
HOW TO ADD AND REMOVE VARIABLES ALREADY DECLARED IN A LIST 1 Answer
How to find the index of the min value in a list 1 Answer
floats and lists 1 Answer