- Home /
Question by
Vice_Versa · Apr 14, 2015 at 09:17 PM ·
collisioncoroutineoncollisionenteryield waitforseconds
How to end a coroutine early
im working on a whack a mole type game. i have it set up so the moles will pop up and down at randomly generated amounts of time using yieldWaitForSeconds. this works fine but i want the moles to pop back down if they collide with the users mallot. the game notices the collisioins, but the moles still stay up for the remaining amount of time. here is my code using UnityEngine; using System.Collections;
public class tester : MonoBehaviour {
bool isMoving = true;
bool moleUp = false;
bool isColliding = false;
public AudioClip moleUpSound;
public AudioClip moleDownSound;
float X;
float Y;
float Z;
// Use this for initialization
void Start()
{
StartCoroutine ("moleMove");
}
void Update()
{
if (this.gameObject.name == "Mole_1") {
X = -1F;
Y = 1.5F;
Z = -1.6F;
} else if (this.gameObject.name == "Mole_2") {
X = 4F;
Y = 1.5F;
Z = -1.6F;
} else if (this.gameObject.name == "Mole_3") {
X = 9F;
Y = 1.5F;
Z = -1.6F;
} else if (this.gameObject.name == "Mole_4") {
X = -1F;
Y = 1.5F;
Z = -6.6F;
} else if (this.gameObject.name == "Mole_5") {
X = 4F;
Y = 1.5F;
Z = -6.6F;
} else if (this.gameObject.name == "Mole_6") {
X = 9F;
Y = 1.5F;
Z = -6.6F;
}
if (moleUp == false) {
if (Y < 3F) {
moveUp();
}
}
if (moleUp == true) {
if (Y > 1F) {
moveDown();
}
}
}
IEnumerator moleMove ()
{
int i;
for (i = 1; i > 0; i++) {
if (moleUp) {
PlaySound ();
moleUp = false;
float generator = Random.Range (2, 3);
yield return new WaitForSeconds(generator);
} else if (moleUp == false) {
PlaySound ();
moleUp = true;
float generator = Random.Range (2, 6);
yield return new WaitForSeconds (generator);
}
}
}
public void PlaySound()
{
if (moleUp) {
audio.clip = moleUpSound;
audio.Play ();
}
if (!moleUp) {
audio.clip = moleDownSound;
audio.Play ();
}
}
public void OnCollisionEnter(Collision col)
{
Vector3 newPosition = new Vector3 (X, 3.5F, Z);
Vector3 oldPosition = new Vector3 (X, -1F, Z);
Debug.Log ("Collision!");
isColliding = true;
moleUp = false;
moveDown ();
}
public void moveUp()
{
if (isColliding == true) {
isColliding = false;
}
Vector3 newPosition = new Vector3 (X, 3.5F, Z);
iTween.MoveTo (gameObject, iTween.Hash ("Position", newPosition, "time", 1, "transition", "spring"));
}
public void moveDown()
{
Vector3 oldPosition = new Vector3 (X, -1F, Z);
iTween.MoveTo (gameObject, iTween.Hash ("Position", oldPosition, "time", 1));
}
}
i would think my moveDown() method in the onCollisionEnter method would move the mole back down, but instead it just bobs around until the remaining time from moleMove runs out. does anybody know how to fix this problem?
Comment