instantiationTools.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import { Logger } from './logger';
  2. import { _TypeStore } from './typeStore';
  3. /**
  4. * Class used to enable instatition of objects by class name
  5. */
  6. export class InstantiationTools {
  7. /**
  8. * Use this object to register external classes like custom textures or material
  9. * to allow the laoders to instantiate them
  10. */
  11. public static RegisteredExternalClasses: { [key: string]: Object } = {};
  12. /**
  13. * Tries to instantiate a new object from a given class name
  14. * @param className defines the class name to instantiate
  15. * @returns the new object or null if the system was not able to do the instantiation
  16. */
  17. public static Instantiate(className: string): any {
  18. if (this.RegisteredExternalClasses && this.RegisteredExternalClasses[className]) {
  19. return this.RegisteredExternalClasses[className];
  20. }
  21. const internalClass = _TypeStore.GetClass(className);
  22. if (internalClass) {
  23. return internalClass;
  24. }
  25. Logger.Warn(className + " not found, you may have missed an import.");
  26. var arr = className.split(".");
  27. var fn: any = (window || this);
  28. for (var i = 0, len = arr.length; i < len; i++) {
  29. fn = fn[arr[i]];
  30. }
  31. if (typeof fn !== "function") {
  32. return null;
  33. }
  34. return fn;
  35. }
  36. }