- Home /
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?
@Jaxcap's solution will work just fine, but you can go one class further:
motor = GetComponent(Character$$anonymous$$otor);
movement = motor.movement;
movement.maxForwardSpeed = 20.0;
You need to figure when you are accessing something by reference vs. by value. Classes are by reference. Primitives like floats are by value. Anything in the reference manual defined as a 'struct' is by value (like Vector3).
Answer by Jaxcap · Jun 06, 2013 at 02:19 PM
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 ;
}
}
excellent. Great advice as well guys. Still a beginner really but ill keep all that in $$anonymous$$d when accessing components. thanks very much.
Your answer
Follow this Question
Related Questions
Difficulties accessing other components 4 Answers
Why GetComponentInChildren is not working ? 3 Answers
2D Animation does not start 1 Answer
differences: generic GetComponent. 3 Answers
Activate objects/crafting in a game. 1 Answer