Search Unity

Components communication, UnityEvents

Discussion in 'Scripting' started by artooretc, Jul 30, 2019.

  1. artooretc

    artooretc

    Joined:
    May 2, 2019
    Posts:
    7
    Is it possible, to handle all components/controllers communication by using ScriptableObject Events?
    In this code example I managed creating unique, object specific individual events, for indicidual object's components to react on them.
    Is this a good approach?
    The point is having individual OnDeath/Moved/SkillUsed etc. Events, and listebers on each object, with responses from this exact object's components (like Health(ondamaged, but only for this object), this object's ui controller to draw healthbar.with new value etc.)

    Code (CSharp):
    1. Public class
    2. CharacterController: Monobehaviour
    3. {
    4.      [SerializeField]
    5.      GameEvent OnPlayerMoved
    6.      void Start()
    7.  {
    8. OnPlayerMoved=ScriptableObject.CreateInstance<GameEvent>();
    9.  OnPlayerMoved.name="On"+this.name+"Moved";
    10. EventsManager.stringEventDictionary.Add(OnPlayerMoved, OnPlayerMoved.name);
    11.      }
    12. }
    Code (CSharp):
    1. Public class GameEventListener: Monobehaviour
    2. {
    3.     GameEvent Event;
    4.     [SerializeField]
    5.     UnityEvent Response;
    6.     void OnEnable()
    7.     {
    8.         Event=EventsManager.stringEventDict["On"+this.name+"Moved";
    9.     }
    10.     void OnEventRaised()
    11.     {
    12.           Response.Invoke();
    13.     }
    14. }
    Code (CSharp):
    1. Public class GameEvent: ScriptableObject
    2. {
    3.      List<GameEventListener> listeners=new...;
    4.      public void Raise()
    5.      {
    6.            Foreach listener
    7.                listener.OnEventRaised();
    8.      }
    9. }
     
    Last edited: Jul 30, 2019
  2. artooretc

    artooretc

    Joined:
    May 2, 2019
    Posts:
    7
    My main point is - example with ScriptableObjects doesn't cover having individual ScriptableObject variables, like Hp, etc, for tracking. It covers only PlayerHp and referencing to it. How would I have each object having it's own HP instance, and for each component of this GameObj - referencing only it's own instance.