- Home /
I figured out the issue and now it works 100%
create waypoints with an array without using "Tags"
Im creating a waypoint system for game objects that react on a trigger. The script goes into the parent and the targets go into a child folder. I wrote a script that lets you manualy set the array size and then just put in the targets in the inspector but i would like this to happen automatically. So if there is an object with lots of targets they dont have to be put in one by one. The Gameobject will move to the new targets if i do it manually.
Im getting Array index is out of range error.
Any idea why it will not compile?
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class TESTArrayTarget : MonoBehaviour
{
public GameObject objectToMove;
public Transform startPosition;
public Transform[] targets;
private Vector3 currentTarget;
private int i = 0;
public float moveSpeed;
//Adding
public GameObject targetFolder;
public int arraySize = 1;
void Start()
{
targetFolder.GetComponentsInChildren<Transform>();
for (int i = 0; i <= targetFolder.transform.childCount ; i++)
{
arraySize++; // just for Debugging
targets[1] = targetFolder.transform.GetChild(1);
}
currentTarget = startPosition.position;
}
void Update()
{
ObjectMoving();
}
void ObjectMoving()
{
objectToMove.transform.position = Vector3.MoveTowards
(objectToMove.transform.position, currentTarget, moveSpeed * 10 * Time.deltaTime);
}
void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
if (i <= targets.Length)
{
if (i >= targets.Length)
{
i = 0;
}
currentTarget = targets[i].position;
i++;
}
}
}
}
I have done a little testing and it seems if i put the folder that houses the targets into element 0 and tell the array that it is the correct size it will auto populate the array and work.
So the only thing i need it to do now is to automatically build the array size Any ideas.