- Home /
NullRefenceException Using Arrays
Basically every line that contains a array throws me a nullrefenceexception even though the array is defined the inspector
using UnityEngine;
using System.Collections;
public class PlayerMovement : Player {
//Fields
public float[] OriginalXYZtranslateSpeed;
private float[] _currentXYZtranslateSpeed;
public float[] MaxXYZtranslateSpeed;
public float[] AccelerationXYZtranslateSpeed;
public float[] DeaccelerationXYZtranslateSpeed;
public float JumpHeight;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
transform.Translate(_currentXYZtranslateSpeed[0] * Time.deltaTime, _currentXYZtranslateSpeed[1] * Time.deltaTime, _currentXYZtranslateSpeed[2] * Time.deltaTime);
KeyboardMovement();
}
void KeyboardMovement()
{
//Sideways movement
if (Input.GetKey(KeyCode.A) && (_currentXYZtranslateSpeed[0] >= -MaxXYZtranslateSpeed[0]))
{
_currentXYZtranslateSpeed[0] -= AccelerationXYZtranslateSpeed[0];
}
else if (Input.GetKey(KeyCode.D) && (_currentXYZtranslateSpeed[0] <= MaxXYZtranslateSpeed[0]))
{
_currentXYZtranslateSpeed[0] += AccelerationXYZtranslateSpeed[0];
}
else if (_currentXYZtranslateSpeed[0] > OriginalXYZtranslateSpeed[0])
{
_currentXYZtranslateSpeed[0] -= DeaccelerationXYZtranslateSpeed[0];
}
else if (_currentXYZtranslateSpeed[0] < OriginalXYZtranslateSpeed[0])
{
_currentXYZtranslateSpeed[0] += DeaccelerationXYZtranslateSpeed[0];
}
//Forward and backwards movement
if (Input.GetKey(KeyCode.W) && (_currentXYZtranslateSpeed[2] <= MaxXYZtranslateSpeed[2]))
{
_currentXYZtranslateSpeed[2] += AccelerationXYZtranslateSpeed[2];
}
else if (Input.GetKey(KeyCode.S) && (_currentXYZtranslateSpeed[2] >= -MaxXYZtranslateSpeed[2]))
{
_currentXYZtranslateSpeed[2] -= AccelerationXYZtranslateSpeed[2];
}
else if (_currentXYZtranslateSpeed[2] > OriginalXYZtranslateSpeed[2])
{
_currentXYZtranslateSpeed[2] -= DeaccelerationXYZtranslateSpeed[2];
}
else if (_currentXYZtranslateSpeed[2] < OriginalXYZtranslateSpeed[2])
{
_currentXYZtranslateSpeed[2] += DeaccelerationXYZtranslateSpeed[2];
}
//Jump
if (Input.GetKey(KeyCode.Space) && IsGrounded())
{
rigidbody.velocity = new Vector3(0, JumpHeight, 0);
}
}
}
Comment
Best Answer
Answer by Adam-Buckner · Apr 22, 2013 at 03:09 PM
Just a note re: both answers for clarity.
You only need to declare the PRIVATE array. The others are, as the OP suggested, initialized in the inspector. The one marked "private" is not, and needs to be initialized in the script somehow.
I would suggest using the generic List as it's just as fast and more versatile.
Answer by Loius · Apr 22, 2013 at 02:52 PM
You haven't initialized_currentXYZ anywhere: you need to:
_currentXYZ = new float[3]
in Start.