I need to delay an Inventory’s open time, but “yield return WaitforSeconds” is not working. Here is the coroutine’s code:
public IEnumerator CheckIfStillHover() {
yield return new WaitForSecondsRealtime (1.5f); // change to options class variable once it is created
print ("Fine. I admit it. I cut in line. Happy?");
}
In case this has something to do with the way I called it, which I also had difficulty with (if anyone knows why I had to store it in a variable to call it, please tell me), here is the code from a separate script which I used to call the coroutine:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent (typeof (InventoryRenderer))]
public class ToggleInventoryHover : MonoBehaviour {
//name the inventory to match this string (or vice-versa)
public string inventoryName = "Inventory";
GameObject inventory;
IEnumerator coroutine;
bool isHover = false;
void Start() {
inventory = GameObject.Find(inventoryName);
coroutine = inventory.GetComponent<InventoryRenderer> ().CheckIfStillHover ();
}
void OnMouseOver() {
isHover = true;
inventory.GetComponent<InventoryRenderer> ().StartCoroutine(coroutine);
}
void OnMouseExit() {
isHover = false;
}
}
Here’s a possible solution you’re not keeping in mind:
WaitForSeconds DOES NOT WORK AS A DELAY OUTSIDE THE COROUTINE.
When you start a Coroutine, it executes itself, but the script inmediately executes the following instruction. For a WaitForSeconds to work, you need to put the code to open the inventory inside the coroutine method.
It would look something like this:
public IEnumerator CheckIfStillHover() {
yield return new WaitForSecondsRealtime (1.5f); // change to options class variable once it is created
//Whatever you want to delay goes in here
print ("Fine. I admit it. I cut in line. Happy?");
}
i would use the Invoke mehod for this its much more straight forward and in the end is doing the same behind the scenes Unity - Scripting API: MonoBehaviour.Invoke
Also check if OnMouseOver is really called
What do you mean when you say “not working” ? It would help if you identified what problem you’re having.
Is there a reason you are using WaitForSecondsRealtime and not WaitForSeconds(5) ??
I’m new but I’d like to help if I can.
public class Whatever : MonoBehaviour
{
public float delay = 1.5;
void Start()
{
OnMouseOver(); // I use Button also
StartCoroutine (LoadStuffAfterDelay (delay));
}
IEnumerator LoadStuffAfterDelay(float delay)
{
yield return new WaitForSeconds (delay);
//
//Do this next directions here
}
}