unity 用代码控制动画的播放的进度

Wesley13
• 阅读 943

https://answers.unity.com/questions/1225328/imported-animated-object-and-slider-tutorial.html

using UnityEngine;

public class NewBehaviourScript : MonoBehaviour {
    //Animation 需要将动画调为Legacy,
    //自建的动画可以在Inspector面板下调为Debug模式,勾选上Legacy就可以了
    //public Animation _animation;

    public Animator _animator;

    void Start () {
        //_animation.Play("New Animation1");
       // _animation["New Animation1"].speed = 0;

        _animator.speed = 0;
    }
    float step = 0;
    float timer = 0;

    void Update () {
        //if (Input.GetMouseButton(0))
        //{
        //    timer += Time.deltaTime;
        //    if (timer>0.1f)
        //    {
        //        step += 0.1f;
        //        if (step <= 1)
        //        {
        //            _animation["New Animation1"].normalizedTime = step;
        //            Debug.Log(step);
        //        }
        //        else
        //        {
        //            step = 0;
        //        }
        //        timer = 0;
        //    }
        //}
        if (Input.GetMouseButton(1))
        {
            timer += Time.deltaTime;
            if (timer > 0.1f)
            {
                step += 0.1f;
                if (step <= 1)
                {
                    _animator.Play("New Animation1", 0, step);
                    Debug.Log(step);
                }
                else
                {
                    step = 0;
                }
                timer = 0;
            }
        }
    }
}

How to control animation with slider

Hello, Im a noob to unity.

Ive searched and it seems there have been similar questions to this, but answered with advanced knowledge. I have no idea how to start this.

(attached image) I have a hand pinching a block. i want to use the slider in a way that when I slide the knob to the right, the animation will advance, pinching the block.

I have the animation exported in fbx format and placed in my canvas. I added the slider but don't know where to go from there as far as connecting it, and the correct scripting for it.unity 用代码控制动画的播放的进度 So anything that is along the lines of using the slider to control the imported animation would be great. Please help! Thank you!

screen-shot-2016-08-05-at-14612-pm.png (154.9 kB)

评论 ·  Show 2

3条回复

 ·  添加您的回复

  • 排序:

 

unity 用代码控制动画的播放的进度

1

最佳解答

个解答,截止vfxjex · 2016年08月07日 05:17

Hello I think I answered this concern base on the link @KuR5 shared, but if things are not yet cleared let me try to clarify it.

First of all make sure that the attached component of your model is "Animation" not Animator.

second make sure that the animation of your hand is "Legacy". if you don't know how to make your animation Legacy just right click the inspector "Tab" of your animation clip and check the Legacy checkbox. make sure you switch back to normal after doing this so.

Third in the animation component, there is an Animations attribute. change the size to 1 and drag and drop the animation of your hand.

4th Copy and paste this Script and attached it to your model in the Hierarchy. Don't forget to drag and drop the slider into the slider variable.

  1. using UnityEngine;

  2. using UnityEngine.UI;

  3. using System.Collections;

  4. public class AnimControl : MonoBehaviour {

  5. Animation anim;

  6. //Drag and drop your Slider into this variable.

  7. public Slider slider;

  8. // Use this for initialization

  9. void Start () {

  10. anim = GetComponent<Animation> ();

  11. //Make sure you have attached your animation in the Animations attribute

  12. anim.Play ("myAnimation");

  13. anim ["myAnimation"].speed = 0;

  14. }

  15. // Attached this on Slider's On Value Change

  16. public void AnimateOnSliderValue () {

  17. anim["myAnimation"].normalizedTime = slider.value;

  18. }

  19. }

Hope this works.

评论 ·  隐藏 1 ·  分享

unity 用代码控制动画的播放的进度 mbrako  · 2016年08月09日 21:12 0

Something isn't working but it looks like it almost is.

  1. I bring my 'handAnim' fbx into the scene. The part where you say to right click for Legacy ( I think we are using different Unity versions) but I changed the Animation type to Legacy and did 'Apply', you say put back to normal but I dont see a normal option'. see screen shot below on 'answer' ( I couldnt add on reply)

  2. Confirmed Im using Animation with size 1, used your script and where it says 'myAnimation' replaced with with 'handAnimation', and dropped it on my handAnim component hierarchy, and after bringing my slider into the scene, and also dragged and dropped the slider into the Slider variable

  3. // Attached this on Slider's On Value Change public void AnimateOnSliderValue () { anim["myAnimation"].normalizedTime = slider.value; --For this part, On Value Change under Runtime, I connected the 'handSlider (slider) and selected 'value' (is that right?)

  4. I hit play, notice there are no errors in my console but the slider isn't affecting the animation. Now I do realize my animation starts and ends (23.0-49.0) Will this affect the slider when the slider triggers the animation and do I need to indicate that its starts at frame 23? If so, how?

