Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Reflection;
- using UnityEngine;
- namespace TankDemo.Model
- {
- /// <summary>
- /// Main basic pattern class - 'Factory'
- /// Author: Boris Kotlyar
- /// </summary>
- public static class Factory
- {
- // cached types
- private static Dictionary<string, Type> _entitiesByName;
- private static bool IsInitialized => _entitiesByName != null;
- private static void Init()
- {
- // if already initialized, just skip
- if (IsInitialized)
- return;
- // get all entities
- var entitiesTypes = Assembly.GetAssembly(typeof(Entity)).GetTypes().Where(myType =>
- myType.IsClass && !myType.IsAbstract && myType.IsSubclassOf(typeof(Entity)));
- // dictionary for finding these by name later
- _entitiesByName = new Dictionary<string, Type>();
- // get the names and put them to dictionary
- foreach (var entitiesType in entitiesTypes)
- {
- _entitiesByName.Add(entitiesType.Name, entitiesType);
- }
- }
- /// <summary>
- /// Return component from MonoBehaviour
- /// </summary>
- /// <param name="obj">MonoBehaviour</param>
- /// <param name="entityName">entity combonent based class type</param>
- /// <returns></returns>
- public static Entity GetComponentEntity(GameObject obj, string entityName)
- {
- Init();
- if (_entitiesByName.ContainsKey(entityName))
- {
- var entity = obj.AddComponent(_entitiesByName[entityName]) as Entity;
- return entity;
- }
- return null;
- }
- /// <summary>
- /// Get model entity
- /// </summary>
- /// <param name="entityName">entity class type</param>
- /// <returns></returns>
- public static Entity GetEntity(string entityName)
- {
- Init();
- if (_entitiesByName.ContainsKey(entityName))
- {
- var type = _entitiesByName[entityName];
- var entity = Activator.CreateInstance(type) as Entity;
- return entity;
- }
- return null;
- }
- /// <summary>
- /// Get all stored entities
- /// </summary>
- /// <returns></returns>
- internal static IEnumerable<string> GetNames()
- {
- Init();
- return _entitiesByName.Keys;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment