- Home /
Calling variables in classes from other scripts
Hello. I'm a new unity user, and am just messing around with some basic scripting concepts before I get started on any real projects
Anyways, what I want to do is make a simple powerup that when touched, makes you run faster. I'm using the built in first person camera, and created a separate script for the powerup itself. I'd like to call the 'maxForwardSpeed' variable from the 'CharacterMotor' js file. Note that is part of the CharacterMotorMovement class in said file. This is what I have so far (I know what I have is wrong)
function OnTriggerEnter(other : Collider) {
if (other.tag == "Player") {
other.GetComponent(CharacterMotor).maxForwardSpeed = 1;
Destroy(gameObject);
}
}
As a disclaimer, I have checked every question here related to this topic and have read the piece on this in the reference manual (link below) multiple times
http://docs.unity3d.com/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html
Answer by stingman · Jul 12, 2012 at 01:42 AM
I assume this script will be attached to the powerup. If that's the case this looks fine as is. This is what your code will do:
when a game object tagged as "Player" enters the trigger of the powerup it will look for a component on "Player" called CharacterMotor. It will then change the value of the variable of maxForwardSpeed to equal 1. It will also destroy the powerup.
Is this what you want? If 1 is the default value of the variable then just increase the value until you reach the desired speed. You've got it all set up correct though.
Yeah it's attached to the powerUp. I'll keep messing around with it some more, because its giving me a "$$anonymous$$issing$$anonymous$$ethodException: $$anonymous$$ethod not found: 'Character$$anonymous$$otor.maxForwardSpeed" error. I should note that this only comes up when you touch the powerup item, no errors before that. Thanks though, at least I know I'm close hah
Answer by fifty6 · Jul 12, 2012 at 04:49 AM
var foodDec: int = 0;
function Update() {
var motorScript = transform.GetComponent(CharacterMotor);
if(Input.GetKey("left shift")) { //Debug.Log("player is running"); motorScript.movement.maxForwardSpeed = 9; foodDec = 5;
} else { motorScript = transform.GetComponent(CharacterMotor); motorScript.movement.maxForwardSpeed = 6; foodDec = 1; }
}
This is how I created a sprint function. Try calling it by variable.movement.maxForwardSpeed = .
Thanks for the tip. While I still haven't gotten it quiet yet, I know I'm close. I'll keep trying things
function OnTriggerEnter(powerUp : Collider) {
var moveScript = transform.GetComponent(Character$$anonymous$$otor);
if (powerUp.tag == "Player") { Debug.Log("get"); moveScript.movement.maxForwardSpeed = 50; Destroy(gameObject); } }
is what I'm now using, but I keep getting a null reference exception error