how to add component to gameobject unity code example

Example 1: unity create gameobject with component

GameObject go = new GameObject("Test", typeof(MeshRenderer), typeof(MeshFilter), typeof(YourScript));

Example 2: c# addcomponent

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

Example 3: unity adding component to another gameobject

//referencing a gameobject
public GameObject exampleObject;
//===============================================================>
private Rigidbody rb; //example of a component

public void Awake() {
	// adding a Rigidbody component to exampleObject
	rb = exampleObject.AddComponent<Rigidbody>();
  
	// referencing an existing Rigidbody component in exampleObject
	rb = exampleObject.GetComponent<Rigidbody>();
}

Example 4: On add component unity

void Reset()
{
  //Your code here
}