2025.04.09 - [Unity] - [TIL] Unity 최종프로젝트 몬스터 AI 구현하기(FSM)_ 2일차
[TIL] Unity 최종프로젝트 몬스터 AI 구현하기(FSM)_ 2일차
2025.04.08 - [Unity] - [TIL] 최종프로젝트 몬스터 AI 구현하기_ 1일차 [TIL] Unity 최종프로젝트 몬스터 AI 구현하기_ 1일차최종프로젝트에서 내가 맡은 역할은 바로 플레이어를 공격하고 추격하는 몬스터
unihee1.tistory.com
1. 개요
이전에 올린 게시글을 보면 MonsterController 스크립트를 볼 수 있다.
void Start()
{
if (monsterData == null)
return;
nav = GetComponent<NavMeshAgent>();
rigid = GetComponent<Rigidbody>();
animator = GetComponent<Animator>();
target = GameObject.FindWithTag("Test")?.transform;
nav.speed = monsterData.monsterRunSpeed;
stateMachine = new StateMachine();
stateMachine.ChangeState(new IdleState(this, stateMachine));
}
위의 코드와 같이 target을 FindWithTag를 통해 Tag가 Test인 오브젝트를 가져오는 것을 볼 수 있다.
FindWithTag를 쓰게 되면 씬의 모든 객체를 확인하기 때문에 성능적으로 비효율적이다. 따라서 사용을 지양해야 한다.
오늘은 FindWithTag를 쓰지 않고 Player의 trasform을 가져올 수 있도록 수정해볼 것이다.
2. NameSpace 사용하기
using UnityEngine;
namespace MonsterTarget
{
public class PlayerObject
{
public static GameObject playerObject;
}
}
MonsterTarget 네임스페이스 내에 PlayerObject 클래스를 정의하고 그 안에 playerObject라는 GameObject 타입의 정적 변수를 선언하여 클래스의 모든 인스턴스가 동일한 playerObject를 공유하게 한다.
- PlayerController 스트립트
private void Awake()
{
playerInput = GetComponent<PlayerInput>();
if (playerInput != null)
{
var playerActionMap = playerInput.actions.FindActionMap("Player");
if (playerActionMap != null)
{
inventoryAction = playerActionMap.FindAction("Inventory");
craftingAction = playerActionMap.FindAction("Crafting");
}
}
PlayerObject.playerObject = this.gameObject;
rigidbody = GetComponent<Rigidbody>();
combat = GetComponent<PlayerCombat>();
condition = GetComponent<PlayerCondition>();
}
Using문으로 MonsterTarget에 접근한 후 Awake에서 playerObject에 현재 gameObject를 등록해준다.
- MonsterController 스크립트
rivate void Start()
{
nav = GetComponent<NavMeshAgent>();
rigid = GetComponent<Rigidbody>();
animator = GetComponent<Animator>();
hpUI = GetComponentInChildren<MonsterHPUI>();
target = PlayerObject.playerObject.transform;
if (Data != null)
{
nav.speed = Data.monsterRunSpeed;
}
}
PlayerObject.playerObject를 통해 플레이어 오브젝트를 찾고 그 Transform을 target으로 저장한다.
'Unity' 카테고리의 다른 글
[TIL] Unity 최종프로젝트 자료구조를 활용한 오브젝트풀링 구현_2 (2) | 2025.04.30 |
---|---|
[TIL] Unity 최종프로젝트 자료구조를 활용한 오브젝트풀링 구현 (1) | 2025.04.29 |
[TIL] Unity 머티리얼 깨짐 현상 해결 (Render PipeLine convert) (1) | 2025.04.25 |
[TIL] Unity 최종프로젝트 몬스터 트러블 슈팅 (1) | 2025.04.24 |
[TIL] Unity 애니메이션 컨트롤러(Animation Controller) (1) | 2025.04.23 |