이번 게시글에서는 이전 게시글에서 다루었던 ScriptableObject의 사용방법과 생성 방식에 대해서 알아보겠습니다.
사용 방법
- 데이터 컨테이너 클래스 정의 및 ScriptableObject 상속
- . asset생성 및 데이터 할당
- 데이터 활용
데이터 컨테이너 클래스 정의 및 ScriptableObject 상속
[CreateAssetMenu(menuName = "Game/Monster")]
public class Monster : ScriptableObject
{
public float speed;
public int MaxHealth;
}
소스와 같이 클래스를 정의하고, ScriptableObject를 상속합니다. 해당 에셋을 생성할 수 있게, CreateMenu를 정의하고, 이를 통해 에셋을 생성할 수 있게 선언합니다.
클래스에 정의한 속성과 동일하게, Create 메뉴의 Game/Monster를 통해 해당 Asset을 생성할 수 있습니다.
생성된 Monster Asset은 이미지와 같은 Inspector를 통해 확인이 가능하고, 데이터를 저장할 수 있습니다. 해당 데이터를 다른 스크립트에서 활용할 때는 아래와 같습니다.
public class MonsterSpawner : MonoBehaviour
{
public Monster MonsterData;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
Debug.Log(MonsterData.speed);
Debug.Log(MonsterData.MaxHealth);
}
}
이미지와 같이 Monster라는 데이터 에셋을 Spawner에서 할당하여, 데이터를 활용할 때 멤버 변수에 접근하듯이 접근하여 데이터를 활용할 수 있습니다.
Zombie를 생성과 동시에 Initialize 하여 데이터를 초기화
public class Zombie : MonoBehaviour
{
public float Speed;
public int MaxHealth;
public void Initialize(Monster monster)
{
Speed = monster.speed;
MaxHealth = monster.MaxHealth;
}
}
데이터 컨테이너에 들어가 있는 Speed와 MaxHealth를 기반으로 데이터를 초기화하고, 관리할 수 있습니다.
'Unity' 카테고리의 다른 글
ScriptableObject - 1 (0) | 2025.10.10 |
---|---|
Renderer Feature - 3(선택적 글로우/하이라이트) (1) | 2025.06.24 |
Unity_RF(Renderer Feature) - 2 (0) | 2025.05.23 |
Unity_URP RF(RendererFeature) (0) | 2025.05.12 |
Unity Git hub Acitons - 4 (Game-ci/unity-builder) (1) | 2025.03.13 |