091
[C#] Unity 속 C# script(3) 본문
01. Destroy() 사용하기
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ifstat_ggi : MonoBehaviour {
int hp = 20;
void OnMouseDown(){
hp -= 10;
if(hp<1){
print("사라짐");
Destroy(gameObject); //목숨 변수인 hp가 1 미만이 될 때 오브젝트가 사라지는 코드
}
}
}
- print()와 Debug.Log()는 둘다 콘솔에 메세지를 출력하는데 사용되지만 디버깅에 특화된 Debug.Log()를 사용하는 것을 권장(경고,오류, 정보 등 다양한 필터링 기능을 제공하기 때문에도 더 유용함)
- Destroy(gameObject); : 저번 글에서 설명한 GetComponent<T>와 같이 GameObject의 메서드로 파라미터(오브젝트)를 삭제하는 메서드임
02. 게임 오브젝트를 클릭 시 색상 변경 -> OnMouseDown()으로 구현하기
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ifstat_ggi : MonoBehaviour {
int count = 0;
void OnMouseDown(){
count++;
if(count % 2 == 0){ //Even
GetComponent<Renderer>().material.color = Color.yellow;
print(" Even number of clicks ");
} else { //Odd
GetComponent<Renderer>().material.color = Color.blue;
print(" Odd number of clicks ");
}
}
}
- (gameObject.)GetComponent<Renderer>().material.color = Color.yellow; : gameObject는 명시하지 않아도 스크립트가 부착된 오프젝트의 컴포넌트를 가져옴 -> rd1 = GetComponent<Rigidbody>(); 저번 게시글에 썼던 02예제도 이렇게 바꿔써도 됨. 그리고 저번 글에서 말했던 것처럼 Material 컴포넌트는 Renderer에 적용되고, material.color은 material의 color에 Color.yellow를 넣겠다는 것, Color은 유니티에서 새상을 다룰 때 사용하는 구조체임 -> Color.blue,Color.red 등 있으면 더하기 연산을 통해 색을 섞을 수도 있고 Color(R,G,B,A)처럼 쓰는 것이 원래 기본 구조임(Red,Green,Blue,Alpha(투명도)/4가지 모두 0.0~1.0 범위를 가짐)
03. 응용
-> 캡슐 사라지게하기
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ifstat_ggi : MonoBehaviour {
int count = 0;
void OnMouseDown(){
count++;
print("캡슐을 "+(count+1)+"번 클릭하셨습니다.");
if(count >= 5){
Destroy(gameObject,2); //gameObject가 2초후에 사라짐
}
}
}
- Destroy(gameObject,t); : t초 후에 사라지는 명령어
-> 공을 커지게 하기
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ifstat_ggi : MonoBehaviour {
int count = 0;
void OnMouseDown(){
count++;
if(count % 3 == 0){
transform.localScale = new Vector3(3,3,3);
print("Sphere가 원래 크기의 3배로 커짐");
} else if (count % 2 == 0){
transform.localScale = new Vector3(2,2,2);
print("Sphere가 원래 크기의 2배로 커짐");
} else {
print("Sphere가 원래 크기를 유지함");
}
}
}
- transform은 Transfom 컴포넌트를 참조하는 속성이고 Transform은 GetComponent<T>와 같이 GameObject의 메서드임, Transform의 메서드에는 position(월드 좌표계에서 오브젝트의 위치),localPosition(부모 오브젝트를 기준으로 한 위치),localScale(부모 오브젝트가 있을 때 배수, 없을 때는 스케일을 직접 설정하는 것과 같음) 등이 있음
- transform.localScale = new Vector3(3,3,3); : 위에 설명한대로 localScale은 부모 오브젝트가 있을 때와 없을 때 역할이 다르게 느껴질 수 있지만 부모 오브젝트가 없을 때는 기본값인 (1,1,1)과 Vector3(3,3,3)을 곱하기 때문에 직접 스케일을 정하는 것처럼 보일 뿐임, 부모 오브젝트가 있는 경우 부모 오브젝트의 위치값(a,a,a)와 Vector3(3,3,3)을 곱하면 실제 자식 오브젝트 = 적용되는 오브젝트의 위치값은 (3a,3a,3a)가 됨
* 일부 출처 - 고수정, ”게임프로그래밍 ”, 인덕대학교
'Programming Language > C#' 카테고리의 다른 글
[C#] Unity 속 C# script(5) : 사용자입력스크립트 (5) | 2024.12.08 |
---|---|
[C#] Unity 속 C# script(4) (8) | 2024.10.21 |
[C#] Unity 속 C# script(2) (3) | 2024.10.19 |
[C#] Unity 속 C# script(1) (4) | 2024.10.14 |
[C#] 기초문법(연산자,제어문) (4) | 2024.10.13 |