Search Unity

how can i change a variable value from other script?

Discussion in 'Scripting' started by brunoenvia, Aug 21, 2019.

  1. brunoenvia

    brunoenvia

    Joined:
    Aug 5, 2019
    Posts:
    94
    i need to change player speed from other script how can i do that?
     
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    You get a reference to the instance of the script and then make the change. There's a variety of ways to get that reference, which there's lots of threads discussing so I won't rehash them all here.

    But as a quick example, assume you have a MonoBehaviour called PlayerScript with a public Speed float, and you set your reference to it in the inspector. Your code in the other script could look something like this:
    Code (csharp):
    1. public PlayerScript PlayerScriptInstance;  //Reference to PlayerScript set in the inspector
    2.  
    3. private void changeSpeed(float newSpeed)
    4. {
    5.     PlayerScriptInstance.Speed = newSpeed;
    6. }