- Home /
Duplicate Question
How to make a timer that loops with booleans?
I have 3 scripts: Melee script is a raycast that shoots 5 meters out and when it hits something it calls the gameObject's function "PickItemUp". The OrangeScript initiates the timer afterwards and "picks up" the orange. The OrangeSpawnerScript then starts a timer from 5 seconds and when it reaches 0 it spawns a new orange and should be able to loop. This is where I am having problems as when I first start the game the timer goes down and an orange spawns and I can "pick it up", but then afterwards the boolean that enables the timer does NOT enable itself again. I can MANUALLY set it to true through the inspector however, but my script won't do it by itself. Here are the scripts:
using UnityEngine; using System.Collections;
public class Melee : MonoBehaviour {
public float maxDistance = 5.0F;
void Update ()
{
if(Input.GetKeyDown(KeyCode.E))
{
RaycastHit hit;
if(Physics.Raycast (transform.position, transform.TransformDirection(Vector3.forward), out hit))
{
float hitDistance = hit.distance;
if(hitDistance < maxDistance)
{
hit.transform.SendMessage("PickUpItem", SendMessageOptions.DontRequireReceiver);
}
}
}
}
}
using UnityEngine; using System.Collections;
public class OrangeScript : MonoBehaviour {
public OrangeSpawnerScript OSScript;
public void PickUpItem ()
{
OSScript.Timer();
Destroy(gameObject);
}
}
using UnityEngine; using System.Collections;
public class OrangeSpawnerScript : MonoBehaviour {
public Transform theOrange;
public float timer = 5.0F;
public bool timerEnabled;
public void Timer ()
{
timerEnabled = true;
}
void Update ()
{
if(timerEnabled)
{
timer -= 1 * Time.deltaTime;
if(timer <= 0)
{
Instantiate(theOrange, transform.position, transform.rotation);
timerEnabled = false;
timer = 5.0F;
}
}
}
}
Thanks so much in advance :)
Do not do anything like this at all.
be sure to use Invoke() and InvokeRepeating() for simple timers in Unity.
there are 100s great questions on here about it, and, unityGE$$anonymous$$S.com for many articles.
In your case it would be something like InvokeRepeating("makeAnOrange", 5, 5);
it's just that simple.
to stop it happening, "InvokeCancel("makeAnOrange");"
to start it again InvokeRepeating("makeAnOrange", 5, 5);
first search please, cheers
Ins$$anonymous$$d of telling me the obvious path to success why don't you help me out and actually show me the location of these so called 100's of questions? I'll wait while you find me some; please hurry.
Answer by bodec · May 07, 2013 at 06:27 AM
on your first script you need to access your spawn script and reset the Boolean to start your timer again. You could also reset it if(no child exist)then spawn. (not real code but idea).