unity Player.getcomponet<Move2S> code example

Example 1: getcomponent c#

//First script 
public class Enemy : MonoBehaviour{
  public int health = 10;
  public void saySomething(){
    Debug.Log("Hi, i am an enemy.");
  } 
}
//Second script
//There is one thing though,
//if the script is located on another gameobject,
//which will be most likely, you have to somehow
//find that gameobject first. There are many ways of
//doing it, via raycast, collision,
//trigger, find by tag, find by gameobject etc.
//But i will use the simplest way to understand,
//that is declaring public GameObject in player script,
//which contains Enemy, and later you just drag and drop the
//gameobject in the inspector.
public class Player : MonoBehaviour{
  //Drag and drop gameobject with script Enemy in inspector
  GameObject enemyGameObject;
  void Start(){       
    //We get Enemy component - script
    //from public gameobject which contains this script
    Enemy enemyScript = enemyGameObject.GetComponent<Enemy>();
    //This will debug Enemy health is: 10  
    Debug.Log("Enemy health is:"+ enemyScript.health)  
      //This will debug "Hi, i am an enemy." 
      enemyScript.saySomething();  
  } 
}

Example 2: 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;