본문 바로가기

TIL

23.11.14

ScriptableObject : 플레이어 위치 찾기

몬스터가 플레이어를 추적하는 기능을 만들 때 플레이어의 위치를 찾기위해서 Find 메소드를 사용하거나 GameManager같은 매니저가 플레이어를 미리 참조하고 있고 그걸 받아올 수 있지만, ScriptableObject를 사용하여 위치를 찾을수 있다.

 

PlayerPosition.cs

플레이어의 위치를 필드로 가지는 ScriptableObject이다.

using UnityEngine;

[CreateAssetMenu(fmenuName = "PlayerPosition")]
public class PlayerPosition : ScriptableObject
{
	public Vector3 position { get; set; }
}

 

 

Player.cs

플레이어 스크립트에 SerializeField로 만들어둔 PlayerPosition을 넣어 놓고, Update문에서 플레이어의 위치를 계속 수정해준다.

using UnityEngine;

public class Player : MonoBehaviour
{
	[field: SerializeField] private PlayerPosition _pp;
    
    ...
    ...
    
    private void Update()
    {
    	_pp.position = position;
    	...
    }
    
    ...
    ...
}

 

Monster.cs

몬스터 스크립트에서도 SerializeField로 만들어둔 PlayerPosition을 넣어 놓고, 플레이어를 추적할 때 PlayerPosition에서 _position을 가져와서 사용한다.

using UnityEngine;

public class Monster : MonoBehaviour
{
	[field: SerializeField] private PlayerPosition _target;
    ...
    ...
    
    private void Update()
    {
    	...
        Chase(_target.position);
    }
}

'TIL' 카테고리의 다른 글

23.11.16  (0) 2023.11.17
23.11.15  (0) 2023.11.16
23.11.13  (0) 2023.11.13
23.11.10  (0) 2023.11.13
23.11.09  (0) 2023.11.13