C# 如何在Unity3D中单击开关?
我想这样做,一旦点击一个按钮,它会做一些东西,当你再次点击它,它会做其他东西C# 如何在Unity3D中单击开关?,c#,unity3d,unityscript,unity5,C#,Unity3d,Unityscript,Unity5,我想这样做,一旦点击一个按钮,它会做一些东西,当你再次点击它,它会做其他东西 using UnityEngine; using System.Collections; public class Ai : MonoBehaviour { bool stopstate = false; Animator _anim; // Use this for initialization void Start () { _anim = GetComponen
using UnityEngine;
using System.Collections;
public class Ai : MonoBehaviour {
bool stopstate = false;
Animator _anim;
// Use this for initialization
void Start () {
_anim = GetComponent<Animator> ();
//_animation = GetComponent<Animation> ();
}
// Update is called once per frame
void Update () {
if (Input.GetKey (KeyCode.Z)) {
if (stopstate == false) {
stopstate = true;
_anim.Stop ();
} else {
stopstate = false;
_anim.StartPlayback ();
}
}
}
}
使用UnityEngine;
使用系统集合;
公共类Ai:单一行为{
bool stopstate=false;
动画师;
//用于初始化
无效开始(){
_anim=GetComponent();
//_animation=GetComponent();
}
//每帧调用一次更新
无效更新(){
if(Input.GetKey(KeyCode.Z)){
if(stopstate==false){
stopstate=true;
_anim.Stop();
}否则{
stopstate=false;
_anim.StartPlayback();
}
}
}
}
有一次我单击了Z Stop(),但如果我在Z上再次按下它,现在播放
问题是代码在Update函数中,所以我在按下Z键后使用了一个断点,它在_anim.StartPlayback()上停止;但当我第二次点击Z时,它应该会到达那里
第二个问题是它何时执行行_anim.StartPlayback();它不会让角色从停止点继续行走
_动画停止();确实要停止它,但StartPlayback()不能让它继续。对您来说,最好的选择是在前端创建一个复选框(让它成为
chktogle
),然后使用以下代码(在初始化或页面加载后)将其外观更改为按钮:
所以它就像前端的一个按钮。然后,您可以使用以下代码在选中时执行某些操作,如果未选中,则执行其他操作
private void chkToggle_CheckedChanged(object sender, EventArgs e)
{
if((sender as CheckBox).Checked)
{
// Do something
}
else
{
// Do other thing
}
}
如果是单个方法,则可以使用boolean
类型的全局变量来保持状态并切换它们;然后代码将如下所示:
bool currentState; // false will be the default value
void Update ()
{
if(currentState)
{
// Dosomething
}
else
{
// Do some other thing
}
currentState = !currentState; // toggle the state
}
使用布尔值跟踪状态?
bool currentState; // false will be the default value
void Update ()
{
if(currentState)
{
// Dosomething
}
else
{
// Do some other thing
}
currentState = !currentState; // toggle the state
}