Unity2D: Start a new Coroutine whenever a button has been pressed

Is there a way how to start a new Coroutine whenever a button has been pressed? I made a script to check how many times a button has been pressed but I don't know how to implement a call which would increment the press count inside the Corutine (buttonCount++). Is it possible?

public int buttonCount = 0;

public void Check() {
    buttonCount ++;
}

This is what I'm using StartCoroutine for:

public GameObject LeftUp, RightUp, LeftDown, RightDown, ForceSphere;
public int buttonCount = 0;

public void Check() {
    buttonCount ++;
}

public void ActivateForceField ()
{
        StartCoroutine (CreateForceField ()); 
        forceActive = true; 
}

IEnumerator CreateForceField ()
{
    LeftUp.SetActive (true);
    RightUp.SetActive (true);
    yield return new WaitForSeconds (1.0f);
    LeftDown.SetActive (true);
    RightDown.SetActive (true);
    yield return new WaitForSeconds (1.0f);
    LeftUp.SetActive (false);
    RightUp.SetActive (false);
    yield return new WaitForSeconds (1.0f);
    LeftDown.SetActive (false);
    RightDown.SetActive (false);
    //yield return new WaitForSeconds (1.0f);
    ForceSphere.SetActive (true);
    yield return new WaitForSeconds (10.0f);
    ForceSphere.SetActive (false);

    forceActive = false;
}

I tried putting Check(); in my IEnumerator at the beginning but it didn't work. Thank you :)


for example if your script that contains ActivateForceField is called TheScript then

create a UI button, in your inspector select your button, then

-look for the button script in the inspector,then

-look for "On click"

-Then select the gameobject that contains TheScript

-then in the next selection box , select TheScript -> ActivateForceField()

this way each time your button is clicked this function will be called

链接地址: http://www.djcxy.com/p/53176.html

上一篇: IEnumerator的yield返回null

下一篇: Unity2D:每按一次按钮就开始一个新的协同程序