오늘의 트러블 슈팅
오늘은 트러블 슈팅 위주로 알려드리겠습니다.
using UnityEngine;
public class PlayerAttack : MonoBehaviour
public PlayerCondition playerCondition;
public float staminaCost = 10f;
public float attackDamage = 10f;
public float attackRange = 3f;
public LayerMask targetLayer;
// 몬스터 레이어 넣기
private Animator animator;
private void Awake()
{ if (playerCondition == null)
playerCondition = GetComponent<PlayerCondition>();
animator = GetComponent<Animator>();
if (animator == null)
Debug.LogWarning("Animator가 없습니다!"); }
public void TryAttack()
{ if (playerCondition == null) {
Debug.LogWarning("PlayerCondition이 연결되어 있지 않습니다!"); return; }
// 스태미나 체크
if (!playerCondition.UseStamina(staminaCost)) { Debug.Log("스태미나 부족으로 공격 불가");
animator.ResetTrigger("Attack"); return; }
animator.SetTrigger("Attack");
// 플레이어 앞 방향으로 Ray 발사 Ray ray = new Ray(transform.position + Vector3.up, transform.forward);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, attackRange, targetLayer))
{ IDamagable monster = hit.collider.GetComponent<IDamagable>();
if (monster != null) { monster.TakePhysicalDamage(attackDamage); Debug.Log("몬스터 타격!"); } } }
public class Structure : MonoBehaviour
public StructureData data; private int accumulatedDamage = 0;
public GameObject prefab;
//private Vector3 pos;
//private Quaternion rot;
private void Start()
{ pos = transform.position; rot = transform.rotation; }
//public void Gather(Vector3 hitPoint, Vector3 hitNormal, int damageAmount)
{ data.hp -= damageAmount; //hp accumulatedDamage += damageAmount; //
while (accumulatedDamage >= data.damagePer) { for (int i = 0; i < data.dropAmount; i++)
// {Instantiate(data.dropItem, hitPoint + Vector3.up, Quaternion.LookRotation(hitNormal, Vector3.up)); }
accumulatedDamage -= data.damagePer;
//data.dropCount--; // if (data.dropCount <= 0)
{ Destroy(gameObject); // StartCoroutine(Regen()); } } }
private IEnumerator Regen()
{ yield return new WaitForSeconds(30f); Instantiate(prefab,pos,rot); } }
수정 전 코드입니다.
몬스터는 IDamagable 인터페이스로 데미지를 받고,
나무(Structure)는 IDamagable을 구현하지 않아서 PlayerAttack이 때려도 데미지가 안 들어가는 구조
즉,
PlayerAttack → IDamagable만 공격 가능
나무는 Structure 클래스만 있고 IDamagable이 아님 → 공격 안 됨
IDamagable을 추가해서 데미지를 받게 해도 되겠지만,
만약코드가 꼬이게 된다면 Monster도 수정해야 하는 다른 문제가 또 발생할 수 있음.
그래서 선택한 Gatherable 인터페이스 따로 만들기.
1) Gather 전용 인터페이스 만들기
public interface IGatherable
{
void Gather(Vector3 hitPoint, Vector3 hitNormal, int damage);
}
2) Structure가 IGatherable 구현하도록 수정
public class Structure : MonoBehaviour, IGatherable
{
public void Gather(Vector3 hitPoint, Vector3 hitNormal, int damage)
{
// 나무/돌 맞았을 때 처리
}
}
3)PlayerGather는 IGatherable만 찾으면 됨
IGatherable target = hit.collider.GetComponent<IGatherable>();
if (target != null)
{
target.Gather(hit.point, hit.normal, damage);
}
이로인해 나무나 돌 자원들 Struture는 IGatherable 인터페이스로 해결.
배운 내용: 팀원과의 소통은 중요. 인터페이스의 중요도. 팀업을 하게 되면 소통이 매우 중요하다고 느낌.