Adding a Component to a gameobject/prefab in code

Hi,

I am trying to add a MonoBehaviour Script called “ScanComponent” (that I created) to a gameobject in code and I am quite confused why it doesn’t work, because when I try to add a “SphereCollider” to the gameobject in the same way it works.

Does anyone know how to add a self written Script to a Component?
(The error code is “CS0039” and it says that “UnityEngine.Component” can’t be converted to “ScanComponent”)

Best regards,
Dominik

 newObject.AddComponent<ScanComponent>();

Then you can

newObject.GetComponent<ScanComponent>();

But if you do iton prefab what always will have this component you can just drag nd drop it on that prefab in inspector and your GO will always have it.

Does ScanComponent is a Monobehavior?

Only 50 cents in @MartinMa answer, when you do an AddComponent, you can cache the result, isn’t necessary to do an GetComponent

var component = newObject.AddComponent<ScanComponent>();