How to make a GetKeyUp action to wait for a few seconds before activating
This script is for a platform to drop out (lose collision) when the spacebar is pressed, and regain the collision when the spacebar is released. I want the collision to wait 3 seconds after the spacebar is released to reinstate itself, but I can't figure out how to format it. I don't understand where to put IENumerator or anything. I'm very new to coding so I don't understand the structure very well yet.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GlassToggle : MonoBehaviour {
Collider m_Collider;
void Start()
{
m_Collider = GetComponent<Collider>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
//Toggle the Collider on and off when pressing the space bar
m_Collider.enabled = false;
}
else if (Input.GetKeyUp(KeyCode.Space))
{
m_Collider.enabled = true;
}
}
}
Answer by tormentoarmagedoom · Jun 07, 2018 at 07:46 AM
Good day.
You hava a function called Invoke. It allows you to execute a method in X seconds. So you want something like this:
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
//Toggle the Collider on and off when pressing the space bar
m_Collider.enabled = false;
}
else if (Input.GetKeyUp(KeyCode.Space))
{
Invoke ("EnableCollider", 3);
}
}
public void EnableCollider()
{
m_Collider.enabled = true;
}
GoodBye!
Thank you! It worked perfectly. I couldn't find a solution anywhere else that didn't require me to use IEnumerator but this is really simple. I'll read up more on Invoke as well.
Your answer