Unity 강의 정리 5-5장: C# 프로그래밍 [중급] (1/2) : Static🎮

나무·2023년 8월 30일
1

Unity

목록 보기
14/21
post-thumbnail

인프런에 있는 레트로의 유니티 C# 게임 프로그래밍 에센스 강의를 듣고 정리하는 글입니다!

static의 활용과 기능 📚


1. Static 변수의 사용 🔍

다음은 Dog 클래스의 기본 형태이다. 이 클래스에는 nickNameweight라는 멤버 변수와, Bark라는 메서드가 존재한다.

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

public class Dog : MonoBehaviour
{
    public string nickName;
    public float weight;

    public void Bark()
    {
        Debug.Log(nickName + ": Bark");
    }
}

2. 일반 변수를 이용한 개체 수 계산 📊

다음 코드는 객체가 생성될 때마다 count 변수를 1씩 증가시켜 전체 객체의 수를 계산하도록 한다. 이를 위해 Awake() 함수 내에서 개체 수를 증가시킨다.

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

public class Dog : MonoBehaviour
{
    public string nickName;
    public float weight;

    public int count = 0;

    void Awake()
    {
        count = count + 1;
    }

    void Start()
    {
        Bark();
    }

    public void Bark()
    {
        Debug.Log("모든 개들의 수 : " + count);
        Debug.Log(nickName + ": Bark");
    }
}

3. Static 변수로 개체 수 계산 🔄

count 변수를 static으로 선언하면, 모든 Dog 인스턴스에서 이 변수를 공유하게 된다. 이를 통해 전체 개체 수를 정확하게 파악할 수 있다.

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

public class Dog : MonoBehaviour
{
    public string nickName;
    public float weight;

    public static int count = 0;

    void Awake()
    {
        count = count + 1;
    }

    void Start()
    {
        Bark();
    }

    public void Bark()
    {
        Debug.Log("모든 개들의 수 : " + count);
        Debug.Log(nickName + ": Bark");
    }
}

4. Static 함수 사용 🛠️

static 함수는 클래스 레벨에서 호출할 수 있는 함수이다. 다음 예시에서는 ShowAnimalType이라는 static 함수를 추가하였다.

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

public class Dog : MonoBehaviour
{
    public string nickName;
    public float weight;

    public static int count = 0;

    void Awake()
    {
        count = count + 1;
    }

    void Start()
    {
        Bark();
    }

    public void Bark()
    {
        Debug.Log("모든 개들의 수 : " + count);
        Debug.Log(nickName + ": Bark");
    }

    public static void ShowAnimalType()
    {
        Debug.Log("이 친구는 개입니다.");
    }
}

이 함수는 다른 클래스에서도 호출할 수 있다. 예를 들어, Test 클래스에서 Dog 클래스의 static 변수와 함수를 직접 호출한다.

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

public class Test : MonoBehaviour
{
    void Start()
    {
        Debug.Log("모든 개들의 수 : " + Dog.count);
        Dog.ShowAnimalType();
    }
}

정리 📝

이 글에서는 Unity와 C#을 활용하여 static 변수와 함수의 사용법을 소개하였다. static 키워드를 이용하면 클래스 레벨에서 데이터를 공유하거나 함수를 호출할 수 있다.

profile
개인 공부를 정리함니다

0개의 댓글