C# script to make GameObject go between multiple points.

 

Updated Script:

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

// © 2017 TheFlyingKeyboard and released under MIT License
// theflyingkeyboard.net

//Moves object between points

public class MoveBetweenPoints : MonoBehaviour {
    [SerializeField] private Transform objectToMove;
    [SerializeField] private bool moveThisObject = false;
    [SerializeField] private float moveSpeed;
    [SerializeField] private List<Transform> points;

    private int counter;
    private bool goBack;

    // Use this for initialization
    void Start()
    {
        counter = 0;
        goBack = false;

        if (moveThisObject)
        {
            objectToMove = transform;
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (counter == (points.Count - 1))
        {
            goBack = true;
        }
        else if (counter == 0)
        {
            goBack = false;
        }


        if (objectToMove.position == points[counter].position)
        {
            if (!goBack)
            {
                counter++;
            }
            else
            {
                counter--;
            }
        }

        objectToMove.position = Vector3.MoveTowards(objectToMove.position, points[counter].position, moveSpeed * Time.deltaTime);
    }
}

Old Script:

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

// © 2017 TheFlyingKeyboard and released under MIT License
// theflyingkeyboard.net

public class MoveBetweenPoints : MonoBehaviour {
    public float moveSpeed;
    
    public List<Transform> points;

    private int counter;
    private bool goBack;
      
    // Use this for initialization
    void Start()
    {
        counter = 0;
        goBack = false;
    }

    // Update is called once per frame
    void Update()
    {
        if (counter == (points.Count - 1))
        {
            goBack = true;
        } else if (counter == 0)
        {
            goBack = false;
        }


        if (transform.position == points[counter].position)
        {
            if (!goBack)
            {
                counter++;
            }
            else
            {
                counter--;
            }      
        }

        transform.position = Vector3.MoveTowards(transform.position, points[counter].position, moveSpeed * Time.deltaTime);
    }
}

 

Unity C# Move GameObject Between Points
Tagged on:             

Leave a Reply

Your email address will not be published. Required fields are marked *

This website stores some user agent data. These data are used to provide a more personalized experience and to track your whereabouts around our website in compliance with the European General Data Protection Regulation. If you decide to opt-out of any future tracking, a cookie will be set up in your browser to remember this choice for one year. I Agree, Deny
504