- Home /
Accessing CharacterMotor
Hello, I've been pulling my hair out for hours now not able to figure this one out. So, as the title suggests, I'm trying to access the CharacterMotor, and store it in the variable. That task on its own is not such a problem. However, I need to access it in the Update() function, and since GetComponent is kinda harsh, I wanted to try to declare the variable before I actually use it. The problem is, you can't declare a variable in the Start() function and use it in the update(that I know of), and you can't call GetComponent outside of a function. So knowing that, how can I make my variable in the start function public so my update function can get to it? I'm using csharp, and here is the start function code:
void Start()
{
Component mainController = player.GetComponent<CharacterController>();
CharacterMotor chMotor = mainController.GetComponent<CharacterMotor>();
}
Answer by Cherno · Mar 12, 2015 at 11:12 PM
Uhm... Why don't you declare the variable in the main body and then assign the component in the Update or Start function?
private CharacterMotor characterMotor;
void Start() {
characterMotor = GetComponent<CharacterMotor>();
}
void Update() {
characterMotor.someVariable = xyz
}
I tried that. It doesn't work. I have
private Character$$anonymous$$otor ch$$anonymous$$otor;
right under the class declaration.
This in my start...
void Start()
{
Component mainController = player.GetComponent<CharacterController>();
ch$$anonymous$$otor = mainController.GetComponent<Character$$anonymous$$otor>();
}
And this to test in the Update function:
if(Input.Get$$anonymous$$ey($$anonymous$$eyCode.LeftShift))
{
ch$$anonymous$$otor.enabled = false;
}
Your Start() function makes no sense because you try to access the Character$$anonymous$$otor component of mainController, which is of Type CharacterController (or rather, non-specific Type Component, which is bad in itself :) ). GetComponent can only be used with variables of Type GameObject (although Transform is accepted as well, but in the end it's always a GameObject that is accessed). To assign the variable ch$$anonymous$$otor, write:
//assu$$anonymous$$g player is a variable of Type GameObject or Transform
ch$$anonymous$$otor = player.GetComponent<Character$$anonymous$$otor>();
Also, don't use Type Component. Try to use the right Type when using GetComponent:
CharacterController mainController = player.GetComponent<CharacterController>();
OH! Wow, I feel dumb. It works perfectly now, thank you so much!
Your answer