- Home /
Change character speed through script
Okay, so I have a script and I'm trying to make the character crouch down. I have the crouching done, but now I need to change his speed when he's crouched. Right now, I have:
gameObject.Find("First Person Controller").GetComponent("CharacterMotor").CharacterMotorMovement.maxForwardSpeed = 3;
It saying its a null reference exception. I'm thinking its because the variables I'm trying to access are in a class. How can I change the speed of him though code? Thanks
Answer by nhftk12 · May 23, 2011 at 04:18 AM
Try to write "FirstPersonController" and not "First Person Controller" as you wrote in your code... if there is a problem - add a comment.
That wouldn't work because the object name has spaces in it. It would say null reference exception.
so change the object name to FirstPersonController. There is a problem with the name in the code or the object name, one of them have to be wrong as the error say...
Answer by blu4andor · Feb 11, 2012 at 12:28 PM
I had the same problem, but finally got it working. Here's how you access that variable:
yourPlayerObjectHere.GetComponent("CharacterMotor").movement.maxForwardSpeed;
You don't want to use CharacterMotorMovement because that's the name of the class. The problem is, maxForwardSpeed isn't a static variable. The CharacterMotorMovement object in your FPS Controller is actually an instance of that CharacterMotorMovement class simply called "movement."
For example, I wrote a script that stores my player's walking speed into a variable:
var player : Transform;
var walkingSpeed = player.GetComponent("CharacterMotor").movement.maxForwardSpeed;
If you still get errors, another thing you have to remember is that you can't access maxForwardSpeed until after the game starts. So you might wanna put it in the Update() function or the Start() function.
Your answer
Follow this Question
Related Questions
Strange crash, please help 1 Answer
Reading Other Scripts stats 3 Answers
Why is my character so slow? 1 Answer
Set default forward speed in first person controller 2 Answers