Skip to content

ThirteeNov

My personal blog about coding and internet

Menu
  • About me
  • About Zofia Kreasi
  • Cart
  • Checkout
  • Making an airplane game from scratch in Unity
  • My account
  • Privacy Policy
  • Privacy Policy – zkLeaderboard
  • Sample Page
  • Shop
  • Tutorials on Learning JavaScript
  • ZKAccounts – Privacy Policy
Menu

Enemy Patrol Starting from the Nearest and Closest Waypoint in Unity3D

Posted on October 9, 2019August 4, 2020 by Habibie

I’ve created a simple C# script for Unity game that allows you to create a patrolling enemy around multiple waypoints (check points). It will start patrolling from the nearest / closest waypoint available around the patrolling object, then it continues to check the next waypoint incrementally.

Watch the tutorial video on my YouTube channel and please subscribe to support me 😀

Here is the script (Create a script with name EnemyPatrol and paste this code into it):

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

public class EnemyPatrol : MonoBehaviour
{
    public float MovementSpeed = 3f;
    public float TurningSpeed = 3f;

    Vector3 dist;
    bool WpReached;
    GameObject StartingPoint;
    string TargetWpToGo;
    int CurrentWpNumber;
    Rigidbody rb;

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
        StartingPoint = FindClosestWaypoint();
        TargetWpToGo = StartingPoint.gameObject.name;
        CurrentWpNumber = int.Parse(TargetWpToGo.Split(char.Parse("-"))[1]);
        Debug.Log("Current Wp Target : " + CurrentWpNumber);
    }

    // Update is called once per frame
    void LateUpdate()
    {

        GameObject WpToGo = GameObject.Find("wp-" + CurrentWpNumber);
        Vector3 lookPos = WpToGo.transform.position - transform.position;
        lookPos.y = 0;
        Quaternion rotation = Quaternion.LookRotation(lookPos);
        transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * TurningSpeed);
        transform.position += transform.forward * Time.deltaTime * MovementSpeed;
    }

    //Function for finding closest waypoint
    public GameObject FindClosestWaypoint()
    {
        GameObject[] gos;
        gos = GameObject.FindGameObjectsWithTag("Waypoint");
        GameObject closest = null;
        float distance = Mathf.Infinity;
        Vector3 position = transform.position;
        foreach (GameObject go in gos)
        {
            Vector3 diff = go.transform.position - position;
            float curDistance = diff.sqrMagnitude;
            if (curDistance < distance)
            {
                closest = go;
                distance = curDistance;
            }
        }
        return closest;
    }

    private void OnTriggerEnter(Collider other)
    {
        if(other.tag == "Waypoint" && !WpReached)
        {
            WpReached = true;
            if (GameObject.Find("wp-" + (CurrentWpNumber + 1)) != null)
                CurrentWpNumber += 1;
            else
                CurrentWpNumber = 0;
        }
        Debug.Log("Current Wp Target : " + CurrentWpNumber);
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.tag == "Waypoint" && WpReached)
        {
            WpReached = false;
        }
    }
}
Post Views: 448
ciihuy2020

Welcome!

  • My YouTube Channel
  • My GitHub Page
  • About me

Categories

  • 3DVista
  • Android
  • Apache
  • C#
  • Cordova
  • Electron & Node JS
  • HTML5, CSS & JavaScript
  • iOS
  • Let's Make Unity Games
  • Misc
  • Photoshop
  • PHP
  • Python
  • Uncategorized
  • Unity
  • WordPress

Recent Posts

  • Hover Reveal script for Unity to show and hide object on mouse hover
  • How to Prevent UI Clicks in Unity from “Bleeding Through” to 3D Objects Behind Them
  • Make objects like wires and cables easily in Unity using Ciihuy Curved Mesh
  • [SOLVED] Can’t Add Custom Domain to Blogger After Losing CNAME Verification
  • iOS App Icon Generator by CiihuyCom
© 2026 ThirteeNov | Powered by Superbs Personal Blog theme