Skip to content

HonkbarkStudios/UnityObjectPooler

master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Code

Latest commit

 

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
 
 

UnityObjectPooler

A generic handler for pooling game objects in unity

Friendsheep

This ObjectPooler is used in production in the game Friendsheep

Adding to your project:

  1. Download GameObjectPooler.
  2. Add Script to unity.
  3. Add an empty game object and add GameObjectPooler as a script component

How to use:

This is an examplescript of how to use the pooler. to instantiate a new game object use GameObjectPooler.Instance.GetObject(LargeCloud); then set its position and rotation. After that set the game object to active. When you don't need the object set it to inactive with this code:

largeCloud.SetActive(false);

using UnityEngine;
using System.Collections;

public class EnvironmentSpawner : MonoBehaviour {

	public GameObject LargeCloud;

	void Start () {
		StartCoroutine(SpawnLargeClouds());
	}

	IEnumerator SpawnLargeClouds() {
		yield return new WaitForSeconds(2);
		while(true) {
			var largeCloud = GameObjectPooler.Instance.GetObject(LargeCloud);
			largeCloud.transform.position = new Vector3(0.98f, 5.68f, -0f);
			largeCloud.transform.rotation = Quaternion.identity;
			largeCloud.SetActive(true);
			yield return new WaitForSeconds(2);
		}
	}
}

Preloading objects

To load one or more objects into the object pool before using GameObjectPooler.Instance.GetObject(LargeCloud); use the method PreloadGameObject(Gameobject Prefab); Do this when starting the game instead of when playing and you will avoid drops in performance because of instantiating new gameobjects

using UnityEngine;
using System.Collections;

public class EnvironmentSpawner : MonoBehaviour {

	public GameObject LargeCloud;

	void Start () {
		this.PreloadGameObjectsIntoPool();
	}

	private void PreloadGameObjectsIntoPool() {
		this.AddFiveCopiesOfGameObjectToPool(LargeCloud);
	}

	private void AddFiveCopiesOfGameObjectToPool(GameObject gameObject) {
		for(int i = 0; i < 5; i++) {
			GameObjectPooler.Instance.PreloadGameObject(gameObject);
		}
	}
}

About

A generic handler for pooling game objects in unity

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages