Unity/C# 문법

[유니티] 데이터 은닉(캡슐화)+생성자

Skull Crusher 2021. 4. 27. 11:53
728x90

1. 데이터 은닉

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

public class ItemInfo
{
    private string name;
    private int price;
    private int damage;
    private int type;

    public void SetItemInfo(string name, int damage, int price, int type)
    {
        this.name = name;
        this.damage = damage;
        this.price = price;
        this.type = type;
    }

    public void PrintInfo()
    {
        Debug.Log("아이템 이름 >>>" + name);
        Debug.Log("아이템 데미지 >>>" + damage);
        Debug.Log("아이템 가격 >>>" + price);
        Debug.Log("아이템 종류 >>>" + type);
    }
}
public class CSharpContruct : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        ItemInfo item = new ItemInfo();

        item.SetItemInfo("불타는검", 100, 10000, 1);
        item.PrintInfo();

    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

2. 생성자 사용

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

public class ItemInfo
{
    private string name;
    private int price;
    private int damage;
    private int type;

    public ItemInfo(string name, int damage, int price, int type)
    {
        SetItemInfo(name, damage, price, type);
    }

    //데이터 캡슐
    public void SetItemInfo(string name, int damage, int price, int type)
    {
        this.name = name;
        this.damage = damage;
        this.price = price;
        this.type = type;
    }

    public void PrintInfo()
    {
        Debug.Log("아이템 이름 >>>" + name);
        Debug.Log("아이템 데미지 >>>" + damage);
        Debug.Log("아이템 가격 >>>" + price);
        Debug.Log("아이템 종류 >>>" + type);
    }
}
public class CSharpContruct : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        ItemInfo item = new ItemInfo("불타는검", 100, 10000,1);

        item.PrintInfo();

    }

    // Update is called once per frame
    void Update()
    {
        
    }
}