-3

I want to make a code run for a few seconds in if statement like I want to make BoxCollider.enabled=false whenever I press "e" and make BoxCollider.enabled=true again after a few seconds. How can I do this?

I tried the invoke method but it's not working.

    if (Input.GetKeyDown("e"))

    {
        BoxCollider.enabled = false;

        Invoke("enable", 2f);
    }

    void enable()

    {
        BoxCollider.enabled = true;

     }

3 Answers3

1

Well I am a beginner just like you, but i think i have a solution for your problem

    public float waitTime = 0f;
public void Update()
{
    waitTime = waitTime + Time.deltaTime;

    if (Input.GetKeyDown("e"))
    {
        BoxCollider.enabled = false;
        waitTime = 0;
    }
    if (waitTime >= 2)
    {
        BoxCollider.enabled = true;
    }

}

what i did here is i created a variable that count seconds and i reset it to 0 after the user presses E then when it becomes 2 the boxCollider.enabeled = true again

1

Most elegant way would be using a coroutine

    if (Input.GetKeyDown("e")){
        BoxCollider.enabled = false;  
        StartCoroutine(EnableCoroutine());      
    }

    ...

    IEnumerator EnableCoroutine() {
        //A coroutine can 'wait' until something is done
        //yield return null; would wait a single frame

        yield return new WaitForSeconds(2);

        //After 2 seconds the following code will be executed
        BoxCollider.enabled = true;
    }
Anton Mihaylov
  • 938
  • 5
  • 10
0

You could use a Timer.

Try the following example:

class Program
{
    static bool boxCollider = true;
    static Timer aTimer;
    static void Main(string[] args)
    {
        var key = Console.ReadKey();
        if (key.Key == ConsoleKey.E)
        {
            Console.WriteLine("The key was pressed at {0:HH:mm:ss.fff}", DateTime.Now);
            boxCollider = true;
            aTimer = new System.Timers.Timer(2000);
            aTimer.Elapsed += onTimerEnded;
            aTimer.Enabled = true;
        }
        Console.ReadLine();
    }

    private static void onTimerEnded(object sender, ElapsedEventArgs e)
    {
        Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
                      e.SignalTime);
        Enable();
        aTimer.Enabled = false;
        aTimer.Dispose();
    }

    private static void Enable()
    {
        boxCollider = true;
    }

The BoxCollider will be reset after the interval is reached.

tobre
  • 1,347
  • 3
  • 21
  • 53