LoginSignup
0
0

More than 3 years have passed since last update.

[Unity] ObjectPool

Last updated at Posted at 2019-10-29

はじめに

個人メモのため限定共有公開ダヨ。
Unityでの、オブジェクトプールと簡単な使い方のみ。(2019/07/15)
UniRx使ってるヨ。

コード

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

public class ObjectPool
{
    private GameObject obj;         // 生成元のオブジェクト
    private int objNum;             // 生成する数
    private GameObject[] objs;      // オブジェクトプール配列

    public ObjectPool(GameObject obj, int objNum, bool instantiate = true)
    {
        this.obj = obj;
        this.objNum = objNum;

        objs = new GameObject[objNum];
        if (instantiate) Init();
    }

    public void Init()
    {
        var objParent = new GameObject(obj.name).transform;
        for (int i = 0; i < objNum; i++)
        {
            objs[i] = Object.Instantiate(obj) as GameObject;
            objs[i].name = obj.name + i;
            objs[i].transform.parent = objParent;
            objs[i].SetActive(false);
        }
    }

    private int stateIndex = 0;

    public void SetActive(Vector3 position)
    {
        if (objs[stateIndex].activeSelf)
        {
            var addObjs = Object.Instantiate(obj);
            addObjs.transform.position = position;
            Observable.Timer(System.TimeSpan.FromSeconds(10)).Subscribe(_ => Object.Destroy(addObjs));
        }
        else
        {
            objs[stateIndex].SetActive(true);
            objs[stateIndex].transform.position = position;
            Observable.Timer(System.TimeSpan.FromSeconds(10)).Subscribe(_ => objs[stateIndex].SetActive(false));    // 一定時間後にアクティブファルス - オブジェクト側で捜査したほうがいい
            RoundRobin();
        }
    }

    public void RoundRobin()
    {
        stateIndex = stateIndex < objNum-1 ? stateIndex+1 : 0;
    }
}

使うとき

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

public class ObjectPool_Test : MonoBehaviour
{
    public GameObject obj;
    private ObjectPool objPool;

    void Start()
    {

        objPool = new ObjectPool(obj, 100);             // 生成
        objPool.SetActive(new Vector3(0f, 10f, 0f));    // 使用
    }
}

おわりに

とりあえず作ったものなので要改良。

ゲームオブジェクトにアタッチしてないので、MonoBehaviour使うのなら、改造してね。
追記:最初限定公開で個人メモにしてたのでいろいろ雑

0
0
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
0
0