Programming-Design-Patterns.../Assets/Patterns_And_Principles/Patterns/Object Pool Pattern/UnityObjectPool/Script/Launcher.cs

56 lines
No EOL
1.4 KiB
C#

using System;
using UnityEngine;
using UnityEngine.Pool;
namespace Patterns_And_Principles.Patterns.Object_Pool_Pattern.UnityObjectPool.Script
{
public class Launcher : MonoBehaviour
{
[SerializeField]
private Bullet bulletPrefab;
[SerializeField]
private int maxPoolSize = 10;
private IObjectPool<Bullet> _bulletPool;
private void Awake()
{
_bulletPool = new ObjectPool<Bullet>(createFunc: OnCreate, actionOnGet: OnGet, actionOnRelease: OnRelase,
actionOnDestroy: OnDestroy, maxSize: maxPoolSize);
}
private Bullet OnCreate()
{
Bullet bullet = Instantiate(bulletPrefab, transform.position, transform.rotation);
bullet.SetPool(_bulletPool);
return bullet;
}
private void OnGet(Bullet bullet)
{
bullet.gameObject.SetActive(true);
bullet.gameObject.transform.position = transform.position;
}
private void OnRelase(Bullet bullet)
{
bullet.gameObject.SetActive(false);
}
private void OnDestroy(Bullet bullet)
{
Destroy(bullet.gameObject);
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
_bulletPool.Get();
}
}
}
}