- Home /
Limit number of bullet on screen c#
Hey guys! I'm almost done with my project but I need a last bit of help.
I got a script for my enemies to fire at random rate, but sometime even random can fail me. I'd like a way to limit the number of bullet that can be instantiated at the same time on my screen. For example, if five of my enemies shoot at the same time, the others won't be able to shoot until those five bullets are gone. (I already have a timer for my bullets to vanish after some seconds) here is my shooting script
using UnityEngine;
using System.Collections;
public class canonenemy : MonoBehaviour {
public GameObject bolt;
public Transform Canon;
public float fireRatep;
public float fireRatem;
private float nextFire = 0.0f;
// Use this for initialization
void Start () {
nextFire = nextFire + Random.Range (fireRatep, fireRatem);
}
// Update is called once per frame
void FixedUpdate () {
if (Time.time > nextFire) {
nextFire = Time.time + Random.Range (fireRatep, fireRatem);
Instantiate (bolt, Canon.position, Canon.rotation);
}
}
}
Not sure what can be done about it... Thanks in advance!
Answer by Eluate · Jan 01, 2015 at 10:17 PM
You should have a tinker with FindGameObjectsWithTag and tags.
A solution for this question would be to assign a tag to the bolt and then using this if statement to find the amount of gameobjects with the tag in the scene.
if (GameObject.FindGameObjectsWithTag(tag).Length < 5) {
boltObject = (GameObject)Instantiate (bolt, Canon.position, Canon.rotation);
boltObject.tag = tag;
}
Note: Tags must be declared in the tag manager before using them.
Unity says it doesn't know the .length I didn't use the exact code you gave because I need the double argument of fire-rate and bullet number in my 'if'.
using UnityEngine;
using System.Collections;
public class canonenemy : $$anonymous$$onoBehaviour {
public GameObject bolt;
public Transform Canon;
public float fireRatep;
public float fireRatem;
private float nextFire = 0.0f;
// Use this for initialization
void Start () {
nextFire = nextFire + Random.Range (fireRatep, fireRatem);
}
// Update is called once per frame
void FixedUpdate () {
if ((Time.time > nextFire) && (GameObject.FindWithTag("enemybolt").Length < 5)) {
nextFire = Time.time + Random.Range (fireRatep, fireRatem);
Instantiate (bolt, Canon.position, Canon.rotation);
}
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to limit bullets in screen like old NES game 4 Answers
Make my gun model fire bullets 1 Answer
Bullet fires before direction change 0 Answers