<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Vector focus</title>
    <description>The latest articles on DEV Community by Vector focus (@vectorfocus).</description>
    <link>https://dev.to/vectorfocus</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1279253%2F4c8e96e7-59e1-427b-9c2a-88dd65f50ee3.png</url>
      <title>DEV Community: Vector focus</title>
      <link>https://dev.to/vectorfocus</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/vectorfocus"/>
    <language>en</language>
    <item>
      <title>A quick way to use ObjectPooling in Unity</title>
      <dc:creator>Vector focus</dc:creator>
      <pubDate>Mon, 12 Feb 2024 18:09:14 +0000</pubDate>
      <link>https://dev.to/vectorfocus/a-quick-way-to-use-objectpooling-in-unity-4l6h</link>
      <guid>https://dev.to/vectorfocus/a-quick-way-to-use-objectpooling-in-unity-4l6h</guid>
      <description>&lt;p&gt;In Unity, pooling is an essential method for reusing gameObjects.&lt;br&gt;
This breaks the infernal loop of infinite destruction/creation.&lt;/p&gt;

&lt;p&gt;The principle of object pooling is that, instead of destroying a gameObject, we deactivate it and put it in its initial state so that we can &lt;strong&gt;reuse&lt;/strong&gt; it later.&lt;/p&gt;

&lt;p&gt;For example, in a shooter, each explosion could be a gameObject that we &lt;strong&gt;recycle&lt;/strong&gt;.&lt;/p&gt;
&lt;h2&gt;
  
  
  How to use it on Unity.
&lt;/h2&gt;

&lt;p&gt;Since version 2021, Unity has had a specific method for managing &lt;strong&gt;gameObject pooling&lt;/strong&gt;: &lt;a href="https://docs.unity3d.com/ScriptReference/Pool.ObjectPool_1.html"&gt;ObjectPool&lt;/a&gt;.&lt;br&gt;
This very efficient method has 7 parameters, see below for a real example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using UnityEngine.Pool;

public class RocketManager : MonoBehaviour
{
    // prefab
    public Rocket prefabRocket;

    public ObjectPool&amp;lt;Rocket&amp;gt; PoolRocket { get; set; }

    public void Awake()
    {   
        PoolRocket = new ObjectPool&amp;lt;Rocket&amp;gt;(OnCreate, OnTake, OnReturn, OnDestroy, false, 10, 20);
    }

    private void OnCreate()
    {

    }

    private void OnTake(Rocket rocket)
    {

    }

    private void OnReturn(Rocket rocket)
    {

    }

    private void OnDestroy(Rocket rocket)
    {

    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It's true that these parameters are optional except for the first one, but this can quickly become very complicated for the readability of your code.&lt;br&gt;
Especially if 80% of the time your actions (the first 4 parameters) do the same thing all the time. &lt;/p&gt;

&lt;p&gt;A good starting point would be to create a service that allows us to avoid this &lt;strong&gt;repetition&lt;/strong&gt;.&lt;/p&gt;
&lt;h2&gt;
  
  
  The quick-to-use version
&lt;/h2&gt;

&lt;p&gt;In my case, I use pooling 90% of the time on gameObjects with &lt;strong&gt;their own Monobehaviour&lt;/strong&gt;.&lt;br&gt;
The service will work even if your gameObject doesn't have a custom Monobehaviour, you'll just have less control over the configuration.  &lt;/p&gt;

&lt;p&gt;To start we'll create an IRelease interface, which will have an implementable method for adding an action when the gameObject returns to the pool.&lt;br&gt;
If it's implemented, its method will allow us to &lt;strong&gt;reset our Gameobject&lt;/strong&gt; to its initial state, for example.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public interface IRelease
{
    void Release();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then, to avoid the hassle of specifying parameters for each new gameObject we want to pool, we'll create a static C# class.&lt;/p&gt;

&lt;p&gt;In my case, most of the time the &lt;strong&gt;only parameters&lt;/strong&gt; I needed to change were the parameters for the initial and maximum number of gameObjects or the collectionCheck.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using UnityEngine;
using UnityEngine.Pool;

public static class BaseObjectPooling
{
    public static ObjectPool&amp;lt;T&amp;gt; GetDefaultPooling&amp;lt;T&amp;gt;(T prefab, int initial = 10, int max = 20, bool collectionChecks = false) where T : MonoBehaviour
    {
        return new ObjectPool&amp;lt;T&amp;gt;(() =&amp;gt; GameObject.Instantiate(prefab), (T obj) =&amp;gt; obj.gameObject.SetActive(true), OnRelease, (T obj) =&amp;gt; GameObject.Destroy(obj), collectionChecks, initial, max);
    }

    private static void OnRelease(MonoBehaviour obj)
    {
        IRelease release = obj as IRelease;

        if (release != null)
        {
            release.Release();
        }

        obj.gameObject.SetActive(false);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The code above shows that the instantiation, activation and deletion actions do nothing more than their primary actions.&lt;/p&gt;

&lt;p&gt;There's just the OnRelease method, which will call an additional method if the IRelease interface is implemented.&lt;/p&gt;

&lt;h2&gt;
  
  
  How it's used
&lt;/h2&gt;

&lt;p&gt;We're going to use another MonoBehaviour to initialise our Pool system.&lt;br&gt;
Note that I always instantiate my pools in the Awake method, and then I never use them until the Start method is called.&lt;br&gt;
This ensures that my pool is ready and avoids errors.&lt;/p&gt;

&lt;p&gt;In the example below, we're going to set up a Pool system for rockets, using a prefab as a model.&lt;br&gt;
The Rocket class is a MonoBehaviour, and we invoke 10 rockets using the pools, associating a random colour with them.&lt;br&gt;
The manager is a singleton to make the demonstration easier, but it's not compulsory.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using UnityEngine.Pool;

public class RocketManager : MonoBehaviour
{
    // prefab
    public Rocket prefabRocket;

    public ObjectPool&amp;lt;Rocket&amp;gt; PoolRocket { get; set; }

    public static RocketManager Instance { get; private set; }

    public void Awake()
    {
        Instance = this;

        PoolRocket = BaseObjectPooling.GetDefaultPooling&amp;lt;Rocket&amp;gt;(prefabRocket);
    }

    private void Start()
    {
        for (int i = 0; i &amp;lt; 10; i++)
        {
            var instance = PoolRocket.Get();
            instance.SetColor(GetRandomColor());
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this fictitious example, the rocket will have to return to its &lt;strong&gt;Pool&lt;/strong&gt; when the rocket is destroyed.&lt;br&gt;
This is illustrated by the "Explosion" method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Rocket : MonoBehaviour, IRelease
{
    public void SetColor(Color color)
    {
        // set color
    }

    public void Explosion()
    {
        // this ship is destroy, back to the pool
        RocketManager.Instance.PoolRocket.Release(this);
    }

    public void Release()
    {
        // base color
        SetColor(Color.gray);
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Well, the colours example doesn't really make sense, but it's there to show that Release can be used to reset a component.&lt;br&gt;
This is not shown in this example, but it is possible to track undestroyed objects in a list.&lt;/p&gt;

&lt;p&gt;This service isn't as functional as it could be, but it seems to me to be a &lt;strong&gt;good approach&lt;/strong&gt; to using Pools quickly.&lt;br&gt;
Feel free to customise it at home to make it more efficient =)&lt;/p&gt;

&lt;p&gt;You can find more Unity tips and tricks on my &lt;a href="https://blog.vector-focus.com"&gt;blog&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>unity3d</category>
    </item>
  </channel>
</rss>
