- Home /
How stop a piece of code from running if the conditions are no more met.
Hello, I'm quite new to scripting and i need help with a piece of code. What I'm basically trying to do is that... Lets say I'm cutting a tree in a rpg game. If i move too far away from the tree, i want him to "stop cutting the tree".
IEnumerator OnMouseDown()
{
float distance = Vector3.Distance(transform.position, pelaaja.position);
GameObject Player = GameObject.Find("Player");
GameMaster gameMaster = Player.GetComponent<GameMaster>();
if(distance <= 1.414214f && gameMaster.gatheringResources == false )
{
float choppingTime = Random.Range(chopMin, chopMax);
print(choppingTime);
gameMaster.gatheringResources = true;
yield return new WaitForSeconds(choppingTime);
Inventory inventory = Player.GetComponent<Inventory>();
inventory.wood += 1;
print("You Just Chopped a log");
gameMaster.gatheringResources = false;
Destroy(gameObject);
}
else
{
print("You are either too far or already choping") ;
}
}
So basically what I'm trying to ask is that if the distance grows larger than 1.414214 while the yield is running, how do i make the rest of the code stop from running and instead print something like "you moved too far". I hope you can understand my question. If you need more info go ahead and ask. I'm guessing it has something to do with a while loop, I just couldn't get it to work
oh also if you wonder what "pelaaja" means, its just player in Finnish.
Answer by SirCrazyNugget · Jul 24, 2014 at 04:05 PM
I'd do something like:
void OnMouseDown(){
float endChoppingTime = Time.time + Random.Range(chopMin, chopMax);
//begine chopping
DoChopping(endChoppingTime);
}
IEnumerator DoChopping(float endTime){
while(Time.time < endTime){
if(distance <= 1.414214f &! gameMaster.gatheringResources){
//continue chopping
yield return new WaitForEndOfFrame();
}else{
//stop chopping
yield break;
}
}else{
//finished chopping
yield break;
}
}