- Home /
Executing multiple actions one after another Unity
Hi, every one. I want execute multiple action in one only funtion, for example
// "moveForward, rotate and moveBackward" are function that have diferent time of execution
// I want to see slow execution
void Update()
{
if (Input.GetKey(KeyCode.UpArrow))
{
moveForward();
for(i=0 to 6){
rotate(90°);
}
moveBackward();
}
}
public void moveForward(){
for(1 to 500){
gameObject.Transform. position = new vector3(1,y,z);
sleep(0.500s);
}
}
public void rotate(){}
public void moveBackward(){}
Comment
Best Answer
Answer by slavo · May 09, 2017 at 11:12 AM
Hello,
Coroutines + dumping should do the job.
https://docs.unity3d.com/Manual/Coroutines.html https://docs.unity3d.com/ScriptReference/Vector3.MoveTowards.html https://docs.unity3d.com/ScriptReference/Vector3.RotateTowards.html
Cheers
Hi Slavo. Fine, but a want execute first action after others action. See example(first moveForward after rotate after moveBackward). Whit Coroutine this execute in parallel (I dont want this)
You can achive this using coroutines. If you yield coroutine, then code is waiting for it ins$$anonymous$$d of run it in parallel.
float speed = 5f; //m/s
float angularSpeed = 10f; //degres per sec
IEnumerator PerformStuffs()
{
for (int i = 0; i < 500; i++)
{
yield return $$anonymous$$oveForward();
}
for (int i = 0; i < 6; i++)
{
yield return Rotate();
}
yield return $$anonymous$$oveBackward();
}
//$$anonymous$$ove Forward 2m
IEnumerator $$anonymous$$oveForward()
{
var newPos = transform.position + transform.forward * 2f;
while (Vector3.Distance(newPos, transform.position) > 0.01f)
{
transform.position = Vector3.$$anonymous$$oveTowards(transform.position, newPos, Time.deltaTime * speed);
yield return null; //wait for next frame
}
}
//$$anonymous$$ove Back 2m
IEnumerator $$anonymous$$oveBackward()
{
var newPos = transform.position - transform.forward * 2f;
while (Vector3.Distance(newPos, transform.position) > 0.01f)
{
transform.position = Vector3.$$anonymous$$oveTowards(transform.position, newPos, Time.deltaTime * speed);
yield return null; //wait for next frame
}
}
IEnumerator Rotate()
{
Quaternion desiredRotation = transform.rotation * Quaternion.Euler(0f, 90f, 0f);
while (Quaternion.Angle(transform.rotation, desiredRotation) > 0.5f)
{
Quaternion.RotateTowards(transform.rotation, desiredRotation, angularSpeed * Time.deltaTime);
yield return null; //wait for next frame
}
}