how to add component in unity code example

Example 1: Add component object to gameobject unity

//to add a new ridgidbody
gameobject.AddComponent<Rigidbody>();
//to add a new meshCollider
gameobject.AddComponent<MeshCollider>();
//Original answer by MakerBenjammin6, cleanup by me.

Example 2: unity add component

//Use the AddComponent<T>() Method to add a component to your gameobject
GameObject gameObject;

gameObject.AddComponent<BoxCollider>(); //Component has to be an actual Unity component

Example 3: c# addcomponent

// Consider an existing GameObject, gameObj
Rigidbody addedComp = gameObj.AddComponent<Rigidbody>() as Rigidbody;
// You can also add custom components by class name