LoginSignup
9
12

More than 5 years have passed since last update.

[デザインパターン] Object pooling

Last updated at Posted at 2016-06-26

はじめに: Object poolingって何?

Object pooling の目的は複数のオブジェクトを作成と破壊することを防ぐ
作成したオブジェクトを削除しないで、再利用します。

なぜObject pollingにしますか

Objectを作成することと削除することはつまりメモリを割り当てること(allocate memory)とメモリを割り当て取り消すことだ(deallocate memory)。
このような動作を複数実行したら、パフォーマンスは遅くになります。
削除するかわりに、再利用します。

Object pollingを実装

デザインパターン

  1. ローディングステートにいくつかObjectをリストで作成する
  2. Objectを使いたいときに、新しいObjectを作らないで、作成したリストからObjectを取得する
  3. Objectを使わない(Disable)ときに、Objectを削除しないで、Disableステートをアサインして、リストにプッシュする。
  4. リストが空でしたばあいは、新しいObjectを作成して、リストにプッシュする。 poolinh.png

実装

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class ObjectPoller : MonoBehaviour {

    //singleton
 //   public static ObjectPoller poller;
    public GameObject pollObject;
    public int polledAmount = 20 ;
    public List<GameObject> pollList;
    public bool isAllowIncrease =true;

    void Awake() {
       // poller = this;
    }
    // Use this for initialization
    void Start () {
        pollList = new List<GameObject>();
        //setting for pollList object
        for (int i = 0; i < polledAmount; i++) {
            GameObject gameObject = (GameObject)Instantiate(pollObject);
            gameObject.SetActive(false);
            pollList.Add(gameObject);
        }
    }

    public GameObject getPollObject() {
        for (int i = 0; i < pollList.Count; i++) {
            if (!pollList[i].activeInHierarchy) {
                pollList[i].SetActive(true);
                Debug.Log(i);
                return pollList[i];
            }
        }
        if (isAllowIncrease) {
            GameObject gameObject = (GameObject)Instantiate(pollObject);
            pollList.Add(gameObject);
            return gameObject;
        }
        return null;
    }
}
9
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
12