Hi, I'm having a problem, I'm trying to make an array of multiple scripts. Then I found the suggestion of: Code (CSharp): public MonoBehaviour [] something however I can not add prefabs, so I've solved add the scripts in this obj and just deactivating. However now and I can not add the scripts in it as in the example: Code (CSharp): int randomPower = Random.Range (0, something.Count); other.gameObject.AddComponent <something[randomPower]> (); Someone please help me, I've been looking for hours, but none has solved the problem.
That won't work, you need the type as a parameter: Code (CSharp): other.gameObject.AddComponent(something[randomPower].GetType()); [/QUOTE] Maybe somebody can help with what you want to achieve but this is something I never saw before. What you could do is using a set of strings: Code (CSharp): public string[] scripts; // Use this for initialization void Start() { int randomPower = UnityEngine.Random.Range(0, scripts.Length); var type = Type.GetType(scripts[randomPower]); gameObject.AddComponent(type); } You have to include namespaces in GetType() if there are any. Another way is using hard coded Types: Code (CSharp): public Type[] scripts = new Type[] { typeof( Script1), typeof( Script2), typeof( Script3) }; // Use this for initialization void Start() { int randomPower = UnityEngine.Random.Range(0, scripts.Length); gameObject.AddComponent(scripts[randomPower]); } or so: Code (CSharp): public string[] scripts; // Use this for initialization void Start() { int randomPower = UnityEngine.Random.Range(0, scripts.Length); gameObject.AddComponent(GetPower(scripts[randomPower])); } Type GetPower(string power) { switch (power) { case "Power1": return typeof(Power1); case "Power2": return typeof(Power2); default: break; } return null; } That is all that comes into my mind.
I don't think you need to work as hard as all that. This is the one case where the version of AddComponent that takes a type name as a string would be preferable to the strongly-typed version. ...Oops, but I see Unity has deprecated that. Bad Unity! No biscuit! So either you use the deprecated function while you still can, or you monkey around with Types as @McDev02 has shown.