- Home /
Error when trying to set variable with array
I'm trying to make a tower defense game. I've never used array's before, so i figured now would be a good time. I'm making a enemy, were the goal is to move from waypoint to waypoint. I'm using smoothdamp, so i need target positions, but when i try to set the target positions using the array, i get an error saying "NullReferenceException: Object reference not set to an instance of an object Boo.Lang.Runtime.RuntimeServices.CheckNumericPromotion (IConvertible convertible) Boo.Lang.Runtime.RuntimeServices.CheckNumericPromotion (System.Object value) Boo.Lang.Runtime.RuntimeServices.UnboxSingle (System.Object value) enemy.Update () (at Assets/scripts/enemy.js:16)" If anybody can help me figure out why this is happening, i'd very much appreciate it. Here is my script...
var waypoint : Transform[];
var currentWaypoint : int;
//moving smoothdamp vars
var targetX : float;
var targetZ : float;
var time : float;
private var velocity : float;
function Update()
{
targetX = waypoint[currentWaypoint].x;
targetZ = waypoint[currentWaypoint].z;
transform.position.x = Mathf.SmoothDamp(transform.position.x, targetX, velocity, time * Time.deltaTime);
transform.position.z = Mathf.SmoothDamp(transform.position.z, targetZ, velocity, time * Time.deltaTime);
}
function Awake()
{
waypoint = Camera.main.GetComponent(waypointsInit).waypoints;
currentWaypoint = 0;
targetX = transform.position.x;
targetZ = transform.position.z;
}
function OnTriggerEnter(hit : Collider)
{
if(hit.gameObject.tag == "waypoint")
{
currentWaypoint += 1;
print(currentWaypoint);
}
}
Answer by bompi88 · Nov 30, 2013 at 03:12 PM
Your waypoint variable contains an array of Transforms, so it's waypoint[currentWaypoint].position.x not waypoint[currentWaypoint].x. So
targetX = waypoint[currentWaypoint].position.x;
targetZ = waypoint[currentWaypoint].position.z;
And make sure you have initialized the array in the script that is attached to the camera with some transforms in the inspector, before you run the script.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
IndexOutOfRangeException: Array index is out of range 0 Answers
Getting ArgumentOutOfRangeException on array c# 1 Answer
Array index is out of range? 2 Answers