Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

the problem with bullets...

Discussion in 'Getting Started' started by Steel598, Jul 12, 2017.

  1. Steel598

    Steel598

    Joined:
    Apr 22, 2017
    Posts:
    17
    I have been using this website for my shooting code: https://mega.nz/#F!dkklTQiR!WL25e1TKLmhYKQT2RpIXNA
    when I use this it lets me have a limited time with the bullet and its clones, or i get to keep the bullet and all its clones. here is the code that uses bullet and shoots it:
    Code (JavaScript):
    1. static var ammo = 100;
    2. static var maxAmmo = 100;
    3. var key : String = "mouse 0";
    4. var bullet : Rigidbody;
    5. var speed : float = 1000;
    6.  
    7. function Update () {
    8.     if(Input.GetKeyDown(key)){
    9.         if(ammo > 0){
    10.             shoot();
    11.         }
    12.     }
    13. }
    14. function shoot(){
    15.     var bullet1 : Rigidbody = Instantiate(bullet, transform.position, transform.rotation);
    16.     bullet1.AddForce(transform.forward * speed);
    17.     ammo --;
    18. }
    19.  
    is there a way that i can delete the clones after a certain amount of time??? i see people doing it, but i have no idea... thanks!
     
  2. DanielQuick

    DanielQuick

    Joined:
    Dec 31, 2010
    Posts:
    3,137
    Code (csharp):
    1. // After you instantiate the bullet
    2. Destroy(bullet1.gameObject, destroyDelay);
     
  3. Steel598

    Steel598

    Joined:
    Apr 22, 2017
    Posts:
    17
    thank you.
     
  4. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
  5. GeorgeCH

    GeorgeCH

    Joined:
    Oct 5, 2016
    Posts:
    222
    What he said.

    Object pooling might sound a bit complex at first, but it is an extremely good habit to get into (and if you ever plan on releasing your game on a mobile device, it's probably a must). Just yesterday, I rewrote my game to replace instantiation with object pooling and my FPS tripled.

    With instantiation, you create a copy of the desired object every time you need one and destroy it when you no longer need it. Doing so with too many objects (bullets are an excellent example) will slow the game down over time.