can you use AddComponent with a custom script?

Hi there,

Just wondering, is ther a way to use AddComponent to add a custom script to an object? I’m stuck trying to get it to work. I keep getting -
No appropriate version of 'UnityEngine.GameObject.AddComponent
I guess that makes sense because it is my own script but I figured sice you can do it in the editor window , there must be a way to do it in the game.

Any Ideas?
Thanks
Pete

1: Show me the code you used.
2: try this:

 yourObjectName.AddComponent("YourScriptNameWithOutFileExtension");

for another example…

floorCube.AddComponent(“FloorIsMadeOfLava”);

1 Like

It should be gameObject.AddComponent, not GameObject (you’re adding to a specific game object, not the class).

–Eric

Make sure you inherit from MonoBehavior.

I realize the docs show the string version first. You should read from the bottom of the page, instead. :wink: GetComponent, at least, tips you off. And don’t forget the new generic version, if you need to store the component in a variable.

Ahh Cool, thanks guys, I wasn’t using the quotation marks :slight_smile:
Sorry, I don’t know ho i missed that… embarrassing…

Like I said, you shouldn’t.

Hmm, I’m not sure I get it, how would you use this? GameObject.AddComponent.
Also, GetComponent is only for getting existing components, right?

I think it’s like this…

GameObject.AddComponent.();

But honestly I’ve always loathed typecasted functions like this… they never make sense to me.

I have no idea how it works in UnityScript. You could have made it yourself, in C#, before it was in the API, with an extension method (this still works, but is pointless):

public static T GenericAddComponent <T> (this GameObject gameObject) where T : Component {
	return gameObject.AddComponent(typeof(T)) as T;
}

And then you could use it like this, exactly the same as AddComponent as it exists now:

BoxCollider boxCollider = gameObject.GenericAddComponent<BoxCollider>();

Here’s a great intro to extension methods:
http://www.youtube.com/watch?v=va556bGnXIg