Search Unity

Script to Find Component Based on Input Component Type

Discussion in 'Scripting' started by Xepherys, Mar 26, 2017.

  1. Xepherys

    Xepherys

    Joined:
    Sep 9, 2012
    Posts:
    204
    I'm trying to create a function in C# that will take a GameObject and a Component<T> and return an attached Component from base, child, or parent elements.

    Currently I have this:


    public static T GetCombatComponent<T>(GameObject go)
    {
    T _ret;

    _ret = go.GetComponent<T>();

    if (_ret == null)
    {
    _ret = go.GetComponentInChildren<T>();
    }

    if (_ret == null)
    {
    _ret = go.GetComponentInParent<T>();
    }

    return _ret;
    }
    and am calling it like this:

    DamageListener _dl = CombatMethods.GetCombatComponent<DamageListener>(c.gameObject);

    Obviously this isn't quite right, but I'm not sure what would work. Basically, in this case I want to return a DamageListener attached somewhere on c.gameObject. But in another place I might want to return a DamageTalker or a DeathScript or a CharacterSheet, so making this work helps create an easy method for getting what will always be a single instance of a Type, but that might be in various places on the hierarchy.
     
  2. Xepherys

    Xepherys

    Joined:
    Sep 9, 2012
    Posts:
    204
    Well, I'm answering this rather than closing it only because the written function may prove helpful to someone else down the road. It appears that, despite my best efforts, I was only saving the one script and not the other - thus there was no completed function to call from the one script. Or it was something else, but the code looks the same and it's suddenly working, so... yay?