Unity 3D:使用 UI 按钮更改精灵动画
Unity 3D: Changing sprite animation using UI button
我正在学习关于 youtube 关于在代码中更改 sprite 动画的教程,我想知道是否可以使用 UI 按钮将其更改为更改 sprite 动画。有谁知道如何做到这一点。谢谢!
编辑:
多亏了你的帮助,我重新放置的脚本可以正常工作,它将 sprite 图像从图像 1 更改为图像 2 但我基本上想要实现的是每次单击 UI 按钮时 sprite 图像精灵图一(UI 按钮点击)> 精灵图二(UI 按钮点击)> 精灵图三(UI 按钮点击)> 然后重复这个过程而不是精灵图图片自动更改。
按钮有一个 OnClick 事件 http://docs.unity3d.com/ScriptReference/UI.Button-onClick.html
您只需创建一个在单击按钮时调用的方法,在您的例子中是更改精灵代码。被视为您正在使用计时器,但您需要使用类似 bool 的东西,因为 onClick()
仅在单击时被调用一次,而不是每一帧。
看https://www.youtube.com/watch?v=J5ZNuM6K27E
bool b_RunSpriteAnim;
public void onClick(){
b_RunSpriteAnim = true;
}
void Update(){
if (b_RunSpriteAnim)
//your anim sprite stuff
}
然后一旦精灵动画完成,只需切换 b_RunSpriteAnim
到 false
并重置计时器。
已编辑:
你不需要布尔值。我只是认为你想要它是因为你在使用计时器(基于 Youtube link)。如果您只想立即更改精灵,则不需要它。至于 Imagethree
不起作用,那是因为您从未将它包含在您的代码中。目前还不清楚你想用 Imagethree
实现什么,如果你把它也包含在 onClick
中,它只会覆盖刚刚设置的图像二,所以我不确定你是什么期待实现。
public void onClick(){
this.gameObject.GetComponent<SpriteRenderer>().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++];
}
我正在学习关于 youtube 关于在代码中更改 sprite 动画的教程,我想知道是否可以使用 UI 按钮将其更改为更改 sprite 动画。有谁知道如何做到这一点。谢谢!
编辑: 多亏了你的帮助,我重新放置的脚本可以正常工作,它将 sprite 图像从图像 1 更改为图像 2 但我基本上想要实现的是每次单击 UI 按钮时 sprite 图像精灵图一(UI 按钮点击)> 精灵图二(UI 按钮点击)> 精灵图三(UI 按钮点击)> 然后重复这个过程而不是精灵图图片自动更改。
按钮有一个 OnClick 事件 http://docs.unity3d.com/ScriptReference/UI.Button-onClick.html
您只需创建一个在单击按钮时调用的方法,在您的例子中是更改精灵代码。被视为您正在使用计时器,但您需要使用类似 bool 的东西,因为 onClick()
仅在单击时被调用一次,而不是每一帧。
看https://www.youtube.com/watch?v=J5ZNuM6K27E
bool b_RunSpriteAnim;
public void onClick(){
b_RunSpriteAnim = true;
}
void Update(){
if (b_RunSpriteAnim)
//your anim sprite stuff
}
然后一旦精灵动画完成,只需切换 b_RunSpriteAnim
到 false
并重置计时器。
已编辑:
你不需要布尔值。我只是认为你想要它是因为你在使用计时器(基于 Youtube link)。如果您只想立即更改精灵,则不需要它。至于 Imagethree
不起作用,那是因为您从未将它包含在您的代码中。目前还不清楚你想用 Imagethree
实现什么,如果你把它也包含在 onClick
中,它只会覆盖刚刚设置的图像二,所以我不确定你是什么期待实现。
public void onClick(){
this.gameObject.GetComponent<SpriteRenderer>().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++];
}