Cant find Objects with GameObject.Find()

I am new to this whole programming thing, so it mitght be a simple thing but i dont know what.
I am trying to move Object from a Waypoint-Object to another and from there to the next one and so on. My Problem is, that the script cant find my WayPoint-GameObjects with GameObject.Find(name); It just puts an empty Vector into my array.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AttackBehavior : MonoBehaviour
{
    private Vector2[] targets;
    private int j = 0;

    public void Start()
    {
        GameObject[] wpObj = GameObject.FindGameObjectsWithTag("WayPointTAG");
        Vector2[] goals = new Vector2[wpObj.Length];
        goals[0] = GameObject.Find("WayPoint").transform.position;
        for (int i = 1; i == wpObj.Length; i++)
        {
            goals[i] = GameObject.Find("WayPoint (" + i + ")").transform.position;
        }
        targets = goals;
    }

    void Update()
    {
        if(Vector2.Distance(transform.position, targets[j]) == 0)
        {
            j++;
        }
        else
        {
            transform.position = Vector2.MoveTowards(transform.position, targets[j], 5 * Time.deltaTime);
        }
    }
}

I meant to move the Object this script is attached to.

Remember the first rule of GameObject.Find():

Do not use GameObject.Find();

More information: https://starmanta.gitbooks.io/unitytipsredux/content/first-question.html

All MonoBehaviour instances have a .transform shortcut you can manipulate directly.

1 Like

I tried transform.Find(); but it didnt work either and i dont think the rest of the techniques dont work for me.

Create a WaypointManager which is a singleton and contains an array of your waypoints, and access them through that singleton.