How to add collider by a named variable

Hi all I want to do something similar to this… But I am unsure of how to figure out the string name to use.

string my_col = “CircleColiider2D”;
gameObject.AddComponent(Type.GetType(my_col));

of course my string constant will be of 1 of several types, Box,sphere,circle etc… Or even other components in the future.

I have tried “UnityEngine.CircleColider2D”

All cases of type that I have tried resulted in null values.

Highflier

What are you trying to do with it? There might be a better way

You can use a crude solution like this:

string my_col = "CircleCollider2D";
CircleColider2D selected = new CircleCollider2D();
if (selected.getType() == "my_col"){
    do something
}

I don´t know what you want in your project, but if you want to attach, for example, a type of element only put the name of the element with a string, instead of a type, you are doing it wrong. What i Would do is have a lot of differents types of components in differents prefabs. Each prefab have different components, (one of the circlecollider, other polygonCollider, etc).

In script, i attach all of type you are ussing (for example, if in my script i attach in editor a gameobject with circlecollider, in script i use all component type, and, with a sentence, only if thats components are different to null, thats means that components is the availabe one

I have a layout file that I use a load time. It has a list of GameObjects and a list of components that go with each Object. Thus I can create the object, and I can add the components/scripts that I have created but the built in components such as colliderboxes do not work, Thus right now I have to have a case statement. I just thought there would be a way to add a unity built in component runtime via it’s name and not it’s type.

string input
Switch (input)
Case “CircleCollider2D” :
gameObject.AddComponent();
Break;
Default :
gameObject.AddComponent(Type.GetType(input));
Break

Well I have decided to just give up on the Type.GetType technique, as it does not work at all in WebGl builds but does partially work in the editor. A large Switch case statement is what I will use instead.

Also as a note I found a bug in the WebGL player, The following lines of code crash in WebGL but work fine in some of the other platforms. Not sure how to report it but feel free to.

List myObjects = new List();
myObjects.clear();

The Clear method will get a stack overflow. It appears to count down from the # of items in the list. Thus 0-1 = -1 and so forth.

The fix that I am using is to either check the count before I try to clear it, and only clear it is count >0
or just add a object first
myObjects.Add(gameObject);
myObjects.clear();

It has been a slow learning process searching for bugs like these.

Highflier

Inside your project, I think the bug report option is in the window or help menu. It’s one of the drop downs to the right of the ones across the top

I reported the list.clear(); bug.