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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Poison Aura. Convert Component type to Specific one.

Discussion in 'Scripting' started by radokhlebov, Apr 10, 2016.

  1. radokhlebov

    radokhlebov

    Joined:
    Mar 13, 2015
    Posts:
    14
    So I've got aura that is basicly 2d collider and when some object with a collider in it enters trigger-aura that gameobject puts in List<GameObject>. Well. The question is how to get not Component but list of ZedHealth?

    Code:

    Code (CSharp):
    1. public List<Component> GetListOfComponent(List<GameObject> gameObjectsList, string componentName)
    2.     {
    3.         List<Component> comp = new List<Component>();
    4.  
    5.         Type type = Type.GetType(componentName);
    6.  
    7.         foreach (GameObject gObject in gameObjectsList)
    8.         {
    9.             if (gObject)
    10.             {
    11.                 if (gObject.GetComponent(type) != null)
    12.                 {
    13.                     comp.Add(gObject.GetComponent(type));
    14.                 }
    15.             }
    16.         }
    17.  
    18.         return comp;
    19.     }
    Code (CSharp):
    1.  List<Component> counterC = GetListOfComponent(targets, "ZedHealth");
    2.  
    3.         Debug.Log(string.Format("Objects count: {0}", counterC.Count));
     
  2. Zaladur

    Zaladur

    Joined:
    Oct 20, 2012
    Posts:
    392
    It seems like you are trying to use your generic, but not quite getting there. Try something like....

    Code (csharp):
    1.  
    2. public List<T> GetListOfComponent(List<GameObject> gameObjectsList)
    3.    {
    4.        List<T> comp = new List<T>();
    5.        foreach (GameObject gObject in gameObjectsList)
    6.        {
    7.            var c = gObject.GetComponent<T>();
    8.            if (c != null)  comp.Add(c);              
    9.        }
    10.        return comp;
    11.    }
    12.  

    Code (csharp):
    1.  
    2. var counterC = GetListOfComponent<ZedHealth>(targets);
    3.