首页 > 解决方案 > 如何通过脚本为材质 alpha 属性设置动画?

问题描述

我正在通过脚本创建 Animator OverrideController,该脚本基于分配给 animator 组件的当前控制器。我已经为位置创建了动画曲线,它可以工作。当我尝试为透明度设置动画(材质颜色 alpha)时,它不起作用。我是否未能正确访问此属性?

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

public class AnimationScript : MonoBehaviour {

    void Start()
    {
        AnimationClip clip = new AnimationClip();

        AnimationCurve curve = AnimationCurve.EaseInOut(0.0f, transform.position.x, 1.0f, transform.position.x);
        clip.SetCurve("", typeof(Transform), "localPosition.x", curve);

        curve = AnimationCurve.Linear(0.0f, 1.0f, 1.0f, 0.0f);
        clip.SetCurve("", typeof(Material), "_Color.a", curve);

        Animator anim = GetComponent<Animator>();
        AnimatorOverrideController animatorOverrideController = new AnimatorOverrideController(anim.runtimeAnimatorController);
        // "loop" is the name of clip not name of state
        animatorOverrideController["loop"] = clip;
        anim.runtimeAnimatorController = animatorOverrideController;
    }

}

然而,遗留动画组件的类似代码可以工作:

void Start()
{
    Animation anim = GetComponent<Animation>();
    AnimationCurve curve;

    // create a new AnimationClip
    AnimationClip clip = new AnimationClip();
    clip.legacy = true;

    // update the clip to a change color
    curve = AnimationCurve.Linear(0.0f, 1.0f, 2.0f, 0.0f);
    clip.SetCurve("", typeof(Material), "_Color.a", curve);

    // now animate the GameObject
    anim.AddClip(clip, clip.name);
    anim.Play(clip.name);
}

我错过了什么,为什么第一个脚本不起作用?

标签: unity3d

解决方案


推荐阅读