- Home /
Question by
el-mas-pro-470 · Dec 06, 2018 at 08:26 PM ·
script.waitforsecondsactivegetkeydown
reactivate object after seconds not work?
Hi, I'm doing a script that says that when you press the R key, two objects disappear, and when you wait a few seconds they activate again but it does not work, does anyone know anything?
#pragma strict
var Arma : GameObject;
var Disparador : GameObject;
var TiempoRecarga : float;
function Start (){
Arma.active = true;
Disparador.active = true;
}
function Update () {
if(Input.GetKeyDown(KeyCode.R))
{
Arma.active = false;
Disparador.active = false;
yield WaitForSeconds(TiempoRecarga);
Arma.active = true;
Disparador.active = true;
}
}
Comment
Best Answer
Answer by Vega4Life · Dec 06, 2018 at 08:34 PM
You need to create a coroutine function for the yield, you can't just throw it in Update and expect a delay.
IEnumerator Delay(float time)
{
yield return new WaitForSeconds(time);
Arma.SetActive(true);
Disparador.SetActive(true);
}
In your update call it like this:
StartCoroutine(Delay(TiempoRecarga));
You should also us:
Arma.SetActive(true/false);
Disparador.SetActive(true/false);
Also, I wrote C#, so change to javascript how you see fit.
When I press the R if the objects are deactivated, but the seconds do not activate them again, is there an error? Thank you
using UnityEngine;
using System.Collections;
public class ReloadPos : $$anonymous$$onoBehaviour {
public GameObject Gun$$anonymous$$odel;
public GameObject GunShootPoint;
public float time;
void Start () {
StartCoroutine(Delay(time));
}
void Update () {
if(Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.R))
{
Gun$$anonymous$$odel.SetActive(false);
GunShootPoint.SetActive(false);
}
}
IEnumerator Delay(float time)
{
yield return new WaitForSeconds(time);
Gun$$anonymous$$odel.SetActive(true);
GunShootPoint.SetActive(true);
}
}
Yes, you put the StartCoroutine in the wrong location. Try this:
void Update () {
if(Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.R))
{
Gun$$anonymous$$odel.SetActive(false);
GunShootPoint.SetActive(false);
StartCoroutine(Delay(time));
}
You call the coroutine when 'R' is pressed. :) Now it should work for you.