- Home /
Question by
andry-tino · Jun 01, 2020 at 08:40 AM ·
animationscript.animator controlleranimationclip
Animation created via script does not play
I have created an empty GameObject
and assigned it a script:
[MenuItem("Custom workflow/Initialize")]
static void Initialize()
{
// Place a text mesh on the scene
var obj = new GameObject("Sample");
obj.transform.position = new Vector3(0, 0, 0);
var text = obj.AddComponent<TextMesh>();
text.text = "Hello world";
AnimationClip clip1 = CreateAnimationClip();
AnimatorController sm = CreateSimpleAnimatorController(clip1);
var animator = obj.AddComponent<Animator>();
animator.runtimeAnimatorController = sm;
animator.applyRootMotion = true;
}
In the same file, I have created method CreateAnimationClip
:
private static AnimationClip CreateAnimationClip()
{
var translateX = AnimationCurve.Linear(0.0f, 0.0f, 2.0f, 25.0f);
var animationClip = new AnimationClip();
animationClip.SetCurve("", typeof(Transform), "position.x", translateX);
AssetDatabase.CreateAsset(animationClip, "Assets/procanim.anim");
return animationClip;
}
And I have also defined CreateSimpleAnimatorController
:
private static AnimatorController CreateSimpleAnimatorController(
Motion motion1 = null, Motion motion2 = null)
{
// Creates the controller
var controller = AnimatorController.CreateAnimatorControllerAtPath(
"Assets/SimpleStateMachineTransitions.controller");
// Add parameters
controller.AddParameter("GoToB", AnimatorControllerParameterType.Bool);
controller.AddParameter("GoToA", AnimatorControllerParameterType.Bool);
// Add StateMachines
var rootStateMachine = controller.layers[0].stateMachine;
// Add States
var stateA1 = rootStateMachine.AddState("stateA1");
stateA1.motion = motion1;
var stateB1 = rootStateMachine.AddState("stateB1");
stateB1.motion = motion2;
// Add Transitions
var transitionAB = stateA1.AddTransition(stateB1);
transitionAB.AddCondition(AnimatorConditionMode.If, 0, "GoToB");
transitionAB.duration = 0;
var transitionBA = stateB1.AddTransition(stateA1);
transitionBA.AddCondition(AnimatorConditionMode.If, 0, "GoToA");
transitionBA.duration = 0;
return controller;
}
The problem
As I invoke the menu item, I get all assets in place. When I hit play, nothing happens. I can see state stateA1
is on, but the animation does not run. If I click on the text object in the scene, this is what I see in the animation window:
I think the problem might be here:
animationClip.SetCurve("", typeof(Transform), "position.x", translateX);
Because when I remove it manually and add it manually using the interface and hit play again, it works.
screenshot-2020-06-01-at-095333.png
(118.9 kB)
Comment
Answer by andry-tino · Jun 06, 2020 at 09:55 AM
The issue is that I was using the wrong property name, this fixes it:
animationClip.SetCurve("", typeof(Transform), "localPosition.x", translateX);