Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question How can I let my prefab listen to event?

Discussion in 'Scripting' started by levoxtrip, Jul 26, 2023.

  1. levoxtrip

    levoxtrip

    Joined:
    May 4, 2020
    Posts:
    45
    I have a prefab and want it to listen to events. My problem is the prefab also needs to be deactivated in the beginning.

    Is there a way to let the prefab still listen to events that happen in the game?
     
  2. tomfulghum

    tomfulghum

    Joined:
    May 8, 2017
    Posts:
    69
    You could leave the prefab enabled, subscribe to the event in
    Awake
    and immediately disable the object.
     
  3. dlorre

    dlorre

    Joined:
    Apr 12, 2020
    Posts:
    700
    Let the GameController or a PrefabController handle this. If more than one prefab should listen then make a List<GameObject> and let them register to it.

    Code (csharp):
    1.  
    2.     public class GameController : MonoBehaviour
    3.     {
    4.         public static GameController Instance { get; set; }
    5.         private List<GameObject> prefabs;
    6.         private void Awake()
    7.         {
    8.             prefabs = new();
    9.             if (Instance == null)
    10.             {
    11.                 Instance = this;
    12.             }
    13.         }
    14.         public void RegisterPrefab(GameObject prefab)
    15.         {
    16.               prefabs.Add(prefab);
    17.         }
    18.     }
    19.  
    20.  
    That way your prefab can register:

    Code (csharp):
    1.  
    2.     public class PrefabCode : MonoBehaviour
    3.     {
    4.         private void Awake()
    5.         {
    6.                 GameController.Instance.RegisterPrefab(this.gameObject);
    7.         }
    8.  
    9.     }
    10.  
    Then your game controller can manage the events for your prefabs. You will also have to tweak the script priorities so that GameController's Awake is called first.
     
  4. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    4,019
    If we're talking about non-instantiated prefabs then I really wonder why you're trying to do that?

    If you instantiate the prefab, that's when it should do its stuff and it should have all the data available to it. If that is not the case, change your architecture so that this works.

    Hooking up inactive prefab references to receive events is more likely than not going to cause issues (simply because they are not instantiated, and components not enabled, and who knows possibly those events even fire in the editor...). If you only need to change some values, those values ought to be passed during instantiation (see above).