Advertisement
Guest User

Powerup_Factory

a guest
Dec 9th, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.54 KB | None | 0 0
  1. using System.Collections.Generic;
  2. using System;
  3. using System.Reflection;
  4. using System.Linq;
  5. using UnityEngine;
  6.  
  7. public static class Powerup_Factory
  8. {
  9.     private static Dictionary<string, Type> powerupsByName;
  10.     private static bool IsInitalized => powerupsByName != null;
  11.  
  12.     private static void InitalizeFactory()
  13.     {
  14.         if (IsInitalized)
  15.             return;
  16.  
  17.         var powerupTypes = Assembly.GetAssembly(typeof(Powerup_Base)).GetTypes()
  18.             .Where(myType => !myType.IsAbstract && myType.IsSubclassOf(typeof(Powerup_Base)));
  19.  
  20.         // Dictionary for finding these by name later (could be an enum/id instead of string
  21.         powerupsByName = new Dictionary<string, Type>();
  22.  
  23.         foreach (var type in powerupTypes)
  24.         {
  25.             var tempPowerup = Activator.CreateInstance(type) as Powerup_Base;
  26.             powerupsByName.Add(tempPowerup.PowerupName, type);
  27.         }
  28.  
  29.         Debug.Log("Powerup_Factory Initalized Status: " + IsInitalized);
  30.     }
  31.  
  32.     public static Powerup_Base GetPowerup(string powerupType)
  33.     {
  34.         InitalizeFactory();
  35.  
  36.         if (powerupsByName.ContainsKey(powerupType))
  37.         {
  38.             Type type = powerupsByName[powerupType];
  39.             var powerup = Activator.CreateInstance(type) as Powerup_Base;            
  40.             return powerup;
  41.         }
  42.  
  43.         return null;
  44.     }
  45.  
  46.     internal static IEnumerable<string> GetPowerupNames()
  47.     {
  48.         UnityEngine.Debug.Log("Test");
  49.         InitalizeFactory();
  50.         return powerupsByName.Keys;
  51.     }
  52.  
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement