다음과 같은 코드가 있다. player가 HealthKitItem이나 Gold를 획득하면 Use메서드를 실행하는 코드이다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HealthKitItem : MonoBehaviour
{
public int restoreHealth = 100;
public void Use()
{
Debug.Log("체력을 회복했다!");
Player player = FindObjectOfType<Player>(); // 플레이어를 찾아
player.hp += restoreHealth; // 플레이어의 hp를 100만큼 증가시킨다.
gameObject.SetActive(false); // 헬스킷을 획득했으니 꺼준다.
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GoldItem : MonoBehaviour
{
public int goldAmount = 100;
public void Use()
{
Debug.Log("골드를 얻었다!");
Player player = FindObjectOfType<Player>(); // 플레이어를 찾아
player.gold += goldAmount; // 플레이어의 골드를 100만큼 증가시킨다.
gameObject.SetActive(false); // 골드 아이템을 획득했으니 꺼준다.
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public float hp = 50;
public int gold = 1000;
private Rigidbody2D m_rigidbody;
private float speed = 3f;
private float jumpSpeed = 5f;
void Start()
{
m_rigidbody = GetComponent<Rigidbody2D>();
}
void Update()
{
Vector2 currentVelocity = m_rigidbody.velocity;
float horizontal = Input.GetAxis("Horizontal");
currentVelocity.x = horizontal * speed;
if (Input.GetButtonDown("Jump"))
{
currentVelocity.y = jumpSpeed;
}
m_rigidbody.velocity = currentVelocity;
}
void OnTriggerEnter2D(Collider2D other)
{
GoldItem goldItem = other.GetComponent<GoldItem>();
if(goldItem != null)
{
goldItem.Use();
}
HealthKitItem healthKitItem = other.GetComponent<HealthKitItem>();
if(healthKitItem != null)
{
healthKitItem.Use();
}
}
}
정상적으로 실행이 잘 되지만 OnTriggerEnter2D부분에 불필요하게 GetComponent를 많이 호출하여 성능 저하를 일으킨다. 하지만 인터페이스를 활용하면 해당 아이템을 먹을때 한번만 호출하게 하여 성능을 향상시킬 수 있다.
public interface IItem
{
void Use();
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HealthKitItem : MonoBehaviour, IItem
{
public int restoreHealth = 100;
public void Use()
{
Debug.Log("체력을 회복했다!");
Player player = FindObjectOfType<Player>(); // 플레이어를 찾아
player.hp += restoreHealth; // 플레이어의 hp를 100만큼 증가시킨다.
gameObject.SetActive(false); // 헬스킷을 획득했으니 꺼준다.
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GoldItem : MonoBehaviour, IItem
{
public int goldAmount = 100;
public void Use()
{
Debug.Log("골드를 얻었다!");
Player player = FindObjectOfType<Player>(); // 플레이어를 찾아
player.gold += goldAmount; // 플레이어의 골드를 100만큼 증가시킨다.
gameObject.SetActive(false); // 골드 아이템을 획득했으니 꺼준다.
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public float hp = 50;
public int gold = 1000;
private Rigidbody2D m_rigidbody;
private float speed = 3f;
private float jumpSpeed = 5f;
void Start()
{
m_rigidbody = GetComponent<Rigidbody2D>();
}
void Update()
{
Vector2 currentVelocity = m_rigidbody.velocity;
float horizontal = Input.GetAxis("Horizontal");
currentVelocity.x = horizontal * speed;
if (Input.GetButtonDown("Jump"))
{
currentVelocity.y = jumpSpeed;
}
m_rigidbody.velocity = currentVelocity;
}
void OnTriggerEnter2D(Collider2D other)
{
IItem item = other.GetComponent<IItem>();
if (item != null)
{
item.Use();
}
}
}
이렇게 GetComponent를 한번만 호출할 수 있다.
참고 블로그
'C#_ Unity Game programming' 카테고리의 다른 글
Unity-Instantiate할 때 Canvas의 자식으로 넣는법 (1) | 2024.01.13 |
---|---|
Unity, UI제작시 프리팹 및 풀링 고려(가비지 문제) (0) | 2024.01.12 |
Unity, MVC와 MVP패턴의 차이점 및 실습 코드 (0) | 2024.01.05 |
Unity, Scriptable Object개념 (1) | 2024.01.04 |
C# 인터페이스와 추상클래스 공통점과 차이점 (2) | 2024.01.02 |