- Home /
Vector3 arrays in C#
Hi everyone, thanks for checking this out. I am totally mystified... trying to build an array which keeps the Vector3 position of a game object over time so it can be referenced when a triggering event occurs.
Here's the relevant code:
using UnityEngine;
using System.Collections;
public class ThrowTrajectory : MonoBehaviour {
public int arraySpaces = 20;
public Transform rightHand;
private Vector3[] rhPos;
void Start () { //THIS WORKS PERFECTLY
Vector3[] rhPos = new Vector3[arraySpaces];
Vector3 v = new Vector3(0,0,0);
//Fill the array with initial vectors
for (int i = 0; i < arraySpaces; i++){
rhPos[i] = v;
Debug.Log ("rh " + i + " : " + rhPos[i]);
}
}
void Update () {
Vector3 v = rightHand.position; //This works
Debug.Log (v); //This works
for (int i = 0; i < arraySpaces; i++){
rhPos[i] = v; //THIS DOESN'T WORK - null reference exception - WHY? It's the identical syntax to the Start method?????
Debug.Log ("rh " + i + " : " + rhPos[i]);
}
}
}
Any ideas??
Comment
Best Answer
Answer by robertbu · Oct 14, 2014 at 04:17 PM
Your problem is on line 15:
Vector3[] rhPos = new Vector3[arraySpaces];
You are declaring a local variable with the same name 'rhPos' as the class instance variable. This variable hides the class variable. Change line 15 to:
rhPos = new Vector3[arraySpaces];