Search Unity

Communicate between scripts on same gameobject

Discussion in 'Editor & General Support' started by Wekthor, Feb 6, 2020.

  1. Wekthor

    Wekthor

    Joined:
    Apr 30, 2011
    Posts:
    165
    Hi,

    i have class called Enemy. It handles health, receiving damage etc. For some reasons i decided to not have regular inheritance of base class, but rather have separate script to handle all other logic on the enemy. Ie scripts like Enemy1, Enemy2 etc as separate class.

    So each enemy would have both Enemy script and for example Enemy1 script. While Enemy handles his health and Enemy1 handles for example his shooting logic.

    In this specific example, what is the best way to interact between these two script on one gameobject? The issue is that Enemy script needs to talk to Enemy1 script, but it does not know if it is Enemy1 or Enemy2 ( enemies are created dynamicly in code ), so i cant create reference to it.
    SendMessage seems a bit sloppy, i am hoping for some better way, but not sure what that would be. Thanks
     
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    I'd have both Enemy1 and Enemy2 inherit from a single script, but if you don't want to do that you could just have references to both Enemy1 and Enemy2 components, do a GetComponent for both in Start(), and whichever one isn't null is the one you use. But it depends on how much code needs to interact with these, as I'd only do it that way if I only needed to talk to Enemy1 or Enemy2 fairly infrequently.
     
  3. Wekthor

    Wekthor

    Joined:
    Apr 30, 2011
    Posts:
    165
    I dont have inheritance, because in my EnemyManager, where i spawn enemies, i have custom class object, which is using reference to this spawned Enemy. This enemy object is then used to do all kinds of stuff. If i have different scripts, which inherit from some base class, its not possible to have reference in this custom object to only one script.
    That probably does not make any sense :) In general, i need enemy to appear as exactly same object with same components as much as possible. Only deviation is one custom script on top of that.
    Doing what you suggest would probably work, but get clumsy if there was for example 5 types of enemies or more i think.
     
    Joe-Censored likes this.
  4. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Yeah what I suggested doesn't scale at all :p

    If you showed some code that shows what you're trying to do you might get some better suggestions. I'm personally confused why Enemy1, Enemy2, Enemy3, etc, can't all be the same class. Is your code so different and complex in these scripts that they can't just be combined?