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

Resolved Event subscription only if script is on same game object

Discussion in 'Scripting' started by Daviiid, Jan 16, 2023.

  1. Daviiid

    Daviiid

    Joined:
    Oct 9, 2015
    Posts:
    50
    I have a script EnemyHPControler which needs to communicate with Enemy1Controller, Enemy2Controller...3, 4 and so on. On each EnemyController script I have a method that needs to be called from the EnemyHPController script. While ignoring all the other cloned instances of enemies of the same type with the same script.

    I was thinking of firing off events. But how do I subscribe to it only if both scripts are on the same game object?

    Or maybe I could subscribe to all of them. While I send through this game objects reference and check if they have the same game object and if not unsubscribe? But that doesn't seems like a standard solution. Each time I'd spawn in a new enemy it would try to subscribe and unsubscribe from all other enemies.
    And I don't even know how making different instances of the same event would work.

    Please point me in the right direction thank you.
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,144
    Why not set up your EnemyController scripts to use an interface? Then you can use GetComponent<InterfaceName>() to grab the script that has that interface and run the method it has, which you know it will have since it has to implement the interface.
     
    Bunny83 likes this.
  3. Daviiid

    Daviiid

    Joined:
    Oct 9, 2015
    Posts:
    50
    Thanks Brathnann. This suggestion was exactly what I needed. And the reason I wasn't using interfaces was, because when I checked the Interfaces tutorials before I didn't understand them. I guess I wasn't ready for them back then with my lack of experience. Now I went through a couple more tutorials and I get it now. And I can start optimizing my code.

    While I was googling I found a replacement method which isn't as good as Interfaces I guess. But it worked. It was BroadcastMessage(); I think the interface option is a bit more optimized since it does not have to search through class methods and the children of a game object.