Unity에서 미리 정의된 Component는 GameObject의 Inspector의 Add Component를 클릭하면 추가할 수 있다.
미리 정의된 Component는 Collider(충돌 처리), Audio Source(사운드 출력), Animation(애니메이션 관리) 등이 있다.
해당 Component들의 자세한 기능은 차후 다뤄보도록 하겠다.
Component 만들기
혹은 C# Script를 사용하여 Component를 제작할 수 있다.
다음은 물체를 크기를 변형하여 두근 두근 하게 보이는 PunchScale Component를 제작해 보자.
해당 Component는 Max와 Min 크기 값을 정하는 Initialize와 크기를 변환하는 ScaleUpdate로 구성되어 있다.
이때 크기의 변화는 Vector3.Lerp을 사용하였다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PunchScale : MonoBehaviour
{
private Transform _transform;
private Vector3 _maxSize;
private Vector3 _minSize;
private float _t;
private float _speed;
private int _status;
public void Initialize()
{
_transform = this.gameObject.transform;
var scale = _transform.localScale;
_status = 0;
_speed = 1;
_maxSize = new Vector3(
scale.x * 2.0f,
scale.y * 2.0f,
scale.z * 2.0f);
_minSize = scale;
}
public void ScaleUpdate()
{
_t += Time.deltaTime * _speed;
if (_status == 0)
{
_transform.localScale = Vector3.Lerp(_transform.localScale, _maxSize, _t);
if (_transform.localScale.Equals(_maxSize))
{
_status = 1;
_t = 0;
Debug.Log(System.DateTime.Now);
}
}
else
{
_transform.localScale = Vector3.Lerp(_transform.localScale, _minSize, _t);
if (_transform.localScale.Equals(_minSize))
{
_status = 0;
_t = 0;
Debug.Log(System.DateTime.Now);
}
}
}
}
GetComponent
다음으로 해당 component를 실행할 BehaviorManager 클래스를 작성해 보자.
현재 Cube라는 GameObject에 BehaviorManager와 PunchScale 모두 붙어있는 상황이다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BehaviorManager : MonoBehaviour
{
private PunchScale punchScale;
// Start is called before the first frame update
void Start()
{
punchScale = this.gameObject.GetComponent<PunchScale>();
punchScale.Initialize();
}
// Update is called once per frame
void Update()
{
if(punchScale != null)
{
punchScale.ScaleUpdate();
}
}
}