unity how to get component from gameobject 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: unity create gameobject with component

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

Example 3: findobject getcomponent

GameObject.Find("Name of the object you want to access").GetComponent<Name of the Component (Transform,Script,RigidBody,etc..)();
     
     An Example (easy to understand):
     
     GameObject Player = GameObject.Find("Player");
     PlayerController PlayerControllerScript = Player.GetComponent<PlayerController>();
     PlayerControllerScript.run = true;
     
     Another Example:
     
     GameObject.Find("Player").GetComponent<PlayerController>().run = true;

Example 4: unity get component

public GameObject Var; //only if the component you want is on a different gameObject

void Start(){
	Var.GetComponent<Component>(); //just GetComponent<Component>(); if the component you want is on the same object as script
}