I have a First Person Controller from the Unity Assets I imported. I’d like to know in C#, how to access the CharacterMotor Component’s ‘Max Forward Speed’ variable from another script, as well as change it…
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour
{
//Create a motor variable.
CharacterMotor motor;
//Create your own speed variable.
float mfs;
//For testing purposes
string label;
void Start ()
{
//Be sure component is found before assigning.
if(GetComponent<CharacterMotor>())
motor = GetComponent<CharacterMotor>();
//Check if motor is null or not before matching your speed with motor's speed.
//If you want to create your own speed on startup, just assign a float or int to mfs and remove this.
if(motor != null)
mfs = motor.movement.maxForwardSpeed;
}
void Update()
{
//Press and hold up or down on vertical axis to increase and decrease speed.
//For Testing Purposes.
mfs += (int)Input.GetAxis ("Vertical");
//Be sure motor is not null before matching motor's speed with your variable's speed.
if(motor)
motor.movement.maxForwardSpeed = mfs;
//Update label at runtime to output GUI.
//For Testing Purposes.
label = "Motor Script Max Forward Speed = " + motor.movement.maxForwardSpeed + "
" + "Your Max Forward Speed = " + mfs;
}
void OnGUI ()
{
//Print label variable.
GUILayout.Label (label);
//Instructions.
GUILayout.Label("
" + “Press Up and Down Arrow keys (or W and S) to increase or decrease Max Forward Speed.”);
}
}