Unity 스크립터블 오브젝트

littleDev·2024년 5월 22일

Unity

목록 보기
1/7
post-thumbnail
  1. Scriptable Object Script
using UnityEngine;

namespace DefaultNamespace
{
    // 생성되는 파일 이름, Asset/Create/Scriptable Object/에 표시될 이름, 몇번째 위치에서 표시할지
    [CreateAssetMenu(fileName = "Zombie Data", menuName = "Scriptable Object/Zombie Data", order = int.MaxValue)]
    public class ZombieData : ScriptableObject
    {
        [SerializeField] private string zombieName;
        // 외부에서 참조할때 이용하는 변수 선언방법
        public string ZombieName
        {
            get { return zombieName; }
        }
        [SerializeField] private int hp;
        public int Hp
        {
            get { return hp; }
        }
        [SerializeField] private int damage;
        public int Damage
        {
            get { return damage; }
        }
        [SerializeField] private float sightRange;
        public float SightRange
        {
            get { return sightRange; }
        }
        [SerializeField] private float moveSpeed;
        public float MoveSpeed
        {
            get { return moveSpeed; }
        }
    }
}

scriptable object를 asset으로 생성하는 방법 : Assets/Create/Scriptable Objects/"본인이 설정한 menu name"

여러개를 생성한 결과 :

  1. Scriptable Object 활용 스크립트
using System.Collections;
using System.Collections.Generic;
using DefaultNamespace;
using UnityEngine;

public enum ZombieType
{
    Normal = 0,
    Power,
    Sensitive, 
    Speedy,
    Tanker,
}

public class ZombieSpawner : MonoBehaviour
{
    [SerializeField] private List<ZombieData> zombieData;
    [SerializeField] private GameObject zombiePrefab;
    void Start()
    {
        for (int i = 0; i < zombieData.Count; i++)
        {
            Zombie zombie = SpawnZombie((ZombieType)i);
            zombie.PrintZombieData();
        }
    }
    public Zombie SpawnZombie(ZombieType type)
    {
        Zombie newZombie = Instantiate(zombiePrefab).GetComponent<Zombie>();
        newZombie.zombieData = zombieData[(int)type];
        newZombie.name = newZombie.zombieData.ZombieName;
        return newZombie;
    }
}

아, zombiePrefab에 넣을 프리팹은 미리 만들어둬야한다.

3. Scriptable Object print용 스크립트

using System.Collections;
using System.Collections.Generic;
using DefaultNamespace;
using UnityEngine;

public class Zombie : MonoBehaviour
{
    public ZombieData zombieData;

    public void PrintZombieData()
    {
        Debug.Log("좀비 이름 : " + zombieData.ZombieName);
        Debug.Log("좀비 체력 : " + zombieData.Hp);
        Debug.Log("좀비 공격력 : " + zombieData.Damage);
        Debug.Log("좀비 시야 : " + zombieData.SightRange);
        Debug.Log("좀비 이동속도 : " + zombieData.MoveSpeed);
        Debug.Log("------------------------------------------------");
    }
}

실행 전

실행 후

단점 :스크립터블 오브젝트가 애셋 형태로 게임 폴더에 저장되기 때문에, 플레이어가 직접 수정할 수 있다. 따라서 싱글 플레이일 경우에는 상관 없지만, 멀티플레이 환경에는 적합하지 않으며, 중요한 데이터는 스크립터블 오브젝트를 사용하지 않는게 좋다.

profile
매일 성장하고싶은 개발자

0개의 댓글