Видеоруководство:
Объединение объектов
В иерархии у меня есть два пустых объекта GameObject, один из которых называется Object Pooler, seocnd с именем Cube Spawner.
В Object Pooler прикреплено имя скрипта ObjectPooler:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPooler : MonoBehaviour
{
[System.Serializable]
public class Pool
{
public string tag;
public GameObject prefab;
public int size;
}
#region Singleton
public static ObjectPooler Instance;
private void Awake()
{
Instance = this;
}
#endregion
public List<Pool> pools;
public Dictionary<string, Queue<GameObject>> poolDictionary;
// Start is called before the first frame update
void Start()
{
poolDictionary = new Dictionary<string, Queue<GameObject>>();
foreach(Pool pool in pools)
{
Queue<GameObject> objectPool = new Queue<GameObject>();
for(int i = 0; i < pool.size; i++)
{
GameObject obj = Instantiate(pool.prefab);
obj.SetActive(false);
objectPool.Enqueue(obj);
}
poolDictionary.Add(pool.tag, objectPool);
}
}
public GameObject SpawnFromPool(string tag, Vector3 position, Quaternion rotation)
{
if(!poolDictionary.ContainsKey(tag))
{
Debug.LogWarning("Pool with tag " + tag + " doesn't exist.");
return null;
}
GameObject objectToSpawn = poolDictionary[tag].Dequeue();
objectToSpawn.SetActive(true);
objectToSpawn.transform.position = position;
objectToSpawn.transform.rotation = rotation;
IPooledObject pooledObj = objectToSpawn.GetComponent<IPooledObject>();
if(pooledObj != null)
{
pooledObj.OnObjectSpawn();
}
poolDictionary[tag].Enqueue(objectToSpawn);
return objectToSpawn;
}
}
На Caw Spawner прикреплено имя скрипта CubeSpawner:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CubeSpawner : MonoBehaviour
{
ObjectPooler objectPooler;
// Start is called before the first frame update
void Start()
{
objectPooler = ObjectPooler.Instance;
}
private void FixedUpdate()
{
objectPooler.SpawnFromPool("Cube", transform.position, Quaternion.identity);
}
}
И у меня есть префаб Cube с компонентом Rigidbodyи имя сценария Cube:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Cube : MonoBehaviour , IPooledObject
{
public float upForce = 1f;
public float sideForce = .1f;
// Start is called before the first frame update
public void OnObjectSpawn()
{
float xForce = Random.Range(-sideForce, sideForce);
float yForce = Random.Range(upForce / 2f, upForce);
float zForce = Random.Range(-sideForce, sideForce);
Vector3 force = new Vector3(xForce, yForce, zForce);
GetComponent<Rigidbody>().velocity = force;
}
}
В обучающем видео эффект появления объектов выглядит следующим образом:

И это тот эффект, когда я запускаю игру в своем редакторе:

Rigidbody на кубе Prefab Я только что прикрепил его как естьЯ не изменил ни одного из его значений.