Animation Unity 3D:使用UI按钮更改精灵动画

Animation Unity 3D:使用UI按钮更改精灵动画,animation,unity3d,sprite,Animation,Unity3d,Sprite,我正在学习关于在代码中更改精灵动画的教程,我想知道是否可以使用UI按钮将其更改为更改精灵动画。有人知道怎么做吗。谢谢大家! 编辑: 由于您的帮助,我所使用的脚本工作正常,它将精灵图像从图像一更改为图像二,但我基本上尝试实现的是,每次单击UI按钮,精灵图像将从精灵图像一(UI按钮单击)>精灵图像二(UI按钮单击)>精灵图像三(UI按钮单击)>然后重复该过程,而不是精灵图像自动改变自身。按钮有OnClick事件 您只需创建一个在单击按钮时被调用的方法,在您的示例中是不断变化的sprite代码。尽管您

我正在学习关于在代码中更改精灵动画的教程,我想知道是否可以使用UI按钮将其更改为更改精灵动画。有人知道怎么做吗。谢谢大家!

编辑:
由于您的帮助,我所使用的脚本工作正常,它将精灵图像从图像一更改为图像二,但我基本上尝试实现的是,每次单击UI按钮,精灵图像将从精灵图像一(UI按钮单击)>精灵图像二(UI按钮单击)>精灵图像三(UI按钮单击)>然后重复该过程,而不是精灵图像自动改变自身。

按钮有OnClick事件

您只需创建一个在单击按钮时被调用的方法,在您的示例中是不断变化的sprite代码。尽管您需要使用bool之类的东西,但可以看到您正在使用计时器,因为
onClick()
仅在单击时调用一次,而不是每帧

然后,一旦精灵动画完成,只需将
b_RunSpriteAnim
切换到
false
并重置计时器

编辑: 您不需要布尔值。我以为你想要它是因为你在使用计时器(基于Youtube链接)。如果您只想立即更改精灵,则不需要它。至于
Imagethree
不起作用,这是因为您从未将其包含在代码中。现在还不清楚你想用
Imagethree
实现什么,如果你在
onClick
中也包含这个,它只会覆盖刚刚设置的图像2,所以我不确定你想要实现什么

public void onClick(){
    this.gameObject.GetComponent<SpriteRenderer>().sprite = Imagetwo;
}
public void onClick(){
this.gameObject.GetComponent().sprite=Imagetwo;
}
第二次编辑:

public Sprite[] Images;
//Index starts at one because we are setting the first sprite in Start() method
private int _Index = 1;

void Start(){
    //Set the image to the first one
    this.gameObject.GetComponent<SpriteRenderer>().sprite = Images[0];
}

public void onClick(){
    //Reset back to 0 so it can loop again if the last sprite has been shown
    if (_Index >= Images.Length)
        _Index = 0;

    //Set the image to array at element index, then increment
    this.gameObject.GetComponent<SpriteRenderer>().sprite = Images[_Index++];
}
publicsprite[]图像;
//索引从1开始,因为我们正在Start()方法中设置第一个精灵
私有int_指数=1;
void Start(){
//将图像设置为第一个
this.gameObject.GetComponent().sprite=Images[0];
}
公共void onClick(){
//重置回0,以便在显示最后一个精灵时可以再次循环
如果(_Index>=Images.Length)
_指数=0;
//将图像设置为元素索引处的数组,然后递增
this.gameObject.GetComponent().sprite=Images[_Index++];
}

@JesscaStone 9:40在该教程中,告诉您如何将此onClick方法绑定到按钮。嗯,我试图回复您,但我没有足够的字符,所以我在上面的“添加答案”中留下了我的问题,请阅读,谢谢,嗯,我已经编辑了我的问题,如果您可以查看,那将非常好。如果你能看一看,我将不胜感激。感谢you@JesscaStone更新。在inspector中设置
图像
数组。这应该从第二个->第三个按钮点击,然后第一个->第二个->第三个循环。谢谢,它的工作。我真的很感激,非常感谢,它真的很有帮助。现在还不清楚你想用
Imagethree
做什么,所以我真的不能说。我还编辑了我的答案。你想什么时候换?
public Sprite[] Images;
//Index starts at one because we are setting the first sprite in Start() method
private int _Index = 1;

void Start(){
    //Set the image to the first one
    this.gameObject.GetComponent<SpriteRenderer>().sprite = Images[0];
}

public void onClick(){
    //Reset back to 0 so it can loop again if the last sprite has been shown
    if (_Index >= Images.Length)
        _Index = 0;

    //Set the image to array at element index, then increment
    this.gameObject.GetComponent<SpriteRenderer>().sprite = Images[_Index++];
}