Making scriptable objects and loading resources

데이터 컨테이너

일반적으로 프로젝트의 메모리 사용량을 줄이기 위해 변경되지 않는 데이터를 저장하는 데 사용됨

→ 각 식물의 데이터를 저장하는 방법으로 사용할 예정

→ Scriptable Object: 각 식물마다 S.O를 설정하여

[CreateAssetMenu(fileName = "New Plant", menuName = "Plant")]
// create asset menu line
public class PlantObject : ScriptableObject
{
    public string   plantName;
    public Sprite[] plantStages;
    public float    timeBtwStages;
}

Asset - Plants 폴더 생성 - Create - Plant: Corn

Plant Stages: Spites - Corn0~Corn3

Time Btw Stages: 2

스크린샷 2023-09-15 185509.png

Scriptable Object 생성 → PlotManager 스크립트의 plantStages, timeBtwnStages 변수 변경

스크린샷 2023-09-15 190204.png

public class PlotManager : MonoBehaviour
{
    bool isPlanted = false;
    SpriteRenderer plant;
    BoxCollider2D plantCollider;

    // public Sprite[] plantStages; -> Plants를 Sprite가 아닌 ScriptableObject로 만듦
    int plantStage = 0;
    float timer;
    // float timeBtwnStages = 2f;  -> Plant Object 내 존재

    public PlantObject selectedPlant;

    void Start()
    {
        plant = transform.GetChild(0).GetComponent<SpriteRenderer>();
        plantCollider = transform.GetChild(0).GetComponent<BoxCollider2D>();
    }

    void Update()
    {
        if (isPlanted)
        {
            timer -= Time.deltaTime;

            // plantStage is lower than the last plant stage
            if (timer < 0 && plantStage < selectedPlant.plantStages.Length - 1)
            {
                timer = selectedPlant.timeBtwStages;
                plantStage++;
                UpdatePlant();
            }
        }
    }

    private void OnMouseDown()
    {
        if (isPlanted)
        {
            if (plantStage == selectedPlant.plantStages.Length - 1)
            {
                Harvest();
            }
        }
        else
        {
            Plant();
        }
    }

    void Harvest()
    {
        isPlanted = false;
        plant.gameObject.SetActive(false);
    }

    void Plant()
    {
        isPlanted = true;
        plantStage = 0;
        UpdatePlant();
        timer = selectedPlant.timeBtwStages;
        plant.gameObject.SetActive(true);
    }

    // update the plant apprearance
    void UpdatePlant()
    {
        plant.sprite = selectedPlant.plantStages[plantStage];
        plantCollider.size = plant.sprite.bounds.size;
        plantCollider.offset = new Vector2(0, plant.bounds.size.y / 2);
    }
}

Selected Plant: Corn