Unity 기본10 - class 만들기

1. class 만들기

 

scripts에 character.cs c# 스크립트를 만든다

 

project 창에서 우클릭 - create - c# script하면 만들 수 있다

 

 

 

 

 

 

character.cs 더블클릭해서 visual studio를 연다

 

Character이름 옆에 MonoBehaviour 제거하고

 

void start, void update 모두 제거해서 class 틀만 남긴다

 

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

public class Character
{

}

 

 

클래스 이름, 함수 이름은 대문자로 시작하고 변수 이름은 소문자로 시작하는 것을 관습으로 하고 있다

 

캐릭터의 이름과 체력을 속성으로 가지고, 맞거나 힐받았을때 체력변화, 살아있는지 체크하는 메소드를 작성

 

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

public class Character
{
    string names;
    int hp;

    public Character(string characterName, int initialHP)
    {
        names = characterName;
        hp = initialHP;

    }

    public void Hit(int damage)
    {
        hp -= damage;
    }

    public void Heal(int heal)
    {
        hp += heal;
    }

    public bool isAlive()
    {
        return hp > 0;
    }
}

 

 

 

저장한 다음 HelloWorld.cs에 들어가서, 이렇게 만든 class를 사용한다

 

그냥 Character (이름) = new Character(이름, 체력); 이렇게 쓰면 된다

 

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

public class HelloWorld : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Character daehyuck = new Character("대혁", 100);
    }

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

 

 

메소드는 daehyuck.Hit, daehyuck.Heal... 이런식으로 사용할 수 있다

 

데미지를 주고, 힐을 하고, 살아있는지 검사하고, 다시 데미지를 주고..

 

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

public class HelloWorld : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Character daehyuck = new Character("대혁", 100);

        daehyuck.Hit(90);
        daehyuck.Heal(20);

        Debug.Log("살아있나?" + daehyuck.isAlive());

        daehyuck.Hit(200);

        Debug.Log("살아있나?" + daehyuck.isAlive());
    }

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

 

 

 

 

 

 

 

 

2. 객체지향 프로그래밍

 

프로그래밍 방법론중 하나

 

"이 세상은 객체로 이루어져 있고, 객체 간의 상호작용을 잘 표현하면 된다"

 

객체를 중심으로 프로그래밍하는 것을 객체지향 프로그래밍

 

예를 들어 게임은 캐릭터가 있고, 캐릭터가 사용하는 기술, 아이템, 아군 캐릭터, 적군 캐릭터,...  이런 것들이 객체이고

 

이러한 객체들은 자신들의 특성을 가지고 있고, 각 객체는 또 할 수 있는 일들이 있다.

 

이런 객체의 형태를 정의하는 것을, "class를 만든다"라고 표현

 

"Character"라는 것은 어떤 것인지 정의하고 만드는 것이 class

 

class는 객체를 정의하는 방법이고, 객체를 찍어내는 틀

 

 

3. 코드 분석

 

캐릭터는 이름, 체력이 있다

 

구조체 struct랑 비슷하게

 

 

 

class가 정의되는데

 

public class Character
{
    string names;
    int hp;
}

 

 

struct는 데이터를 모아둔 것이지만

 

class는 데이터뿐만 아니라, 할 수 있는 일도 정의함

 

character은 맞기, 힐, 살아있는지 체크 등의 기능도 가지고 있다

 

public class Character
{
    string names;
    int hp;

    public Character(string characterName, int initialHP)
    {
        names = characterName;
        hp = initialHP;

    }

    public void Hit(int damage)
    {
        hp -= damage;
    }

    public void Heal(int heal)
    {
        hp += heal;
    }

    public bool isAlive()
    {
        return hp > 0;
    }
}

 

 

class가 가지고 있는 데이터 names, hp를 멤버변수, 속성, property, attribute라고 부른다

 

class가 할 수 있는 일들 Hit, Heal, isAlive를 method라고 부른다

 

함수가 class의 일부일 때 method라고 부른다

 

이렇게 객체를 찍어내는 틀 class를 정의하면 실제로 사용해서 객체를 만들어야하는데

 

이렇게 실제 객체를 만들어낸 것을 instance라고 부른다

 

Character daehyuck = new Character("대혁", 100);

 

 

character이라는 class 틀을 이용해 "대혁"이라는 객체를 찍어낸 것

 

class에는 특수한 method가 하나 있는데

 

public class Character
{
    string names;
    int hp;

    public Character(string characterName, int initialHP)
    {
        names = characterName;
        hp = initialHP;

    }

 

 

Hit, Heal, isAlive같은 함수는 void, bool같이 return 타입을 명시하고 있는데 Character이라는 이 method는 return 타입이 없다

 

그리고 class 이름인 Character이랑 동일하다

 

class이름과 같고 return 타입이 없는 이 method는 instance를 만들때 처음 실행되는 method

 

new Character("대혁", 100);할때, public Character(string characterName, int initialHP)이 실행된다.

 

instance를 생성할 때 실행된다고 해서 생성자라고 부른다

 

--------------------------------------------------------------------------------------------------------------------------------------------------------

 

 

4. 새로운 클래스 만들기

 

project - scripts 폴더 내에서 Food.cs 생성

 

음식 이름과, 먹으면 회복되는 hp양을 정의

 

instance 생성하면 실행되는 생성자도 정의

 

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

public class Food
{
    public string name;
    public int hp;

    public Food(string _name, int _hp)
    {
        name = _name;
        hp = _hp;
    }

}

 

 

음식을 먹으면 실제로 회복되어야한다.

 

캐릭터가 음식을 먹으므로, 캐릭터 class에서 음식을 먹는 method를 정의

 

Food class의 food를 받고, isAlive()로 살아있다면, 음식의 hp 회복양만큼 회복

 

    public void Eat(Food food)
    {
        if (isAlive())
        {
            hp += food.hp;
        }
    }

 

 

피자라는 음식을 정의하고, 이제 강하게 맞기 전에 피자를 먹는다

 

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

public class HelloWorld : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Character daehyuck = new Character("대혁", 100);
        Food pizza = new Food("피자", 300);

        daehyuck.Hit(90);
        daehyuck.Heal(20);

        Debug.Log("살아있나?" + daehyuck.isAlive());

        daehyuck.Eat(pizza);
        daehyuck.Hit(200);

        Debug.Log("살아있나?" + daehyuck.isAlive());
    }

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

 

 

TAGS.

Comments