ShovelingLife
A Game Programmer
ShovelingLife
전체 방문자
오늘
어제
  • 분류 전체보기 (1067)
    • 그래픽스 (57)
      • 공통 (19)
      • 수학 물리 (22)
      • OpenGL & Vulkan (1)
      • DirectX (14)
    • 게임엔진 (180)
      • Unreal (69)
      • Unity (100)
      • Cocos2D-X (3)
      • 개인 플젝 (8)
    • 코딩테스트 (221)
      • 공통 (7)
      • 프로그래머스 (22)
      • 백준 (162)
      • LeetCode (19)
      • HackerRank (2)
      • 코딩테스트 알고리즘 (8)
    • CS (235)
      • 공통 (21)
      • 네트워크 (44)
      • OS & 하드웨어 (55)
      • 자료구조 & 알고리즘 (98)
      • 디자인패턴 (6)
      • UML (4)
      • 데이터베이스 (7)
    • 프로그래밍 언어 (346)
      • C++ (167)
      • C# (88)
      • Java (9)
      • Python (33)
      • SQL (30)
      • JavaScript (8)
      • React (7)
    • 그 외 (9)
      • Math (5)
      • 일상 (5)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

  • Source Code 좌측 상단에 복사 버튼 추가 완료
  • 언리얼 엔진 C++ 빌드시간 단축 꿀팁
  • 게임 업계 코딩테스트 관련
  • 1인칭 시점으로 써내려가는 글들

인기 글

태그

  • 배열
  • 백준
  • 포인터
  • Unity
  • 함수
  • 유니티
  • C
  • 티스토리챌린지
  • 알고리즘
  • 파이썬
  • 언리얼
  • 클래스
  • 문자열
  • string
  • SQL
  • 프로그래머스
  • 그래픽스
  • 오블완
  • c#
  • C++

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
ShovelingLife

A Game Programmer

[Unity] 게임 오브젝트 컴포넌트 패턴 (GameObject) C# 구현
게임엔진/Unity

[Unity] 게임 오브젝트 컴포넌트 패턴 (GameObject) C# 구현

2022. 8. 15. 22:35

아래는 간단하게 구현해본 컴포넌트 패턴이다, gameObject라는 매개체 즉 자기 자신을 통해 해당 오브젝트가 존재하는지 확인 및 추가 기능.

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    public class GameObject
    {
        // 컴포넌트 리스트
        public List<Type> lstComp = new List<Type>();

        public T GetComponent<T>() where T : Component
        {
            // 리스트가 해당 오브젝트를 가지고 있을 시
            if (lstComp.Contains(typeof(T)))
            {
                Type type = lstComp[lstComp.IndexOf(typeof(T))];
                T comp = null;

                if      (type == typeof(AComponent))
                         comp = new AComponent() as T;

                else if (type == typeof(BComponent))
                         comp = new BComponent() as T;

                return comp;
            }
            return null;
        }

        // 해당 컴포넌트를 T로 받아 추가
        public void AddComponent<T>() where T : Component
        {
            Console.WriteLine("Added");
            lstComp.Add(typeof(T));
        }
    }


    public class Monobehaviour
    {
        public GameObject gameObject = new GameObject();
    }

    public class Component
    {
        public virtual void Print()
        {

        }
    }

    public class AComponent : Component
    {
        public override void Print()
        {
            Console.WriteLine("AComponent");
        }
    }

    public class BComponent : Component
    {
        public override void Print()
        {
            Console.WriteLine("BComponent");
        }
    }

    public class Test : Monobehaviour
    {
        void Run()
        {
            // AComponent는 추가를 안했으므로 null
            AComponent AComp = gameObject.GetComponent<AComponent>();

            if (AComp != null)
                AComp.Print();

            // BComponent 추가 후 출력
            gameObject.AddComponent<BComponent>();
            BComponent BComp = gameObject.GetComponent<BComponent>();

            if (BComp != null)
                BComp.Print();
        }

        static void Main()
        {
            // 테스트
            Test test = new Test(); 
            test.Run();
        }
    }
}
저작자표시 (새창열림)

'게임엔진 > Unity' 카테고리의 다른 글

[Unity] 프리팹 (Prefab)  (0) 2022.08.18
[Unity] EventSystem을 이용해 아이템UI 드래그 및 다른 슬롯에 등록하기(IDragHandler, IDropHandler)  (0) 2022.08.16
[Unity] / [SerializeField] [HideInInspector] [Serializable] 어트리뷰트 인스펙터 공개/비공개  (0) 2022.08.13
[Unity] Debug 클래스 (에디터 출력용)  (0) 2022.08.08
[Unity] 스크립트 파일  (0) 2022.08.07
    '게임엔진/Unity' 카테고리의 다른 글
    • [Unity] 프리팹 (Prefab)
    • [Unity] EventSystem을 이용해 아이템UI 드래그 및 다른 슬롯에 등록하기(IDragHandler, IDropHandler)
    • [Unity] / [SerializeField] [HideInInspector] [Serializable] 어트리뷰트 인스펙터 공개/비공개
    • [Unity] Debug 클래스 (에디터 출력용)
    ShovelingLife
    ShovelingLife
    Main skill stack => Unity C# / Unreal C++ Studying Front / BackEnd, Java Python

    티스토리툴바