코딩의 신 16

김동관·2025년 10월 21일
post-thumbnail

오늘 한 일

오늘은 한게 없어서 간단하게 코드 몇개 보여드리겠습니다.
public void RemoveItem(Item item, int count = 1)
{
    var existing = items.FirstOrDefault(i => i.Name == item.Name);
    if (existing != null)
    {
        existing.Count -= count;
        if (existing.Count <= 0)
            items.Remove(existing);
    }
}
public bool TryRemoveItem(string itemName, int count = 1)
{
    var existing = items.FirstOrDefault(i => i.Name == itemName);
    if (existing != null && existing.Count >= count)
    {
        existing.Count -= count;
        if (existing.Count <= 0)
            items.Remove(existing);
        return true;
    }
    return false;
}
| 메서드명            | 인자 형태       | 반환값        | 용도                 | 사용 예시                     |
| --------------- | ----------- | ---------- | ------------------ | ------------------------- |
| `RemoveItem`    | `Item` 객체   | 없음(`void`) | 단순히 제거             | `RemoveItem(item, 1);`    |
| `TryRemoveItem` | `string` 이름 | `bool`     | 안전하게 제거 (존재/수량 체크) | `TryRemoveItem("빨간 포션");` |
//간단하게 설명 드리겠습니다.

remove로 아이템을 제거 해도 되지만, tryremoveitem을 더 만들어 안전하게 제거를 할 수 있게 만듭니다.

만약을 위해 remove에서 아이템이 제거거 되지 않았다면 tryremove로 넘어가 더 실행을 해서 확실히 안전하게 제거가 됩니다. 
큰 게임을 만들수록 더 유용하게 쓸 수 있겠죠!

profile
아이디어 뱅크

0개의 댓글