Object Follow A Path Using C# Scripts In Unity

Introduction

 
In this article, we discuss how to make an object follow a path using C# scripts in Unity.
 
Prerequisites
 
Unity Environment version 2017.4.39f1
 
Steps 
 
Create the project in Unity.
 
Object Follow A Path Using C# Scripts In Unity
 
First, you have to open the Unity project. Create the cube.
 
Object Follow A Path Using C# Scripts In Unity
 
Rescale the size for the cube.
 
Object Follow A Path Using C# Scripts In Unity
 
Rename the cube as floor.
 
Object Follow A Path Using C# Scripts In Unity 
 
Click on the "GameObject" menu in the menu bar. Select 3D objects and pick the "cube" option. The cube will be added to the scene View.
 
Object Follow A Path Using C# Scripts In Unity
 
Rename the cube as enemy.
 
Object Follow A Path Using C# Scripts In Unity 
 
Drag and drop the blue and green material. The color of the cube will be changed into blue and green.
 
Object Follow A Path Using C# Scripts In Unity
 
Create a C# Script
 
Right-click on Assets. Select Create >> C# script.
 
Object Follow A Path Using C# Scripts In Unity
 
Rename the script as Enemy.
 
Object Follow A Path Using C# Scripts In Unity
 
Double click on the enemy script. The MonoDevelop-Unity editor will open up.
 
Write the code as shown below:
  1. using System.Collections;  
  2. using System.Collections.Generic;  
  3. using UnityEngine;  
  4. public class Enemy: MonoBehaviour {  
  5.     public Transform[] target;  
  6.     public float speed;  
  7.     private int current;  
  8.     // Use this for initialization    
  9.     void Start() {}  
  10.     // Update is called once per frame    
  11.     void Update() {  
  12.         if (transform.position != target[current].position) {  
  13.             Vector3 pos = Vector3.MoveTowards(transform.position, target[current].position, speed * Time.deltaTime);  
  14.             GetComponent < Rigidbody > ().MovePosition(pos);  
  15.         } else current = (current + 1) % target.Length;  
  16.     }  
  17. }   
Save the program.
 
Click on the "GameObject" menu in the menu bar. Select 3D objects and pick the "create empty" option. The empty (Gameobject) will be added to the scene View.
 
Object Follow A Path Using C# Scripts In Unity
 
Rename the create empty (Gameobject) as a target.
 
Object Follow A Path Using C# Scripts In Unity 
 
Drag and drop the enemy script onto the Enemy.
 
Object Follow A Path Using C# Scripts In Unity
 
Add the rigidbody onto the enemy
 
Object Follow A Path Using C# Scripts In Unity 
 
Call the target. The enemy will be the object to follow a path.
 
Object Follow A Path Using C# Scripts In Unity
 
Save the program. Go to Objects follow a path and click on the Play button. The enemy will be moving to the target.
 
Object Follow A Path Using C# Scripts In Unity
 

Summary

 
I hope you understood how to make an object follow a path using C# scripts in Unity.


Similar Articles