Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using Zenject;
- using UnityEngine;
- // Наша фабрика
- public interface IPrefabFactory
- {
- T Create<T>(T prefabInstance) where T : Component;
- }
- public class PrefabFactory : IPrefabFactory
- {
- private readonly IInstantiator _instantiator;
- public PrefabFactory(IInstantiator instantiator)
- {
- _instantiator = instantiator;
- }
- public T Create<T>(T prefabInstance) where T : Component
- {
- // Перевірка, чи параметр не є null
- if (prefabInstance == null)
- {
- throw new ArgumentNullException(nameof(prefabInstance), "Provided prefab instance is null.");
- }
- // Спроба створення та ін'єкції залежностей
- try
- {
- T component = _instantiator.InstantiatePrefabForComponent<T>(prefabInstance.gameObject);
- if (component != null)
- {
- return component;
- }
- // Якщо не вдалося повернути компонент
- throw new InvalidOperationException("Injection failed for the component.");
- }
- catch (Exception ex)
- {
- // Логування або обробка специфічних випадків виключень
- throw new Exception("An error occurred during the creation process.", ex);
- }
- }
- }
- // Додаємо залежності
- public class FactoryInstaller : MonoInstaller
- {
- public override void InstallBindings()
- {
- Container.BindInterfacesAndSelfTo<PrefabFactory>()
- .AsSingle();
- }
- }
- // Користуємося
- public class YourClassNeedingPrefab
- {
- [Inject]
- private PrefabFactory _prefabFactory;
- public void CreatePrefabInstance()
- {
- var prefabComponent = _prefabFactory.Create(prefab);
- // Use prefabComponent as needed
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment