I would like to ask if anyone has some experience in object pooling through Fusion. To sum up things im migrating from Pun2 to Fusion and need to update my object pool. My issue apart from my lack of experience is that i cant really understand the documentation.
My attempt to make it work was not successful and i think i would need to use the Acquire / Release instance methods that Photon provides but i cant really find a way to do so.
using Photon.Pun;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPool : MonoBehaviourPun
{
public GameObject objectToPool;
public int amountToPool;
private bool isInitialized = false;
private List<GameObject> pooledObjects;
public bool objectsStartHidden = true;
private void Awake()
{
pooledObjects = new List<GameObject>();
}
private void Start()
{
if (PhotonNetwork.IsMasterClient)
{
SetupPool(objectsStartHidden);
}
}
public void SetupPool(bool _hidden)
{
if (isInitialized) return;
if (PhotonNetwork.IsMasterClient)
{
for (int i = 0; i < amountToPool; i++)
{
GameObject tmp = PhotonNetwork.Instantiate(objectToPool.name, Vector3.zero, Quaternion.identity);
int viewID = tmp.GetPhotonView().ViewID;
if (_hidden)
tmp.SetActive(false);
pooledObjects.Add(tmp);
photonView.RPC("AddToPoolRPC", RpcTarget.OthersBuffered, viewID);
}
}
isInitialized = true;
}
public GameObject GetPooledObject()
{
for (int i = 0; i < amountToPool; i++)
{
if (!pooledObjects[i].activeInHierarchy)
{
return pooledObjects[i];
}
}
return null;
}
public int GetPooledObjectIndex(GameObject obj)
{
return pooledObjects.IndexOf(obj);
}
public GameObject GetPooledObject(int index)
{
if (index >= 0 && index < pooledObjects.Count)
{
return pooledObjects[index];
}
return null;
}
[PunRPC]
private void AddToPoolRPC(int viewID)
{
GameObject tmp = PhotonView.Find(viewID).gameObject;
tmp.SetActive(false);
pooledObjects.Add(tmp);
}
}
This was my previous attempt which worked as expected :
- Create a fix amount of objects
- Get one when needed
- Disable it and send it back
This is the behavior i would like to do with Fusion too and hopefully sync it across all clients as ideally only the master would spawn and all clients would take those game instances. So to sum up i have 2 questions - requests!
- Given the demos photon has (tanknarok/asteroids) i see that their way of implementing this is spawn through the network realtime and just keep it there to recycle. is this ok?? I mean its subjective and tied to the amount of items you create but yeah.
- Should the above way be ok or the pre spawning if anyone has any idea and could help i would appreciate it!
Thank you for your time!