Attached is an example of networked object pool for UNet. It uses custom spawn handler functions and has object pools on the host and clients.
Instances of the specified “Prefab” object are created at initialization time, and then used when spawn messages are recieved, so there is no run-time object allocation and destruction.
The pooled object are controlled by the server. Example usage in a player script:
using UnityEngine;
using UnityEngine.Networking;
public class PlayerMove : NetworkBehaviour
{
public NetworkSpawnPool bulletPool;
void Start()
{
bulletPool = NetworkSpawnPool.GetPoolByName("DynamicPool");
}
//public GameObject bulletPrefab;
public override void OnStartLocalPlayer()
{
GetComponent<MeshRenderer>().material.color = Color.red;
}
[Command]
void CmdFire()
{
var bullet = bulletPool.ServerCreateFromPool(transform.position - transform.forward, Quaternion.identity);
if (bullet == null)
return;
bullet.GetComponent<Rigidbody>().velocity = -transform.forward*4;
// spawn the bullet on the clients
NetworkServer.Spawn(bullet);
bulletPool.ServerReturnToPool(bullet, 2.0f);
}
void Update()
{
if (!isLocalPlayer)
return;
var x = Input.GetAxis("Horizontal")*0.1f;
var z = Input.GetAxis("Vertical")*0.1f;
transform.Translate(x, 0, z);
if (Input.GetKeyDown(KeyCode.Space))
{
// Command function is called on the client, but invoked on the server
CmdFire();
}
}
}
Although by default it works with prefabs, there is a virtual function that can be overridden to construct objects from code, like this below:
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
public class DynamicBulletPool : NetworkSpawnPool {
protected override GameObject InstantiatePrefab(Vector3 pos, Quaternion rot)
{
var go = GameObject.CreatePrimitive(PrimitiveType.Sphere);
go.transform.localScale = new Vector3(0.2f, 0.2f, 0.2f);
go.transform.position = pos;
go.transform.rotation = rot;
var rb = go.AddComponent<Rigidbody>();
rb.useGravity = false;
go.AddComponent<NetworkIdentity>();
go.AddComponent<NetworkTransform>();
go.AddComponent<Bullet>();
return go;
}
}
Spawning with prefabs uses the assetId from the prefab, but dynamically created assetIds can be used.
The attached project shows it in use.
2391174–162910–NetworkSpawnPool.cs (4.65 KB)
2391174–162911–networkspawnpool.zip (46.2 KB)