Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Listening on a prefab's event from a controller

Discussion in 'Scripting' started by xqtr123, Feb 13, 2018.

  1. xqtr123

    xqtr123

    Joined:
    Jun 7, 2014
    Posts:
    20
    Hi!
    I have a controller that spawns moving enemies. I have an object pool (Lean Pool asset) and I want to despawn (LeanPool.Despawn) the enemy when it has reached its destination. I'm thinking that I need to create an event trigger in the enemy script and listen to it in the controller script, but I how would I do this?
     
  2. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,294
    The general setup for a event in C# is this:

    Code (csharp):
    1. using System;
    2. using UnityEngine;
    3.  
    4. public class EventDemo : MonoBehaviour {
    5.  
    6.     public Action OnReachedDestination;
    7.     public Vector3 destination;
    8.  
    9.     private void Awake() {
    10.         OnReachedDestination += ReachedDestination;
    11.     }
    12.  
    13.     private void ReachedDestination() {
    14.         Debug.Log("Reached destination!");
    15.     }
    16.  
    17.     void Update() {
    18.         if(Vector3.Distance(transform.position, destination) < 1f) {
    19.             OnReachedDestination();
    20.         }
    21.     }
    22.  
    That's a very silly example, but it shows how to assign a function to a variable and call it. In your case, you'd call LeanPool.Despawn in ReachedDestination, and call it based on whatever system you're using to move things.

    Please ask if there's any problems.
     
  3. xqtr123

    xqtr123

    Joined:
    Jun 7, 2014
    Posts:
    20
    Hi!
    Thanks for the answer, I ended up using
    https://wiki.unity3d.com/index.php?title=Advanced_CSharp_Messenger
    instead, with the following answer:
    https://forum.unity.com/threads/question-about-advanced-csharp-messenger.240902/

    GameController.cs
    IEnumerator SpawnCopters()
    {
    while(true) {
    Vector2 spawnPosition = GetSpawnPosition();

    var clone = LeanPool.Spawn(copter, spawnPosition, transform.rotation, null);
    Messenger.AddListener<GameObject>("reachedDestination", DespawnCopter);
    yield return new WaitForSeconds(Random.Range(15, 25));
    }
    }

    void DespawnCopter(GameObject copter)
    {
    LeanPool.Despawn(copter);
    }

    Copter.cs
    Messenger.Broadcast<GameObject>("reachedDestination", gameObject);
     
    Last edited: Feb 13, 2018