概要
前回の続きです。
実装する点としては、敵オブジェクトが経路の終点に到達すると消えるようにします。
以下gifアニメの様な挙動を実現します。
次
開発環境
IDE:Rider
Unity:2020.3.42(LTS)
OS:Windows10
実装のポイント
EnemyrクラスのUpdateメソッドで終点か判断する
↓
ObjectPoolerクラスのReturnEnemyToPoolメソッドでオブジェクトを非表示する実行する
↓
オブジェクトは非表示になる。
コード部分
Enemy.cs
using System;
using UnityEngine;
public class Enemy : MonoBehaviour
{
[SerializeField] private float moveSpeed = 3f;
[SerializeField] private Waypoint waypoint;
public Vector3 CurrentPointPosition => waypoint.GetWaypointPosition(_currentWaypointIndex);
private int _currentWaypointIndex;
private void Start()
{
_currentWaypointIndex = 0;
}
private void Update()
{
Move();
if (CurrentPointPositionReached())
{
+ UpdateCurrentPointIndex();
}
}
private void Move()
{
Vector3 currentPosition = waypoint.GetWaypointPosition(_currentWaypointIndex);
transform.position = Vector3.MoveTowards(transform.position, currentPosition, moveSpeed * Time.deltaTime);
}
private bool CurrentPointPositionReached()
{
return Vector3.Distance(transform.position, CurrentPointPosition) < 0.1f;
}
+ private void UpdateCurrentPointIndex()
+ {
+ int lastWaypointIndex = waypoint.Points.Length - 1;
+ if (_currentWaypointIndex < lastWaypointIndex)
+ {
+ _currentWaypointIndex++;
+ }
+ else
+ {
+ ReturnEnemyToPool();
+
+ }
+ }
+ private void ReturnEnemyToPool()
+ {
+ ObjectPooler.ReturnToPool(gameObject);
+ }
}
ObjectPooler.cs
using System.Collections.Generic;
using UnityEngine;
public class ObjectPooler : MonoBehaviour
{
[SerializeField] private GameObject prefab;
[SerializeField] private int poolSize;
private List<GameObject> _pool;
private GameObject _poolContainer;
private void Awake()
{
_pool = new List<GameObject>();
_poolContainer = new GameObject($"Pool - {prefab.name}");
CreatePooler();
}
private void CreatePooler()
{
for (int i = 0; i < poolSize; i++)
{
_pool.Add(CreateInstance());
}
}
private GameObject CreateInstance()
{
GameObject newInstance = Instantiate(prefab);
newInstance.transform.SetParent(_poolContainer.transform);
newInstance.SetActive(false);
return newInstance;
}
//
public GameObject GetInstanceFromPool()
{
for (int i = 0; i < _pool.Count; i++)
{
if (!_pool[i].activeInHierarchy)
{
return _pool[i];
}
}
// poolの数がいっぱいの場合は空のGameObjectを返す。
return CreateInstance();
}
+ public static void ReturnToPool(GameObject instance)
+ {
+ instance.SetActive(false);
+ }
}
参考
gameobject アタッチされているコンポーネントを指す。
gameobject.setActive(false)
Section4 14
github コミット分
章まとめ