Skip to content

Instantly share code, notes, and snippets.

@hecres
Last active July 6, 2019 06:17
Show Gist options
  • Select an option

  • Save hecres/641b064c8ad91eaeaafd3d8310a74e8e to your computer and use it in GitHub Desktop.

Select an option

Save hecres/641b064c8ad91eaeaafd3d8310a74e8e to your computer and use it in GitHub Desktop.
20190706_1_2.cs
using System;
using System.Linq;
using HutongGames.PlayMaker;
using HutongGames.PlayMaker.Actions;
using UniRx;
using UniRx.Triggers;
using UnityEngine;
using Zenject;
public class FsmInjector : MonoBehaviour
{
[SerializeField] private string readyEventName = "zenjectReady";
[Inject]
// ReSharper disable once UnusedMember.Local
private void Injects(DiContainer container)
{
var rootGameObjects = gameObject.scene.GetRootGameObjects();
var targets = rootGameObjects
.Select(item => item.GetComponentsInChildren<PlayMakerFSM>())
.SelectMany(value => value)
.ToArray();
var targetFsmList = targets.Select(item => item.Fsm).ToArray();
var disposable = new SingleAssignmentDisposable();
disposable.Disposable = this.UpdateAsObservable()
.Subscribe(_ =>
{
if (targetFsmList.Any(item => !item.Initialized))
{
return;
}
foreach (var fsm in targetFsmList)
{
Inject(container, fsm);
}
foreach (var target in targets)
{
target.SendEvent(readyEventName);
}
disposable.Dispose();
});
}
private void Inject(DiContainer container, Fsm fsm)
{
if (container == null) throw new ArgumentNullException(nameof(container));
if (fsm == null) throw new ArgumentNullException(nameof(fsm));
foreach (var fsmState in fsm.States)
{
foreach (var action in fsmState.Actions)
{
container.Inject(action);
if (action is RunFSM runFsm)
{
Inject(container, runFsm.fsmTemplateControl.RunFsm);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment