카테고리 없음

20250418 TIL Unity 인스펙터 직렬화 문제

note4973 2025. 4. 18. 20:18
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;

public enum TileType
{
    empty = 0,
    ground,
    wall,
    door,
    secretWall,
}

public enum EnvironmentType
{
    none = 0,
    swamp,
    lava,
    grease,
    water,
}



[System.Serializable]
public class Tile
{
    public Vector2Int gridPosition;
    public TileType tileType;
    public EnvironmentType environmentType;
    public bool isDoorPoint;

    public int MoveCost => CalculateMoveCost();
    public int AstarCost => CalculateAstarCost();
    public bool IsWalkable => CalculateIsWalkable();
    public bool isOccupied;
    public bool canSeeThrough = true;

    public bool isExplored;//향후 옵저버패턴 적용 이는 화면 표시방식에 적용 될예정이며 실제 entity의 시야와는 별개로 이용
    public bool isOnSight;
    public CharacterStats characterStats;
    //위에 올라간 mapObject 인스턴스

    private int CalculateMoveCost()
    {
        int cost = environmentType switch
        {
            EnvironmentType.swamp => 2,
            EnvironmentType.lava => 2,
            EnvironmentType.grease => 1,
            EnvironmentType.water => 1,
            _ => 1
        };

        return cost;
    }

    private int CalculateAstarCost()
    {
        int cost = environmentType switch
        {
            EnvironmentType.swamp => 6,
            EnvironmentType.lava => 6,
            EnvironmentType.grease => 2,
            EnvironmentType.water => 1,
            _ => 1
        };

        return cost;
    }

    private bool CalculateIsWalkable()
    {
        bool isWalkable = tileType switch
        {
            TileType.wall => false,
            TileType.secretWall => false,
            TileType.ground => !isOccupied,
            TileType.door => !isOccupied,
            TileType.empty => false,
            _ => false
        };

        return isWalkable;
    }

}

 

현재 Tile 클래스는 Serializable 속성을 부여된 상태이다

그렇다면 Tile tile 과같은 변수는 nullable로 null값을 가질수 있다.

그러나 이러한 변수를 public 또는 Serialized 로 지정한다면 Unity에서 자동으로 new Tile 인스턴스를 생성하여 Inspector 창에 직렬화 하여 보여주게 된다.

 

따라서 이러한 경우 tile 은 null 값을 실질적으로 가질수 없게 된다

 

해결책 1

tile을 프로퍼티로 구현하여 private _tile 과 public Tile로 구성하여 getter와 setter를 통해 접근하게 된다면 public 이면서 null 값을 가질수 있게 된다 다만 이러한 경우 inspector 창에 tile을 직렬화 하여 보여줄순 없게된다.

 

해결책2

bool 값을 추가하여 isTileNull을 설정해주어 접근시 bool 값을 체크하여 null값을 내주거나 현재 타일 정보를 반환하는 형식으로 구성한다 이렇게 구성할 경우 inspector 창에 시각화가 가능하며 tile은 null 값을 가지진 않지만 실질적으로 null 값처럼 이용이 가능하게 된다.