unity find component code example

Example 1: how to get component in unity c#

GetComponent<Rigidbody>(); //used to find component on character (rigid body can be changed)
GameObject.FindGameObjectWithTag("player"); //finds any game object in the scene with this tag

Example 2: how to find a component in unity

//Say you want to find a BoxCollider in the button, you would find the Gameobject first
//Then you would get the component of "BoxCollider" from "Button"

GameObject Button = GameObject.Find("Button");
BoxCollider button = Button.GetComponent<BoxCollider>();

Example 3: unity gameobject.getcomponent

rb = GetComponent<Rigidbody>();