Skip to content

Instantly share code, notes, and snippets.

@IJEMIN
Last active February 7, 2017 11:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IJEMIN/c03e3edcc90300f4de8bbfe9fcdda9e8 to your computer and use it in GitHub Desktop.
Save IJEMIN/c03e3edcc90300f4de8bbfe9fcdda9e8 to your computer and use it in GitHub Desktop.
유니티 C# 스크립트, 클래스와 오브젝트 교육
// 이 튜토리얼 코드는, Derek Benas 의 C# 교육 코드를 유니티 스크립트 교육 맞춰 간단하게 고친것임을 밝힌다.
class Animal
{
// public : 접근 제한이 없다
// protected : 현재 클래스와 자식 클래스에서만 접근 가능
// private : 현재 클래스에서만 접근 가능
// 클래스 내부의 변수를 필드라고 부른다.
public double height;
public double weight;
public string sound;
// 바깥에서 변수에 마음대로 접근하지 않도록 접근자 메소드와 설정자 메소드를 따로 만들거나
// 프로퍼티를 사용하여 스스로 데이터를 검증하게 할 수 있다
private string name;
// 이것이 프로퍼티. 필드처럼 동작하지만, 내부에 따로 값을 반환할 때와 받아들일 때의 처리를 만들 수 있다.
public string Name
{
get { return name; }
set { name = value; }
}
// 모든 오브젝트들은 입력을 받지 않는 기본 생성자를 가지고 있다
// 생성자는 오브젝트가 생성될때 마다
// this 키워드는 현재 자신의 오브젝트의 필드 값들을 가져올때 사용된다. 왜냐면 오브젝트에 특정한 이름이 없어 스스로를 지칭할 이름이 필요하기 때문.
// 기본 생성자는, 다른 생성자들을 따로 만들어줄 경우 자동으로 만들어지지 않는다.
public Animal()
{
this.height = 0;
this.weight = 0;
this.name = "No Name";
this.sound = "No Sound";
numOfAnimals++;
}
// 커스텀 생성자도 만들어 줄수 있다
public Animal(double height, double weight, string name, string sound)
{
this.height = height;
this.weight = weight;
this.name = name;
this.sound = sound;
numOfAnimals++;
}
// static 필드는 Animal 클래스의 모든 오브젝트들이 공유한다
// static 은 클래스와 관련은 있으나, 개별 오브젝트가 가지고 있기에는 어색한 기능이나 값에 사용한다. 각각의 동물들이 자기 외의 전체 동물들의 수를 알고 있는 것은 어색하다.
static int numOfAnimals = 0;
// static 메소드는 static 이 아닌 멤버에 접근 할수 없다
public static int getNumOfAnimals()
{
return numOfAnimals;
}
// 메소드를 선언
public string Explain()
{
return String.Format("{0} 은 {1} 인치 높이고, 무게는 {2} 파운드 이며, 울음소리가 {3} 이다.", name, height, weight, sound);
}
static void Main()
{
// 동물 오브젝트를 만들며, 생성자를 통해 기본 설정을 해준다
Animal dog = new Animal(12, 10, "개", "멍멍");
Animal wolf = new Animal(17, 12, "늑대", "그르릉");
// 점 (.) 을 사용하여 오브젝트 내부의 값을 가져온다
// 개dog 오브젝트 내부의 값들을 가져와보자
Console.WriteLine("{0} 이라는 동물은 {1} 라고 운다", dog.name, dog.sound);
// 늑대wolf 오브젝트 내부의 값들을 가져와보자
Console.WriteLine("{0} 이라는 동물은 {1} 라고 운다", wolf.name, wolf.sound);
// static 메소드를 호출하여 전체 동물 수를 가져와보자
Console.WriteLine("Number of Animals " + Animal.getNumOfAnimals());
// 개별 오브젝트의 메소드를 호출해보자
Console.WriteLine(wolf.Explain());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment