Spag-bol
Spag-bol

Reputation: 35

Adding Scripts to Objects via an Array

I'm currently storing a list of Scripts in an array and I am trying to add each one to a different object. I was just searching for the script by name but after I updated to unity 5 I keep getting warnings telling me not to do it because it slows everything down.

Currently my code looks something like this:

GameObject unit1;
Knight knight; // name of code
Pawn pawn;

CodeName    = new Units [3]     {knight, knight, pawn}

unit1.AddComponent(CodeName[0]);

This gives me the error "cannot convert 'Knight' expression to type `System.Type'".

Its obviously after the object type but I can't figure out how to pass it that information.

Upvotes: 0

Views: 561

Answers (1)

Aizen
Aizen

Reputation: 1825

I am not sure why you're storing Classes in an Object, because you don't really have to. As long as the Class is public, you always call AddComponent without using an array to store them.

Class is stored already from CLR and only be used when you instantiate them. That means it won't need to be Instantiated if it is not used. In Mono(Unity3d) everything that you stored in an array needs to be Instantiated first or at lease have a null Value, but this is not what matters to Unity3D. It will throw you a warning that it is slow because your adding a component to the "GameObject" not into Object which C# understands. The component is known already on RunTime but your still trying to pull the Script out of the Array<- In C# this is a big SIN. Why store Classes where you can Directly access it depending on it's Access Modifier.

In your code you make a pointer or reference to Knight Class and Pawn Class <- You don't need to.

Then Store them in the Array. (You must have a good reason why) Explain further if you really need to do this.

But all you need to do is this.

unit1.AddComponent<Knight>(); 
// In case you didn't notice it is <> which represents Generic, it can be any type.

So you can really do

unit1.AddComponent<Codename[0]>();
// But take my word for it, it is slow. 

Because you're doing this.

Instantiating 3 Classes for Each Object that you will add the Component. Store them to your GameObject which have the Scripts for your array. Pull them out from the Array and check for the Type if it is Equal type. Adding them to the GameObject. Re-Instantiate them by calling the Script Constructor.

If this is a chess game. Imagine how many times your Runtime will do this where you can just do.

-Add the component and Initialize.

Hope this helps.

Upvotes: 1

Related Questions