Using a script to change another script's variables

Hey all, just getting into the scripting aspect of unity and I was looking for a little help. I’ve been reading the Scripting Reference, but haven’t yet come across a way to use a script to change another script’s variables.

For example, I want to have my character’s speed increased when he picks up a speed power-up, but I’m not sure how to get the power-up’s script to change my FPS Controller Script’s speed?

Any help would be great, or if you know where it is in the scripting refernce, that’s good too!

Thanks!

This page has links to pages on accessing other Components and GameObjects. In summary, if the script is located on another GameObject you’ll have to get a reference to that object in some way, and then you can use GetComponent to locate the precise script you want.

If you only have one instance of that script, the easiest way is to make that variable ‘static’, which makes it global and visible to the rest of the program.

There are cleaner ways of doing it though :slight_smile:

You could just have the function for the trigger or collider of the healthpack run a function in the other script that increases the health…

function SpeedUp(hit : int)
{
   speed += hit;
   if (speed > speedMax) {
      speed = speedMax;
   }
}

That would be in the player script. It assumes that speed is stored as an integer inside a variable called speed and that you have a variable called speedMax that prevents the value from going over a certain amount.

function OnTriggerEnter(hit : Collision)
{
   if (hit.transform.tag == "Player") {
      hit.gameObject.SendMessage("SpeedUp", increase);
   }
}

This code assumes you have a variable called increase that holds how much the speed pack speeds up the player and that the player is tagged Player.

this is great, thanks all!