Need help with randomize attack time. Please help!

The concept is simple. There are 5 variables, shootTime, coolDown, timer, minTime, and maxTime. The timer is constantly going up by 1 per second (I used Time.Delta), but only between “minTime” and “maxTime”. so ie; 1,2,3,4 “reset” 1,2,3,4 and so on. So if “timer” is equal to “shootTime”, fire a missle(i already have that code) then randomize the shootTime between the minTime and maxTime. This is kind of like space invaders attack style. That is the random attack type I am looking for. Theres is a mob of enemies all attacking at the random rates between a set amount in my case between 0 and 5.

Can anyone help me fix this code?

using UnityEngine;
using System.Collections;

public class EnemyAttack : MonoBehaviour {
	
	
	//------Variables Start------
	
	public 		float 		time;
	public 		float 		minTime;
	public 		float 		maxTime;
	public 		float 		shootTime;
	public 		GameObject 	missile;
	
	//------Variables End------
	
	
	void Start()
	{
		//Give all enemies a random shootTime to start with.
		shootTime = Random.Range(minTime,maxTime);
	}
	
	// Update is called once per frame
	void Update () 
	{
		
		//Do not allow the time to exceed the limits of minTme and maxTime.
		time = Mathf.Clamp(time,minTime,maxTime);
		
		//Add 1.0 every second.
		time += 1f  * Time.deltaTime;
		
		//If time reaches the max, reset.
		if(time >= maxTime)
		{
			time = minTime;
		}
		
		if(time >= shootTime)
		{
			//Shoot missle. Having trouble here. It instantiates like 20 at a time.
			//I think it has to do with the time >= shootTime but if i put == it doesn't work for me.
			Instantiate(missile,transform.position,transform.rotation);
			
			//Randomize the next shootime.
			shootTime = Random.Range(minTime,maxTime);
		}
	}
}

You may want to check out the [Coroutine Documentation][1] [1]: http://docs.unity3d.com/Documentation/ScriptReference/Coroutine.html You can randomize a waitTime variable that is passed into the coroutine and avoid all of the conditional checks in your Update() function.

I tried that but i can't figure out how to make it work right. Where do I start it? If i put start coroutine in the start function it only runs once. if i put it in the update it calls it every frame. how would i do this? the examples don't really help use it for what im looking for

2 Answers

2

Here is what I’ve noticed in your code.

-You don’t need to multiply deltaTime by 1, just add deltaTime every FixedUpdate.

-You don’t need the clamp

-After your Instantiate, reset your time to 0

Let me know how you get on after those changes :slight_smile:

How do I do the add delta every fixed update?

I think I figured it out my self by using this code.

void Update () 
	{
		fireRate = Random.Range(minTime,maxTime);
		
		if(Time.time > nextFire)
		{	
			nextFire = Time.time + fireRate;
			
			Instantiate(missile,transform.position,transform.rotation);
		}
	}