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.
First, you have to open the Unity project. Create the cube.
Rescale the size for the cube.
Rename the cube as floor.
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.
Rename the cube as enemy.
Drag and drop the blue and green material. The color of the cube will be changed into blue and green.
Create a C# Script
Right-click on Assets. Select Create >> C# script.
Rename the script as Enemy.
Double click on the enemy script. The MonoDevelop-Unity editor will open up.
Write the code as shown below:
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class Enemy: MonoBehaviour {
- public Transform[] target;
- public float speed;
- private int current;
-
- void Start() {}
-
- void Update() {
- if (transform.position != target[current].position) {
- Vector3 pos = Vector3.MoveTowards(transform.position, target[current].position, speed * Time.deltaTime);
- GetComponent < Rigidbody > ().MovePosition(pos);
- } else current = (current + 1) % target.Length;
- }
- }
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.
Rename the create empty (Gameobject) as a target.
Drag and drop the enemy script onto the Enemy.
Add the rigidbody onto the enemy
Call the target. The enemy will be the object to follow a path.
Save the program. Go to Objects follow a path and click on the Play button. The enemy will be moving to the target.
Summary
I hope you understood how to make an object follow a path using C# scripts in Unity.