직렬화와 스크립터블 오브젝트
스크립터블 오브젝트는 유니티 에셋으로 데이터를 저장시키고 필요할 때 꺼내서 쓰는 기능이다.
데이터와 코드를 분리하기 위한 유용한 기능이다.
using UnityEngine;
using UnityEngine.InputSystem;
public class CubeSpawner : MonoBehaviour
{
public GameObject cubePrefab; // 하나의 프리팹만 사용
void Update()
{
if (Keyboard.current.qKey.IsPressed())
{
GameObject newCube = Instantiate(cubePrefab, Vector3.zero, Quaternion.identity);
newCube.transform.localScale = new Vector3(3, 3, 3); // 큰 큐브
}
else if (Keyboard.current.wKey.IsPressed())
{
GameObject newCube = Instantiate(cubePrefab, Vector3.zero, Quaternion.identity);
newCube.transform.localScale = new Vector3(2, 2, 2); // 중간 크기 큐브
}
else if (Keyboard.current.eKey.IsPressed())
{
GameObject newCube = Instantiate(cubePrefab, Vector3.zero, Quaternion.identity);
newCube.transform.localScale = new Vector3(1, 1, 1); // 작은 큐브
}
}
}
Update() 안에서 매 프레임마다 키보드를 체크하고:
- Q 키 누름 → 3x3x3 크기의 큐브 생성
- W 키 누름 → 2x2x2 크기의 큐브 생성
- E 키 누름 → 1x1x1 크기의 큐브 생성
위 코드의 문제점
IsPressed()는 키를 누르고 있는 동안 계속 true라서
키를 ‘누르는 내내’ 계속 생성됨.
즉 Q키를 누른 순간 → 0.01초~0.02초마다 큐브가 무한 생성됨
이런 단점을 해결해줄 스크립터블 오브젝트를 사용해보자
using UnityEngine;
[CreateAssetMenu(fileName = "CubeData", menuName = "Scriptable Objects/CubeData")]
public class CubeData : ScriptableObject
{
public string cubeName;
public Vector3 scale;
}

코드로 제어하기
using UnityEngine;
public class SOSpawner : MonoBehaviour
{
public CubeData[] mySO;
private void Start()
{
transform.localScale = mySO[0].scale;
}
}'📖TIL' 카테고리의 다른 글
| 251114 (0) | 2025.11.14 |
|---|---|
| 251113 NavMesh (0) | 2025.11.13 |
| 251113 CSV & JSON (0) | 2025.11.13 |
| 251113 (0) | 2025.11.13 |
| 내가 이해한 오브젝트 풀링 개념 (0) | 2025.11.12 |