-1

I want to make it so that once clicking on a button it will make something and when you click on it again it will make something else.

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 ();
            }
        }

    }
}

Once I clicked on Z Stop() but if I press it again on Z now Play.

The problem is that the code is in the Update function so I use a break point once I pressed the Z key it stopped on the _anim.StartPlayback (); but it should get there on the second time i click on Z.

Second problem is when it does the line _anim.StartPlayback (); it's not making the character to continue walking from the point it was stopped.

_anim.Stop(); really stop it but StartPlayback() not make it continue.

Tom
  • 2,372
  • 4
  • 25
  • 45
TheLost Lostit
  • 505
  • 6
  • 28

1 Answers1

1

The best option for you is a CheckBox Create a checkbox in the front-end( let it be chkToggle) and then Change its appearance as button using the following code(after initialize or in page load):

chkToggle.Appearance = System.Windows.Forms.Appearance.Button;

So it will be like a button in the front end. Then you can use the following code to do something if it is checked and do other thing if it is not checked.

private void chkToggle_CheckedChanged(object sender, EventArgs e)
{
    if((sender as CheckBox).Checked)
    {
          // Do something
    }
    else
    {
        // Do other thing
    }
}

if it is a single method then you can use a global variable of type boolean to keep the state and toggle them; then the code will be like the following:

bool currentState; // false will be the default value
void Update () 
{
   if(currentState)
   {
     // Dosomething
   }
   else
   {
    // Do some other thing
   }
    currentState = !currentState; // toggle the state
}
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88