addcomponent unity code example

Example 1: unity requirecomponent

using UnityEngine;// PlayerScript requires the GameObject to have a Rigidbody component
[RequireComponent(typeof(Rigidbody))]
public class PlayerScript : MonoBehaviour
{
    Rigidbody rb;    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }    void FixedUpdate()
    {
        rb.AddForce(Vector3.up);
    }
}

Example 2: 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 3: 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 4: c# addcomponent

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

Example 5: On add component unity

void Reset()
{
  //Your code here
}

Example 6: 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