Search Unity

AddComponent Array

Discussion in 'Scripting' started by IchBinJager, Jun 30, 2015.

  1. IchBinJager

    IchBinJager

    Joined:
    Dec 23, 2014
    Posts:
    127
    I don't know if this is even possible but, I'm trying to add an array/list of Components to a prefab made in a function;

    Code (CSharp):
    1. void CreatePrefab(string prefab_name, Component[] toAdd)
    2.     {
    3.         GameObject newPrefab = new GameObject ();
    4.         newPrefab.name = prefab_name;
    5.  
    6.         foreach ( Component dAdd in toAdd )
    7.         {
    8.  
    9.             newPrefab.AddComponent<dAdd>();
    10.         }
    11.     }
    I of course get a "nameSpace" dAdd could not be found. Am I a madman for trying to do all this?
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,537
    The method: AddComponent<T>() takes in a type for T and has to be a known type in that scope. It then creates a NEW component based off that type. There is another version that takes a System.Type object as its parameter.

    The array 'toAdd' is a collection of components, not types. Even if it were types, you can't use the generics version of the function, but instead the version that takes the type object as a parameter.

    Either way, you can't add existing components to a new GameObject. You have to create a NEW component on that GameObject.

    In this case you can do that by saying on line 9:

    Code (csharp):
    1.  
    2. newPrefab.AddComponent(dAdd.GetType());
    3.  
     
  3. IchBinJager

    IchBinJager

    Joined:
    Dec 23, 2014
    Posts:
    127
    Thanks, this was a huge help. I guess I wasn't too far off at least? Just didn't know to add .GetType() . Again, this makes a huge difference. Thanks.