Add Script to a gamobject with addcomponent

Hi,

I face an issue with Addcomponent : I have a gameobject named cube and I would like to attached a script named mousecontroller.

In a script named MapGeneration, I tried cube.AddComponent(mousecontroller) but it recognizes mousecontroller as a classe and tells me that it’s not valid in ths context.

The closer command i have found is cube.AddComponent(typeof(mousecontroller)) but it creates only the component without assigned my script

Thanks by advance.

Did you try just renaming your script into something else than “MouseController”?

Yes but the issue is that AddComponent(string namescript) is obsolete and I can’t find an other solution to do it …

In order to add a script as component at runtime you must use the following syntax;

gameObject.AddComponent<ClassName>();

Where ClassName is the name of your class and it must extend MonoBehaviour.