I am working on a resource collection script. Every frame, the game checks if you are hovering over a resource and if you are holding down right mouse button. If so, and here is my problem, there should be a collection wait time(cooldown) and then your resource amount should increase by one. However, neither route i’ve tried to take works. With invoke, it correctly waits for the specified time before actually giving the resource, but than continues to give me resources, without waiting again. Same goes for WaitForSeconds in a coroutine. I need a way to reuse the wait for either of these methods, but can’t seem to find out how. Any help would be very much appreciated. Here is my code:
using System.Collections;
using UnityEngine;
[RequireComponent(typeof(CameraRaycaster))]
public class gatherResource : MonoBehaviour
{
new Camera camera;
CameraRaycaster camRay;
bool onResource = false;
bool onCooldown = true;
public float gatherSpeed = 3;
public int testResource = 0;
public Coroutine collectResource = null;
// Use this for initialization
void Start ()
{
camera = FindObjectOfType<Camera>();
camRay = camera.GetComponent<CameraRaycaster>();
camRay.onLayerChange += LayerIsResource;
}
private void Update()
{
while (Input.GetMouseButton(1) && onResource == true)
{
print(testResource);
Invoke("CollectResource", gatherSpeed);
break;
}
}
void LayerIsResource(Layer currentLayer)
{
if (currentLayer == Layer.Resource)
onResource = true;
else
onResource = false;
}
float CollectResource()
{
return testResource++;
}
}