add component dynamically from public object

Hi guys,

i’ve got a problem, i tried to search an answer in internet but i didn’t find it.

I’ve got this situation in my project:

public class GameController : MonoBehaviour {

public GameObject enemyShip;
public Object scriptToAdd; //custom script draggable in unity inspector

void Start()
{
         enemyShip.AddComponent<scriptToAdd>(); //How to do this?
}

}

Following different topics i found solutions like enemyShip.AddComponent(scriptToAdd.GetType()) but didn’t works ad this message was shown in console: “Can’t add component because ‘MonoScript’ is not derived from Component.”

Can you help me please? i’m a very beginner in Unity, sorry. I’m asking for help because i haven’t found nothing that can help me.

Thanks in advance

I’m afraid only MonoBehaviour scripts can be added as component. If scriptToAdd is MonoBehaviour you need to give it right type, but Object type cannot be added as component because it isnt component.

EDIT :

Wait a second, now i get it. You want assign any script via. inspector and add it as component, right ?
In that case simply use MonoBehaviour type instead of Object type. Then use enemyShip.AddComponent(typeof(scriptToAdd)) but you cannot use Object, you must use MonoBehaviour type.

Have luck with your project.