- Home /
Calling a function every x seconds and running another function
As the title says, I'm trying to call this function every x seconds
void stuff () {
treeenergy = treeenergy + Random.Range(1,25);
if (treeenergy >= 100)
Instantiate(Tree, new Vector3(x, 0, z), Quaternion.identity);
This is the whole code:
using UnityEngine;
using System.Collections;
public class Treestuff : MonoBehaviour {
public float treeenergy;
public float treeleaves;
public float leafsize;
public float treehieght;
public float x;
public float z;
GameObject Tree;
void Awake () {
treeenergy = 15;
treeleaves = Random.Range(1,100);
leafsize = Random.Range(1,100);
treehieght = Random.Range(1,100);
x = Random.Range(1,10);
z = Random.Range(1,10);
Tree = Resources.Load ("Tree") as GameObject;
}
// Use this for initialization
void Start () {
treeenergy = 15;
}
// Update is called once per frame
void Update () {
}
void stuff () {
treeenergy = treeenergy + Random.Range(1,25);
if (treeenergy >= 100)
Instantiate(Tree, new Vector3(x, 0, z), Quaternion.identity);
}
}
Comment
Answer by Dave-Carlile · Feb 01, 2013 at 05:36 AM
From the documentation:
function InvokeRepeating (methodName : String, time : float, repeatRate : float) : void
Invokes the method methodName in time seconds. After the first invocation repeats calling that function every repeatRate seconds.
Answer by gfvfubb · Feb 01, 2013 at 05:39 AM
An alternative example from Angrybots AutoFire.js
if (Time.time > lastFireTime + 1 / frequency) {
// Spawn visual bullet
var coneRandomRotation = Quaternion.Euler (Random.Range (-coneAngle, coneAngle), Random.Range (-coneAngle, coneAngle), 0);
var go : GameObject = Spawner.Spawn (bulletPrefab, spawnPoint.position, spawnPoint.rotation * coneRandomRotation) as GameObject;
var bullet : SimpleBullet = go.GetComponent.<SimpleBullet> ();
lastFireTime = Time.time;
Your answer
![](https://koobas.hobune.stream/wayback/20220613091942im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Calling JS Static Function from C# Script 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
My function doesn't appears in the OnClick button script 5 Answers
What are these things doing in C#? 3 Answers