Home > Mobile >  How do I use or force unity editor code in the runtime/build?
How do I use or force unity editor code in the runtime/build?

Time:03-08

I want to use editor components in the build. I've searched everywhere and they say use this:

#if UNITY_EDITOR
    //code here
#endif

Which I think is How not to use the editor in runtime. I want the exact opposite. Is there a way to do it? or Could there be an alternative to this code to be used in runtime?

  var controller = UnityEditor.Animations.AnimatorController.CreateAnimatorControllerAtPath("Assets/Resources/Animations/AnimationControllers/SAMPLE_CONTROLLER.controller");
  controller.AddParameter("OpenCloseValue", AnimatorControllerParameterType.Float);
  var rootStateMachine = controller.layers[0].stateMachine;
  var myStateMachine = rootStateMachine.AddStateMachine("s_machine");
  var myState1 = myStateMachine.AddState("state_1");
  controller.SetStateEffectiveMotion(myState1, myAnimationClip);

Thank You.

CodePudding user response:

RuntimeAnimatorController, the class that represents animator controllers during runtime in Unity, doesn't allow you to alter controller parameters, layers, or state machines.

The class that you're trying to use there, AnimatorController, is part of the UnityEditor namespace, and therefore cannot be used at runtime, hence the other posters mentioning that you need to use the preprocessing command #if UNITY_EDITOR to avoid compile errors.

Seems like what you're trying to do here is unsupported.

CodePudding user response:

Which editor components to you want to use at runtime? I think the answer is that you can't really use components that are exclusive to the editor in a build

CodePudding user response:

As mentioned before what you are asking for is simply not possible.

The entire UnityEditor namespace is stripped of during the build process as it contains functionality that is only available within the Unity Editor itself.


It looks to me though what you are trying to achieve is to assign a different AnimationClip to a known / existing AnimatorController.

This is provided by AnimatorOverrideController which maintains the given animator states but allows to assign a different AnimationClip to them.

Simplified example from the API

// As usual get the Animator
var animator = GetComponent<Animator>();
// Create an override controller based on the original Animator controller
var animatorOverrideController = new AnimatorOverrideController(animator.runtimeAnimatorController);
// And use this as the new controller
animator.runtimeAnimatorController = animatorOverrideController;
// Assign a new clip to the given state name
// See https://docs.unity3d.com/ScriptReference/AnimatorOverrideController.Index_operator.html
animatorOverrideController[STATE_NAME] = someAnimationClip;

So you would simply pre-configure an AnimatorController completely in the Editor and then on runtime only override your one AnimationClip in it.

  • Related