0

Hello I'am trying to make a system that instantiate and object, and the moves it to a set of waypoints. When i use intantiate in the Start() function it travels like intended through the waypoints, but when i add the instantiate line to my update() function it only travels a little while and then stops, the same goes for the rest of the instantiated objects. It has something to do with timer i guess, but i have tried a few approaches, but they all lead to the same thing. Hope someone can help.

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

public class waypointTest : MonoBehaviour
{
[SerializeField] private Transform[] waypoints;

public GameObject waypointInvader;
GameObject go;        
private int nextUpdate = 1;
public float speed = 5f;
private int waypointIndex;




void Start()
{               
    
}
void Update()
{
    if (Time.time >= nextUpdate)
    {
        nextUpdate = Mathf.FloorToInt(Time.time) + 1;
        go = Instantiate(waypointInvader, transform.position, transform.rotation) as GameObject;            
    }        

    
    if (go.transform.position != waypoints[waypointIndex].transform.position)
    {
        Vector3 newPos = Vector3.MoveTowards(go.transform.position, waypoints[waypointIndex].transform.position, speed * Time.deltaTime);
        go.transform.position = newPos;
        if (newPos == waypoints[waypointIndex].transform.position)
        {
            waypointIndex += 1;
        }
        if (waypointIndex == waypoints.Length)
        {
            waypointIndex = 0;
        }
    }
    
}
}

1 Answers1

1

The problem is that you are loosing the reference to the object you want to move.

If instantiate is inside Start():

  1. go is set to be the instantiated object
  2. go is moved to every waypoint
  3. go is moved to the very first waypoint
  4. go is moving through the waypoints again

If instantiate is inside Update():

  1. go is set to be the first instantiated object
  2. go is moved to a few waypoints until Time.time >= nextUpdate returns true
  3. go is set to be the second instantiated object and will loose its reference to the first go
  4. The first go stops moving
  5. The second go starts moving
  6. Repeat

One way to solve this problem is to give the moving object go its own movement script. That way you just have to instantiate go and it will handle its movement by itself. If go does not know where the waypoints are you can give it to it after instantiating (For example waypointInvader is a prefab). E.g.:

if (Time.time >= nextUpdate)
{
    nextUpdate = Mathf.FloorToInt(Time.time) + 1;
    go = Instantiate(waypointInvader, transform.position, transform.rotation) as GameObject;
    go.GetComponent<GoMovement>().ListOfWaypoints = waypoints;
}
Daniel M
  • 746
  • 5
  • 13