이 글은
https://www.inflearn.com/course/유니티-게임-프로그래밍-에센스
강의를 요약한 강의노트 입니다.
유니티를 처음 접하시는 분들이거나 좀 더 기반을 다지고 싶으신 분들에게 👍강력하게 추천합니다.
일반적인 클래스를 만들어 오브젝트를 생성하면
클래스의 할당된 메모리크기 * 오브젝트 수 만큼 메모리공간을 차지한다.
이때, 사용하는 것이 Static으로 Static을 사용하면 모든 오브젝트들이 공유하는 단 하나의 변수 혹은 함수를 가져 메모리 낭비를 최소화 할 수 있다.
정적 변수와 함수는 오브젝트를 거쳐 실행할 필요없이 클래스를 통해 바로 접근할 수 있다.
(접근지정자) static (자료형) (변수 혹은 함수 이름)
using System;
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");
}
}
using System;
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("이것은 개입니다.");
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
// 다른 스크립트 파일에서 클래스 이름으로 바로 변수와 함수를 불러올 수 있다.
Debug.Log("Test Dog의 총 개수: " + Dog.count);
Dog.ShowAnimalType();
}
}
Awake와 Start 모두 게임 시작전 단 한번 실행되는 함수다.
두 함수의 차이에 대해 알아보자
Awake :
1. Awake는 게임이 시작되기 전에 모든 변수와 게임의 상태를 초기화 하기위해 사용한다.
2. 모든 오브젝트가 초기화되고 호출되기 때문에 GameObject.FindWithTag를 이용해서 게임 오브젝트를 요청하거나, 다른 오브젝트와 안전하게 연동해서 사용할 수 있다.
3. Awake는 랜덤한 순서로 실행된다.
Start
1. Start는 게임이 실행되고 Update가 실행되기 전 실행되는 함수다.
2. 따라서 Start는 Awake보다 늦게 실행된다.
사용
스크립트간의 참조를 설정하기 위해 Awake를 사용하고 정보를 보내고 받는 경우에는 Start를 사용한다.
❗️출처 : https://luv-n-interest.tistory.com/764
결과 : count출력이 1, 2, 3으로 나온다.
using System;
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 Start()
{
count = count + 1;
Bark();
}
public void Bark()
{
Debug.Log("모든 개들의 수: " + count);
Debug.Log(nickName + "Bark");
}
}
결과 실행되기 전 초기화 작업을 진행하므로 Count값이 3으로 출력된다.
using System;
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");
}
}