- Home /
Question by
orenqz · Feb 09, 2019 at 12:31 AM ·
scripting problemif-statementswaitforsecondsgamesstatment
Stopping in the middle of an if statment
Hello everybody, I want to stop my code for 5 seconds in the middle of my code as you see in my code.
I want that if you press X you stop moving (meaning the code stops for 5 seconds).
{ using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerMovment : MonoBehaviour
{
public float speed;
public float dash;
public float waittime;
public Rigidbody2D player;
void Start()
{
StartCoroutine(Example());
}
IEnumerator Example()
{
yield return new WaitForSeconds(waittime);
}
void FixedUpdate()
{
if (Input.GetKey(KeyCode.X))
{
float x = Input.GetAxis("Horizontal") * speed;
float y = Input.GetAxis("Vertical") * speed;
transform.Translate(dash*x, dash * y, 0);
StartCoroutine(Example());
}
else
{
float x = Input.GetAxis("Horizontal") * speed;
float y = Input.GetAxis("Vertical") * speed;
transform.Translate(x, y, 0);
}
}
}
}
Comment
Answer by Crumpet · Feb 09, 2019 at 04:05 AM
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed;
public float dash;
public float waittime;
public Rigidbody2D player;
public float startTime = 5;
public float timer = 5;
bool _enabled = true;
void Start()
{
StartCoroutine(Example());
}
IEnumerator Example()
{
yield return new WaitForSeconds(waittime);
}
void FixedUpdate()
{
if (_enabled)
{
if (Input.GetKey(KeyCode.X))
{
//stop executing here
_enabled = false;
float x = Input.GetAxis("Horizontal") * speed;
float y = Input.GetAxis("Vertical") * speed;
transform.Translate(dash * x, dash * y, 0);
StartCoroutine(Example());
}
else
{
float x = Input.GetAxis("Horizontal") * speed;
float y = Input.GetAxis("Vertical") * speed;
transform.Translate(x, y, 0);
}
}
else
{
timer -= Time.deltaTime;
if (timer <= 0)
{
_enabled = true;
timer = startTime;
}
}
}
}
Your answer
Follow this Question
Related Questions
Both IF statements in a function are run and their conditions are ignored. 4 Answers
Playing the right animation when running and not running 0 Answers
If statement randomly not working 2 Answers
If statement inside FixedUpdate 0 Answers
WaitForSeconds() and WaitForSecondsRealtime() negative number concern!!!! 4 Answers