accessing components of character motor script

i have pick ups that increase the players speed for a period of time. I’m using built in FPS character controller, and i can access it but i cant declare it in a start function, i have to GetComponent each time i want to adjust it, i dont know why?

function OnControllerColliderHit (pickUp : ControllerColliderHit){

	if (pickUp.collider.gameObject.tag == "GoldenSkull")
	{
		Destroy (pickUp.gameObject);
		GetComponent(CharacterMotor).movement.maxForwardSpeed = 25;
		
		yield WaitForSeconds (4.0);
		GetComponent(CharacterMotor).movement.maxForwardSpeed = 6;
		
	}

}

this works…

var motor : CharacterMotor ;
var speed : float ;

function Start (){

	motor = GetComponent(CharacterMotor);
	speed = motor.movement.maxForwardSpeed;
}

function OnControllerColliderHit (pickUp : ControllerColliderHit){

	if (pickUp.collider.gameObject.tag == "GoldenSkull")
	{
		Destroy (pickUp.gameObject);
		speed = 20 ;
		yield WaitForSeconds (4.0);
		speed = 6 ;
	}

}

but this will not? there is no errors but the speed is not adjusted? why cant i declare the speed as a variable and just access it like that?

In the second one, when you do:

speed = motor.movement.maxForwardSpeed;

since they are both primitives, by doing that you’re not actually “linking” the two variables together. You are just setting the value of speed equal to the value of motor.movement.maxForwardSpeed. So when you change the value of speed in the OnControllerColliderHit function, it’s only changing that value, not the one in the motor object.

With what you have, you could do:

var motor : CharacterMotor ;
 
function Start (){
 
    motor = GetComponent(CharacterMotor);
}
 
function OnControllerColliderHit (pickUp : ControllerColliderHit){
 
    if (pickUp.collider.gameObject.tag == "GoldenSkull")
    {
       Destroy (pickUp.gameObject);
       motor.movement.maxForwardSpeed = 20 ;
       yield WaitForSeconds (4.0);
       motor.movement.maxForwardSpeed = 6 ;
    }
 
}