waygeek

PrefabFactory

Mar 6th, 2024 (edited)
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.06 KB | Gaming | 0 0
  1. using Zenject;
  2. using UnityEngine;
  3.  
  4. // Наша фабрика
  5.     public interface IPrefabFactory
  6.     {
  7.         T Create<T>(T prefabInstance) where T : Component;
  8.     }
  9.  
  10.     public class PrefabFactory : IPrefabFactory
  11.     {
  12.         private readonly IInstantiator _instantiator;
  13.  
  14.         public PrefabFactory(IInstantiator instantiator)
  15.         {
  16.             _instantiator = instantiator;
  17.         }
  18.         public T Create<T>(T prefabInstance) where T : Component
  19.         {
  20.             // Перевірка, чи параметр не є null
  21.             if (prefabInstance == null)
  22.             {
  23.                 throw new ArgumentNullException(nameof(prefabInstance), "Provided prefab instance is null.");
  24.             }
  25.  
  26.             // Спроба створення та ін'єкції залежностей
  27.             try
  28.             {
  29.                 T component = _instantiator.InstantiatePrefabForComponent<T>(prefabInstance.gameObject);
  30.  
  31.                 if (component != null)
  32.                 {
  33.                     return component;
  34.                 }
  35.  
  36.                 // Якщо не вдалося повернути компонент
  37.                 throw new InvalidOperationException("Injection failed for the component.");
  38.             }
  39.             catch (Exception ex)
  40.             {
  41.                 // Логування або обробка специфічних випадків виключень
  42.                 throw new Exception("An error occurred during the creation process.", ex);
  43.             }
  44.         }
  45.     }
  46.  
  47. // Додаємо залежності
  48. public class FactoryInstaller : MonoInstaller
  49. {
  50.     public override void InstallBindings()
  51.     {
  52.         Container.BindInterfacesAndSelfTo<PrefabFactory>()
  53.             .AsSingle();
  54.     }
  55. }
  56.  
  57. // Користуємося
  58. public class YourClassNeedingPrefab
  59. {
  60.     [Inject]
  61.     private PrefabFactory _prefabFactory;
  62.  
  63.     public void CreatePrefabInstance()
  64.     {
  65.         var prefabComponent = _prefabFactory.Create(prefab);
  66.         // Use prefabComponent as needed
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment