Lerp Rotation Of A 3D Object Using C# Scripts In Unity

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.
  1. using System.Collections;  
  2. using System.Collections.Generic;  
  3. using UnityEngine;  
  4. public class Lerprotation: MonoBehaviour {  
  5.     [SerializeField][Range(0 f, 5 f)] float lerptime;  
  6.     [SerializeField] Vector3[] myAngels;  
  7.     int angleIndex;  
  8.     int len;  
  9.     float t = 0 f;  
  10.     // Use this for initialization    
  11.     void Start() {  
  12.         len = myAngels.Length;  
  13.     }  
  14.     // Update is called once per frame    
  15.     void Update() {  
  16.         transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(myAngels[angleIndex]), lerptime * Time.deltaTime);  
  17.         t = Mathf.Lerp(t, 1 f, lerptime * Time.deltaTime);  
  18.         if (t > .9 f) {  
  19.             t = 0 f;  
  20.             angleIndex = Random.Range(0, len - 1);  
  21.         }  
  22.     }  

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.


Similar Articles