Thanks A TON!!!

unity 用代码控制动画的播放的进度

2

个解答,截止Rodlaiz · 2017年02月22日 14:56

The solution provided by Vfxjex doesn't work for me because the Animation component has to be marked as Legacy. I try this solution using Animator instead of Animation and it works for me:

  1. using UnityEngine;

  2. using UnityEngine.UI;

  3. public class ControlAnimation : MonoBehaviour

  4. {

  5. private Animator anim;

  6. public Slider slider; //Assign the UI slider of your scene in this slot

  7. // Use this for initialization

  8. void Start()

  9. {

  10. anim = GetComponent<Animator>();

  11. anim.speed = 0;

  12. }

  13. // Update is called once per frame

  14. void Update()

  15. {

  16. anim.Play("TEST_DELETE", -1, slider.normalizedValue);

  17. }

  18. }

评论 ·  隐藏 1 ·  分享

unity 用代码控制动画的播放的进度 ashishsfb  · 2017年05月10日 11:13 0

I am trying to control my animation via scroll wheel, and this method works fine. Thanks for posting. :)

unity 用代码控制动画的播放的进度

0

个解答,截止mbrako · 2016年08月10日 19:27

I got it working! Thanks @vfxjex

For anybody thats looking for how I got it to work, I put a step-by-step tutorial (Im still a noob to Unity so my explanation is very basic!!)

Lets use a simple example to demonstrate how to use a slider to control a simple animated object that has been exported (fbx)

Im using a model of fingers pinching a skin anatomical figure that I built and animated called 'handAnimationsv002'. I’ve exported the model, joints and blend shape (animated from frame 0-24). I will refer to the names I used in the project, but substitute whatever you may have. Use these images to reference the figuresunity 用代码控制动画的播放的进度 unity 用代码控制动画的播放的进度 Import your fbx into your Unity project (Im using the 2D option)

Figure 1. Select your model. Go into the ‘Rig’ tab. Change Animation type to Legacy and hit Apply.

Figure 2 Create your Canvas (this will add an EventSystem to your project). Drag your fbx over the canvas to create a child of Canvas.

I adjusted the scale and rotation for this just because my export came out too small. Ive also put in a directional light (default) to light this model.

Expand the fbx icon in your project folder to reveal all the parts of the model.

Ive changed name of the icon with the play button to ‘animateHand’ for the script later.

Drag the ‘animateHand’ icon into the value of Animation and make sure your size is set to 1.

Hit Play. You may not see anything. In this case. Ive adjusted both my canvas and main camera settings. I also switched over to 3D view temporarily to see how things are aligned.

Figure 3 Take note of your Pos X and Pos Y to use on your Main Camera Settings. Change the render mode to ‘World Space’ .

Figure 4 Select the Main Camera and Plug in the X and Y position to match the canvas.

Using your 3D scene, move the camera in Z-Axis to get your models in view.

Adjust the Size and Clipping Planes accordingly.

Hit Play now and the scene should be in place. If you notice the object animates, turn off ‘Play Automatically’ on ‘handAnimationsv002’ setting

Figure 5 Create the script ‘AnimControl’ and copy paste this script (courtesy of @vfxjex )

using UnityEngine; using UnityEngine.UI; using System.Collections;

public class AnimControl : MonoBehaviour { Animation anim;

  1. //Drag and drop your Slider into this variable.

  2. public Slider slider;

  3. // Use this for initialization

  4. void Start () {

  5. anim = GetComponent<Animation> ();

  6. //Make sure you have attached your animation in the Animations attribute

  7. anim.Play ("animateHand");

  8. anim ["animateHand"].speed = 0;

  9. }

  10. void Update (){

  11. anim ["animateHand"].normalizedTime = slider.value;

}

}

Select ‘handAnimationsv002’ in the hierarchy and drag the AnimControl script into the components area Then drag ‘Slider’ into the ‘slider value’

Figure 6 Select Slider in the hierarchy and drag Slider to the On Value Changed (Single) value

Figure 7 Select value for the Function

Press Play and try it!!

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Easter79 Easter79
3年前
swap空间的增减方法
(1)增大swap空间去激活swap交换区:swapoff v /dev/vg00/lvswap扩展交换lv:lvextend L 10G /dev/vg00/lvswap重新生成swap交换区:mkswap /dev/vg00/lvswap激活新生成的交换区:swapon v /dev/vg00/lvswap
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
4个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Wesley13 Wesley13
3年前
Java获得今日零时零分零秒的时间(Date型)
publicDatezeroTime()throwsParseException{    DatetimenewDate();    SimpleDateFormatsimpnewSimpleDateFormat("yyyyMMdd00:00:00");    SimpleDateFormatsimp2newS
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
10个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这