Implementation of object pooling in Unity3d

Source: Internet
Author: User

In unity, you often encounter situations where you need to recreate, destroy certain objects, such as bullets in FPS games, monsters in RPG games, and so on, if you use instantiate and destroy directly, you will waste your system resources, while using object pooling can save the waste.

Here is a simple scenario for using a reusable bullet to launch a demo object pool.

First you need to create a cube in the scene and act as a bullet.

Then create the resources folder under the Assets directory, add a rigid body to the cube, remove the gravity, drag the cube into the Resources folder as a preset, and delete the cube in the scene.

The script that creates the object pool, because the object pool needs to be called globally, makes it easier to use singleton mode for object pool scripting.

Hang the Objectpoolmag script on the camera.

1  Public classObjectpoolmag:monobehaviour {2      Public StaticObjectpoolmag _instance;3     Privatedictionary<string, stack> pool =Newdictionary<string, stack>();4    5     voidAwake () {6_instance = This;7     }8 9      PublicGameobject Get (stringPrefabname,vector3 position,quaternion rotation) {Ten  One         stringKey = Prefabname +"(Clone)"; A Gameobject GetItem; -         if(Pool. ContainsKey (key) && Pool[key]. Count >0) -         { theStack list =Pool[key]; -GetItem = list. Pop () asGameobject; -Getitem.setactive (true); -GetItem.transform.position =position; +GetItem.transform.rotation =rotation; -         } +         Else A         { atGetItem = Instantiate (Resources.load (prefabname), position, rotation) asGameobject; -         } -Getitem.getcomponent<des> (). Init ();//Initializing related states -         returnGetItem; -     } -  in      Public voidReturn (gameobject go) -     { to         stringKey =Go.name; +         if(pool. ContainsKey (key)) -         { theStack list =Pool[key]; * list. Push (go); $         }Panax Notoginseng         Else -         { thePool[key] =NewStack (); + Pool[key]. Push (go); A         } theGo.gameObject.SetActive (false); +     } -}

This script provides a way to get gameobject from the object pool and put back the gameobject, when it is necessary to get an object, it will first be judged by the name of the object, if there is already a stack of the name in the dictionary and the number of elements in the stack is greater than 0 o'clock, Pop out of the gameobject directly from within the stack

If not, or if the stack is empty, use instantiate to create a new gameobject.

Then a specific application, put a script fire on the camera to achieve the launch of the Bullets

1  Public classFire:monobehaviour {2     voidUpdate () {3         if(Input.getbuttondown ("Fire1")) {4Gameobject o = objectpoolmag._instance. Get ("Cube", Transform.position, quaternion.identity);5O.getcomponent<rigidbody> (). Addforce (0,0, -);6         }7     }8}

Finally, a des script is added to the cube's presets to control the cube's disappearance.
Ctrip is used here to make the cube disappear after 5 seconds.

1  Public classDes:monobehaviour {2      Public voidInit () {3 Startcoroutine (Returntopool ());4     }5 6 IEnumerator Returntopool () {7         yield return Newwaitforseconds (5f);8Objectpoolmag._instance. Return ( This. Gameobject);9     }Ten}

This is done by using the object pool to re-use the bullets for launch, and only the preset names are different, and any presets can be thrown into the pool.

Implementation of object pooling in Unity3d

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.