P
P
polyakovyevgeniy2017-04-02 21:20:36
Unity
polyakovyevgeniy, 2017-04-02 21:20:36

How to play animation from code in Unity3D?

Created a cube with a nested light source. Created an animation for the cube and two clips, made an animation of the light. Attached two clips to the Animation object. In code I write:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MainScript : MonoBehaviour
{

    private Animation _animation;

    void Start()
    {

        _animation = GetComponent<Animation>();
    }

    // Update is called once per frame
  void Update () {
      if (Input.GetMouseButtonDown(0))
      {
          Debug.Log(_animation.GetClipCount());
          _animation.Play("On");
      }
      if (Input.GetMouseButtonDown(1))
      {
            _animation.Play("Off");
        }
  }
}

Does not work, writes an error: The animation state On could not be played because it couldn't be found!
Please attach an animation clip with the name 'On' or call this function only for existing animations.
UnityEngine.Animation:Play(String)
MainScript:Update() (at Assets/MainScript.cs:21)
Although _animation.GetClipCount() returns 2.
What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Gaydak, 2017-04-02
@polyakovyevgeniy

https://docs.unity3d.com/ScriptReference/Animation...
use the non-deprecated method to get started. (although you may have the fourth version of the unit, of course)
secondly, check the name of the animation "On"
exactly and if it is definitely in the list and the name is correct.
the point is how you created it - more precisely, in the crookedness of the unit)
select the animation and in the debug mode of the inspector check that Legacy is ticked in it
https://docs.unity3d.com/Manual/InspectorOptions.html - this is about how to enable debug the display of the inspector
will specify the animation itself, and not the Anomation component

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question