- Home /
The question is answered, right answer was accepted
coroutine in update method
Hi, I am new at unity and I need your precious help for controlling coroutine method. The thing is I want my object to move forward and then back. It moves forward with no problem, but when it starts to move backward, it also try to move forward. so it flickeringly comes back to originial point. I dont know why it works right for forward but not work properly when it moves backward. I try to control it with some boolean values but couldnt figure out to appropriate usage. If you could hep, I really really be appreciated. Here is my code part;
_pushing = false;
_returning=false;
private void Update
{
if (Input.GetMouseButtonDown(0))
{
firstTouchPos = Input.mousePosition;
}
if (Input.GetMouseButton(0))
{
// does something
}
//if mouse released
else
{
rb.velocity = Vector3.zero;
StartCoroutine("Push", 2);
}
}
private IEnumerator Push(float duration)
{
if (!_pushing)
{
TransformMovingPusher.position += Vector3.forward * 5 * Time.deltaTime;
Debug.Log("forward!");
yield return (new WaitForSeconds(3));
_returning = true;
_pushing = true;
}
if (_returning)
{
Debug.Log("backward!");
TransformMovingPusher.position += Vector3.back *5 * Time.deltaTime;
yield return (new WaitForSeconds(3));
_returning = false;
}
}
I want it like this
and this is the output part. I have 2 different backward ouputs??
Answer by nicoleskryp · May 29, 2021 at 04:36 PM
Use Input.GetMouseButtonUp(0) to accurately get when the mouse is released. The way you're using (Input.GetMouseButton(0)) recieves too many repetitive calls. Read about them all here: https://docs.unity3d.com/ScriptReference/Input.html
I'm not sure why you have so many mouse clicks but if you want the user to click and it moves forward for duration, then moves backwards for same duration just do this:
void Update()
{
//Only gets called once on mouse release
if (Input.GetMouseButtonUp(0))
{
//Call coroutine
StartCoroutine(Push(2));
}
}
private IEnumerator Push(float duration)
{
float timeElapsed = 0;
while (timeElapsed < duration)
{
print("moving forward");
TransformMovingPusher.position += Vector3.forward * 5 * Time.deltaTime;
timeElapsed += Time.deltaTime;
yield return null;
}
//Reset time to move backwards for same duration
timeElapsed = 0;
while (timeElapsed < duration)
{
print("moving back");
TransformMovingPusher.position += Vector3.back *5 * Time.deltaTime;
timeElapsed += Time.deltaTime;
yield return null;
}
}
Follow this Question
Related Questions
Make a function that can return string or IEnumerator 2 Answers
Coroutine Not Working 2 Answers
Coroutines IEnumerator not working as expected 2 Answers
Use Coroutine when object rotates 2 Answers