unity gameobject add component code example

Example 1: 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 2: unity create gameobject with component

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

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: how to add a componet to a gameobject throgh code unity

//This uses C# and unity
//to add a ridgidbody
gameobject.addComponet<ridgidbody>();
//to add a meshCollider
gameobject.addComponet<MeshCollider>();
//check out my profile