x


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

more ▼

asked May 23 '11 at 03:11 AM

Syllith gravatar image

Syllith
44 9 11 13

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

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.

more ▼

answered Feb 11 '12 at 12:28 PM

blu4andor gravatar image

blu4andor
1 1 1 2

(comments are locked)
10|3000 characters needed characters left

Try to write "FirstPersonController" and not "First Person Controller" as you wrote in your code... if there is a problem - add a comment.

more ▼

answered May 23 '11 at 04:18 AM

nhftk12 gravatar image

nhftk12
74 12 16 21

That wouldn't work because the object name has spaces in it. It would say null reference exception.

May 23 '11 at 09:35 PM Syllith

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...

May 24 '11 at 04:15 AM nhftk12
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x372
x186
x30

asked: May 23 '11 at 03:11 AM

Seen: 2535 times

Last Updated: Feb 11 '12 at 02:07 PM