So I have an enemy which is going to be patrolling around the area. I decided to make a gameobject array to find the objects with the tag “Waypoints” and then store the objects position in another array from a for loop and then assign those values to a target variable. I’m new to c# coding so I thought it made sense.
Anyway I logged the arrays and they weren’t empty(it outputs their xyz values). I have the enemy set up (for testing) to move to the position when I press the letter M (It works when I use my position) using navmesh. When I change my target variable to “target = position[0]” and then test it, it outputs “Indexoutofrangeexception: array index is out of range”
So the above didn’t work so I tried another method by using the waypoints array instead → target = waypoints[0].transform.position
It gave me the same error.
I have the variable set up as public because if they aren’t I get an error and then I apply the values in the start function because if I do it outside of it I get an error saying that the array waypoints doesn’t exist or something.
So I tried every possible way (even applying the values manually → waypoint[0] = gameobject.find(“name”) etc.) so any help is appreciated so here is the code, I don’t understand if the array themselves aren’t empty. Thanks.`using UnityEngine;
using System.Collections;
[RequireComponent(typeof(NavMeshAgent))]
public class MannequinAI : MonoBehaviour {
Animator anim;
NavMeshAgent nav;
Vector3 target;
public GameObject[] waypoints; //array for the gameobjects
public Vector3[] positions; //array to store their position
// Use this for initialization
void Start () {
anim = GetComponent<Animator> ();
nav = GetComponent<NavMeshAgent> ();
anim.SetFloat ("Speed", 1);
GameObject[] waypoints = GameObject.FindGameObjectsWithTag("Waypoints");
Vector3[] positions = new Vector3[waypoints.Length];
if (positions.Length != 0) {
Debug.Log (waypoints[0].transform.position);
Debug.Log (waypoints[1].transform.position);
}
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.M)) {
navigation ();//goes to this function
}
if (!nav.pathPending)
{
if (nav.remainingDistance <= nav.stoppingDistance)
{
if (!nav.hasPath || nav.velocity.sqrMagnitude == 0f) //this code is just to check remaining distance from target to change animation.
{
anim.SetFloat ("Speed", 0);
}
}
}
for (int i = 0; i < waypoints.Length; i++)
{
positions _= waypoints*.transform.position; //store the positions with the index i*_
* }*
* }*
* void navigation() {*
* target = positions[0]; //sets the target, this is the error line. I also tried it in update.*
* nav.SetDestination(target); //this part works when target is set to my location.*
* anim.SetFloat (“Speed”, 1);*
* }*
}
`