Creating dynamically unity controller and adding to it states with motions

Today i will show you how to add controller Dynamically Using C# Script

Create new  unity project
then add to it C# script  Assets > Create > C# Script
Add Script

Name it as you like for me “Controller Script”

add your Script to any game object you have Double click on it to open . It will be opened in MonoDevelop

place the following code on “void start” function as we need it be be called once

var controller = UnityEditor.Animations.AnimatorController.CreateAnimatorControllerAtPath ("Assets/Mycontroller.controller");

This will Create to use a blank controller  in Assets folder

Now for adding AnimatorState with a motion

Create New folder Name it Resources inside assets folder. add to it all you .animation file you want to add to your controller,so that you could load it in  run time.

In your Script create two motion object (For Example) to store the loaded animations in it. As the Following Code:

Motion Motion1 = Resources.Load ("Motion1")as Motion;
Motion Motion2 = Resources.Load ("Motion2")as Motion;

Now you could add your motion to your to your controller.  As the Following Code:

AnimatorState it is just a reference to the motions states

;(AnimatorState State1 = controller.AddMotion(Motion1 
;(AnimatorState State2 = controller.AddMotion(Motion2 

Now run your unity project you should find some thing like that

After Adding state

?Now you have added States but why Motion1 has orange color

 Motion1 is the main state for the controller so you may Have to add one to be the main state unless

.you want Motion1 to be the main one 

 Now for adding transition between states  

: Using the AnimatorStates references transition will be made. As the following code 

;(AnimatorStateTransition Transition = State1.AddTransition (State2

.Now run you uinty project you will find transition from state1 to state2

.You can Download the code From here Project Files


2 thoughts on “Creating dynamically unity controller and adding to it states with motions

اترك رد

إملأ الحقول أدناه بالمعلومات المناسبة أو إضغط على إحدى الأيقونات لتسجيل الدخول: Logo

أنت تعلق بإستخدام حساب تسجيل خروج   / تغيير )

صورة تويتر

أنت تعلق بإستخدام حساب Twitter. تسجيل خروج   / تغيير )

Facebook photo

أنت تعلق بإستخدام حساب Facebook. تسجيل خروج   / تغيير )

Google+ photo

أنت تعلق بإستخدام حساب Google+. تسجيل خروج   / تغيير )

Connecting to %s