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

ThirteeNov Walk Patrol C# script for creating any patrolling game object in Unity

Posted on September 13, 2022October 30, 2022 by Habibie

Hi guys… I’m sharing this C# script to make any game object moving and patrolling along given way points that are simple cubes with trigger and tag on them and bla bla bla… here is the script:

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

public class WalkPatrol : MonoBehaviour
{

    public float MovementSpeed = 1f;
    public float TurningSpeed = 3f;
    public Transform WayPointsParent;
    public string WpTag = "WalkWp";
    public bool isLoop = false;
    



    bool IsMoving;
    List<GameObject> Wps = new List<GameObject>();
    int nextWp;
    bool WpReached;

    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine(PatrolNow());
        IsMoving = false;
        WpReached = false;
        foreach (Transform wp in WayPointsParent.transform) {
            //Debug.Log("Name of wp: " + wp.transform.gameObject.name);
            Wps.Add(wp.transform.gameObject);
        }
    }

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

    // Update is called once per frame
    void FixedUpdate()
    {
        if (IsMoving)
        {
            Vector3 lookPos = Wps[nextWp].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;
        }
    }

    IEnumerator PatrolNow()
    {
        yield return new WaitForSeconds(0.1f);
        nextWp = FindClosestPoint();
        IsMoving = true;
    }

    //Function for finding closest waypoint
    public int FindClosestPoint()
    {
        int closest = 0;
        float distance = Mathf.Infinity;
        Vector3 position = transform.position;
        int goidx = 0;
        foreach (Transform go in WayPointsParent.transform)
        {
            Vector3 diff = go.gameObject.transform.position - position;
            float curDistance = diff.sqrMagnitude;
            
            if (curDistance < distance)
            {
                closest = goidx;
                distance = curDistance;
            }
            goidx++;
        }
        Debug.Log("Closest point is: " + closest);
        return closest;
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.tag == WpTag && !WpReached)
        {

            WpReached = true;
            if (nextWp == Wps.Count - 1)
            {
                if (isLoop)
                {
                    nextWp = 0;
                }
                else {
                    IsMoving = false;
                }
                
            }
            else
            {
                nextWp++;
            }
        }
    }

    private void OnTriggerExit(Collider other)
    {

        if (other.tag == WpTag && WpReached)
        {
            WpReached = false;
        }

    }
}

You can watch the video for better understanding:

Post Views: 301
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

  • 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
  • Advanced Blinking Marker Script to show objects position in your game canvas
  • Ciihuy Images Merger – Fast & Easy Online Image Combiner
© 2025 ThirteeNov | Powered by Superbs Personal Blog theme