Scriptable Object Instances


유니티에서 스크립터블 오브젝트를 통해 게임내의 필요한 것들을 관리할 수 있다.

위의 Scriptable_Skill은 아래와 같이 구성되어 있다.

 

using UnityEngine;

[CreateAssetMenu(fileName = "Scriptable_Skill", order = 1004)]
public class Scriptable_Skill : ScriptableObject
{
    public Skill skill;
    public Sprite sprite;
    public float hitPower;
    public float sensorDistance;
    public float sensorRadius;
}

CreateAssetMenu 를 해당 파일을 생성할 수 있게 만들 수 있다.

생성되는 파일명, 보여질 순서이다. (order를 생략하면 Folder 윗쪽으로 생기게 된다.)

프로젝트 뷰에서 마우스 오른쪽 클릭 후 스크립터블 오브젝트 생성이 가능하다.

 

충분히 편리하지만 이미지가 너무 작다는 것이 아쉽기에

인터넷 검색을 해보았고 결국 찾아냈다. 원하는 결과물은 다음과 같다.

 

Sprite = Source Image 와 같다.

 

새로운 스크립트를 작성해주어 Scriptable_Skill에 대한 에디터를 정의해주어야 된다. 최종적으로

2개의 스크립트를 작성해준다.

using UnityEngine;

[CreateAssetMenu(fileName = "Scriptable_Skill", order = 1004)]
public class Scriptable_Skill : ScriptableObject
{
    public Skill skill;
    public float hitPower;
    public float sensorDistance;
    public float sensorRadius;
    public Sprite sprite;
}
using UnityEngine;
using UnityEditor; //Editor 상속 받기위해 써줌

[CustomEditor(typeof(Scriptable_Skill))] //해당 타입에 대해 적용을 해준다. (반드시 써줘야됨)
public class Scriptable_SkillEditor : Editor //에디터를 상속 받는다. OnInspectorGUI 재정의 가능
{
    private Scriptable_Skill scriptable_Skill;
    private Sprite sprite;
    private GUILayoutOption[] options;

    private void OnEnable()
    {
        //GUI 옵션 설정. 크기를 위해 설정해줌
        options = new GUILayoutOption[] { GUILayout.Width(128), GUILayout.Height(128) };
        
        //Editor에선 serializedObject 를 통해 해당 스크립트에 접근이 가능하다.
        //serializedObject.target의 형 변환을 통해 해당 값에 접근이 가능해진다.
        scriptable_Skill = serializedObject.targetObject as Scriptable_Skill;
        
        //기존 sprite를 기본으로 해줌.
        sprite = scriptable_Skill.sprite;
    }

    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        EditorGUILayout.BeginHorizontal(); //줄 맞춤을 위해 설정
        
        GUILayout.Label("Source Image"); //라벨 설정. 이 후 값들이 오른쪽으로 정렬 된다.
        //EditorGUILayout.PrefixLabel("Source Image"); //라벨 설정. 왼쪽으로 정렬 된다.
        
        //EditorGUILayout.ObjectField 를 통해 이미지를 보이게 할 수 있다.
        //(Object, type, allowSceneObject (수정 가능 여부), options)
        EditorGUILayout.ObjectField(sprite, typeof(Sprite), false, options);
        
        EditorGUILayout.EndHorizontal();  //줄 마무리
    }
}

 

 

+ Recent posts