Introduction
In this article, we will discuss Lerp rotation of a 3D object using C# scripts in Unity.
Prerequisites
Unity environment version 2017.4.39f1
Create the Project:
First, you have to open the Unity project. Create the plane.
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
Drag and drop the black and red material. The color of the cube will be changed into black and red.
Create a C# Script
Right-click on Assets. Select Create >> C# script.
Rename the script as Lerprotation.
Double click on the Lerprotation script. The MonoDevelop-Unity editor will open up.
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class Lerprotation: MonoBehaviour {
- [SerializeField][Range(0 f, 5 f)] float lerptime;
- [SerializeField] Vector3[] myAngels;
- int angleIndex;
- int len;
- float t = 0 f;
-
- void Start() {
- len = myAngels.Length;
- }
-
- void Update() {
- transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(myAngels[angleIndex]), lerptime * Time.deltaTime);
- t = Mathf.Lerp(t, 1 f, lerptime * Time.deltaTime);
- if (t > .9 f) {
- t = 0 f;
- angleIndex = Random.Range(0, len - 1);
- }
- }
- }
Save the Program
Drag and drop the Lerprotation script onto the Cube.
Set the Lerptime the Scene View.
Set the Angels LerpRotation the Scene View.
Click on the Play button to see Lerp rotation of a 3D object in run time:
Click on the Play button.The object will show Lerp rotation of a 3D object in the Scene view.
Summary
I hope you understood how to perform Lerp rotation of a 3D object using C# scripts in Unity.