0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[C#メモ] 動的に登録

Last updated at Posted at 2020-05-07
using UnityEngine;
using System;

namespace Core
{
    public class GameEntity : MonoBehaviour
    {
        private string TypeName => $"Core.GameDataStore`1[{GetType()}]";
        private Type Type => Type.GetType(TypeName);
        private object Store => Activator.CreateInstance(Type);

        private void Awake()
        {
            RegistToStore();
        }

        private void OnDestroy()
        {
            UnRegistFromStore();
        }

        private void RegistToStore()
        {
            ExecuteStoreMethod("Regist");
        }

        private void UnRegistFromStore()
        {
            ExecuteStoreMethod("UnRegist");
        }

        private void ExecuteStoreMethod(string methodName)
        {
            var method = Type.GetMethod(methodName, new Type[] { GetType() });
            method.Invoke(Store, new object[] { this });
        }
    }
}

using System.Collections.Generic;

namespace Core
{
    public class GameDataStore<T>
    {
        private static readonly List<T> items = new List<T>();
        public IReadOnlyList<T> Items => items;

        public void Regist(T item)
        {
            items.Add(item);
        }

        public void UnRegist(T item)
        {
            items.Remove(item);
        }
    }
}

気をつけること。
typeNameは本来namespaceも必要。
GetType().NameSpaceで取得できる。
動的に呼び出すメソッドはpublicでなければならない。

目的。
GameEntityを継承したクラスが自動で自クラスをGameDataStoreに登録するようにしたかった。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?