- Home /
Making a turret shoot at a low fire rate.
What is the best method to create a turret, that picks a random object from an array of objects, and than shoots it, and waits, say, 2 seconds before the next shot? I got so far as creating the array, instantiating a random gameObject from the array, and shooting it. The only problem is, that I can't solve, is the "waits for 2 seconds" part. Here is the code I wrote so far:
public class ShootingD : MonoBehaviour {
public Rigidbody[] projectiles = new Rigidbody[5];
Rigidbody MyElement;
public void Update()
{
MyElement = projectiles[Random.Range(0,projectiles.Length)];
Instantiate (MyElement, new Vector3(1, 3, 224), new Quaternion (0,-180, -180, 0));
MyElement.animation.Play ("Shrink");
MyElement.AddForce (Vector3.back, ForceMode.Impulse);
}
}
Answer by Graham-Dunnett · Jan 28, 2015 at 10:31 PM
float myTime = 0.0f;
public void Update()
{
myTime += Time.deltaTime;
if (myTime > 2.0f)
{
myTime -= 2.0f;
MyElement = projectiles[Random.Range(0,projectiles.Length)];
//etc
}
Answer by code-blep · Jan 28, 2015 at 10:37 PM
Graham's answer is good. You could also try out IEnumerator and have dedicated functions taking care of things. For example:
using UnityEngine;
using System.Collections;
public class ShootingD : MonoBehaviour
{
public Rigidbody[] projectiles = new Rigidbody[5];
Rigidbody MyElement;
public float delayTime = 2.0f; // Time between shots
public bool shootEnabled; // Toggle shooting off and on
bool shootRunning;
void Start()
{
StartCoroutine(Shoot());
}
IEnumerator Shoot()
{
while (true)
{
if (shootEnabled == true && shootRunning == false)
{
shootRunning = true;
MyElement = projectiles[Random.Range(0, projectiles.Length)];
Instantiate(MyElement, new Vector3(1, 3, 224), new Quaternion(0, -180, -180, 0));
MyElement.animation.Play("Shrink");
MyElement.AddForce(Vector3.back, ForceMode.Impulse);
yield return new WaitForSeconds(delayTime);
shootRunning = false;
}
yield return null;
}
}
}
Ah, I love this answer! But I don't have enough reputation to upvote, so I'll leave it in a comment. :) I'd been wondering about how to achieve something like this and you've just pointed me to the right parts of the Unity docs!
Your answer
Follow this Question
Related Questions
How can I make a list of Classes or Scripts? 3 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
C# for beginners in Unity for multi-platforms? 1 Answer
Questions on improving my pong code 0 Answers