The main issue here is that you're trying to call AddComponent
with an object rather than a type, which is what's causing your issue. There are 3 possible ways you can fix this:
Solution 1
Use AddComponent with a generic function
This is very close to what you already have, and only requires you to use GetType
rather than the object itself
Component[] components = GameObject.Find("CamFly").GetComponents(typeof(Component));
for (var i = 0; i < components.Length; i++)
{
objCamera.AddComponent<components[i].GetType()>();
}
Solution 2
Use AddComponent with a type as a parameter
Very similar to the first solution, but uses GetType
as a parameter. If you were using the return value, then you'd notice that the type returned here is Component
, whereas the solution aboves return type is whatever you pass in to the generic function
Component[] components = GameObject.Find("CamFly").GetComponents(typeof(Component));
for (var i = 0; i < components.Length; i++)
{
objCamera.AddComponent(components[i].GetType());
}
Solution 3
Use AddComponent with a string argument
Again, this relies on GetType
, but uses a string instead of the type object. I haven't tested this, and my gut says it will be the slowest solution (because Unity will need use reflection to find the type you want), but is here so you can see the possible uses
Component[] components = GameObject.Find("CamFly").GetComponents(typeof(Component));
for (var i = 0; i < components.Length; i++)
{
objCamera.AddComponent(components[i].GetType().ToString());
}