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);
	}
}

2 Answers

2

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.

Ok, I'm not entirely sure what to do with this...

–

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;