Event/Actions in Prefabs, how to listen?

Hi, Hope I can explain myself with this one.

I have a prefab that should announce itself that it was properly placed and later on destroyed. For that an Action was created that basically triggers an Event.

On the other side I have a GameStats Class which listens to this Events and, at the moment, just counts into a variable the amount of prefabs in the game.

I want to use this system to have a game wide possibility to performed some calculations based on certain amounts of prefabs.

My only problem is in the GameStat Class. I cannot suscribe to the Action in start(), because it does not exist at that moment. And puting this in Update() does not work, because the subscription is done a lot.

So I need some kind of solution. I don’t want to call the GameStat Class from the PreFab every time it is placed, because this is not the idea of the system and it should work independent of the prefabs.

Any Ideas? Experience on this?

Thx!

You want a variable that define how many instances of a ScriptType there are at any given time.
Use a static variable.

public class ScriptType: MonoBehaviour
{
      private static int count;
      public static int Count{ get{ return count;}}
      public static event Action<ScriptType> OnCreation;
      public static event Action<ScriptType> OnDestruction;
      void Start(){
            count++;
            if(OnCreation!= null){ OnCreation(this);}
     }
     void OnDestroy()
     {
            count--;
            if(OnDestruction!= null){ OnDestruction(this);}
     }
}

Now some will say, you should not use static when it is not the case", well this is actually a proper case for static. The count is about ScriptType, not about the instances. Also, if you have no instance, you can still check the count (0) without getting null reference. And finally, it keeps your ScriptType from knowing about the GameManager. It has fewer dependencies. Problem solved.

Your GameManager calls it whenever needed.You can also register to the events to be notified of a change:

public class GameManager:  MonoBehaviour{
      void Start(){
            ScriptType.OnCreation += ScriptType_OnCreation;
            ScriptType.OnDestruction += ScriptType_OnDestruction;
     }
     void ScriptType_OnCreation(ScriptType newInstance){}
     void ScriptType_OnDestruction(ScriptType destroyedInstance){}
}