- Home /
Fire fixed number of bullets
I am firing a cannon that fires bullets, but I would like to limit the number of bullets on screen per player, just like in megaman when you can only have 3 bullets on the screen at a time. Anyone care to share a pear? (A example code would be nice)
The solution will depend on your firing code, how you have your game structured, and how you want to define the lifespan of the bullets. Are you reusing bullets are are you destroying and instantiating new ones? Do you literally want to detect if the bullet is still visible, or do you want to give each bullet a lifespan? Posting your firing code would help.
I want to detect if the bullets from a player are still in the world, so if 1 of the 3 fired bullets gets destroyed, I can immediately fire another.
Answer by robertbu · Feb 25, 2014 at 05:54 AM
I want to detect if the bullets from a player are still in the world
One solution is to give your bullets a tag that is only used for bullets. Say you use 'Bullet' and are firing on a mouse click, you can do:
var countOfExistingBullets = GameObject.FindGameObjectsWithTag("Bullet").Length;
if (countOfExistingBullets < 3 && Input.GetMouseButtonDown(0)) {
// Firing code goes here
}
Also, it should go without saying, but just in case - you'll want to destroy your bullets when they hit solid geometry. So in the script attached to your bullet's GameObject (assu$$anonymous$$g your bullet has a collider):
function OnCollisionEnter(other:Collider) {
//this line will let you make other GameObjects react to
//being hit by a bullet as long as they have a collider,
//are on the right layer to collide with bullets, and
//have a function called TryDamage(int damageAmount)
other.Send$$anonymous$$essage("TryDamage",1,Send$$anonymous$$essageOptions.DontRequireReceiver);
//maybe spawn some bullet-explosion-on-impact prefab here
Destroy(gameObject);
}
ALRIGHT, the code has worked. Also, I implemented it so that it works with multiplayers. Thanks
Your answer
![](https://koobas.hobune.stream/wayback/20220613134637im_/https://answers.unity.com/themes/thub/images/avi.jpg)