Creation of (Unity-optimized) object pools

Source: Internet
Author: User
Tags foreach

People who know a little about unity must know that instantiating objects is very cost-efficient, while destroying objects consumes a little but also affects performance, so in order to optimize, the common objects into the object pool, in the call to take out, when not in use when hidden into the object pool, so that can greatly reduce the consumption of resources.

I. Using a custom resource configuration file

Http://www.360doc.com/content/14/0323/13/12282510_363016017.shtml

Some things to know before writing the object pool, this custom resource configuration technology allows us to write the object pool more convenient to use, it can let us directly in a saved custom configuration file for the object pool operation, the runtime will automatically help us load, very convenient, Of course, we can also directly put the written object pool script on an object to make it prefab to use but obviously this is very uncomfortable and inconvenient.

There is no need to know this technology very clearly, and probably know how to use it to get started.

Two. Create a Gameobjectpool class

First we create a pool class, which should have a name, a pre-object, a maximum capacity, and a list collection to store the instantiated objects, as well as a way to fetch the objects externally.

[Serializable]
public class Gameobjectpool {public
    string name;
    [Serializefield]
    Private Gameobject prefab;
    [Serializefield]
    private int maxCount;
    [NonSerialized]
    Private list<gameobject> golist;
Public Gameobject Getinst ()
{
foreach (Gameobject item in golist)       //Traverse whether there is an idle object, if there is a return
{
if (!item.activeinhierarchy)
return item;
} if
(Golist.count>=maxcount)                //found no idle object, before creating a new object to determine whether to reach the capacity, if reached, destroy the oldest object
{
Gameobject.destroy (Golist[0]);       

Golist.removeat (0);
}
Gameobject temp = gameobject.instantiate (prefab) as Gameobject;   Creates a new object to join the collection and returns
Golist.add (temp);
return temp;
}}

Note that you must precede the class with the Serializable attribute so that the pool class can be serialized, and if you do not want to write some fields as public, you can manipulate them in the editor with Serializefield, For fields that do not need to be serialized, such as Golist saves the objects generated in the game, you do not need to operate in the configuration file to add the NonSerialized feature.

Three. Create a poollist class

Creating the Poollist class, which holds the collection of object pools, is the key to inheriting the Scriptableobject class

public class Poollist:scriptableobject {public
    list<gameobjectpool> poollist;	
}
Four. Extend the Unity Editor
[MenuItem ("Manager/create poollistconfigure")]
    static void Createpoollistconfigure ()
    {
        poollist poollist=scriptableobject.createinstance<poollist> ();
        String path= "Assets/scripts/pool/poollist.asset";
        Assetdatabase.createasset (poollist, path);
        Assetdatabase.saveassets ();
    }
Poollist is created to use the method in Scriptableobject, and finally we use the method in Assetdatabase to save the object as a asset file, the path must start the project path or it will be an error.

Five. Create a Poolmanager Management object pool


public class Poolmanager {private Poolmanager _instance;  Public Poolmanager Instance {get {if (_instance = = null) _instance = new
            Poolmanager ();
        return _instance;
    }} Private Const string poolconfigurepath = "Poollist";
    Private dictionary<string, gameobjectpool> pooldic;
        Private Poolmanager () {poollist poollist = resources.load<poollist> (Poolconfigurepath);
        Pooldic=new dictionary<string,gameobjectpool> ();
        foreach (Gameobjectpool item in poollist.poollist) {Pooldic.add (Item.name, item);
        }} public Gameobject Getinst (string poolname) {Gameobjectpool pool; if (Pooldic.trygetvalue (poolname, Out pool)) return pool.
        Getinst ();
        Debug.logwarning ("Pool:" + poolname + "is not exist!");
    return null; }
    public void Init ()
    {
    }
}
The code is simple, as a management class is generally done in a singleton mode, in the constructor to load the previous generated configuration table, using the dictionary structure to store each object pool convenient to find, provide external methods of object, the last Init () method is used to initialize, because our constructors are private, So when the outside call instance is constructed, if you call the Getinst method when the creation will cause obvious lag, so long as the game before the beginning of a call to init this empty method can be.

In fact the object pool we can continue to expand, such as the life cycle, so that some of our long-unused objects have been automatically destroyed after a period of time to save memory, and so on when needed to continue to deep research.

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.