How to obtain a variable in update that doesn't behave like a loop? C#
I'm attempting to listen for the status of the Character Controller to gather the Y coordinate of the start of the fall with fallD1, and the end of the fall with fallD2. With this current code, the if behaves like a loop statement because of the FixedUpdate().
void FixedUpdate(){
if (!controller.isGrounded){
playerTransform = player.transform;
Vector3 playerPos = playerTransform.position;
fallD1 = postition(playerPos); //position() pulls the Y coordinate from playerPos
}
else {
playerTransform = player.transform;
Vector3 playerPos = playerTransform.position;
fallD2 = postition(playerPos); //position() pulls the Y coordinate from playerPos
intFallDistance = fallD1 - fallD2;
Debug.Log(intFallDistance);
}
}
They will continue to follow the exact coordinates until the current status is false. Does anyone have any suggestions on how to go about this more efficiently? EDIT: I've thought of creating a loop that starts when the player is no longer grounded and execute the rest of the else statement upon exit, but I'm not sure how to go about creating such a loop
Answer by jasonlu00 · Sep 21, 2017 at 11:31 PM
You can do event-based check instead of polling. https://docs.unity3d.com/ScriptReference/CharacterController.OnControllerColliderHit.html
void Start(){
fallD1 = 0; //assume your character starts at y=0
fallD2 = fallD1;
}
void OnControllerColliderHit(ControllerColliderHit hit) {
if(controller.isGrounded){
fallD2 = controller.transform.position.y;
intFallDistance = fallD1 - fallD2;
Debug.Log(intFallDistance);
fallD1 = fallD2; //set D1 to new y
}
}
While your code didn't quite meet my needs, I was able to extrapolate off of it to find the true solution. Thank you very much! $$anonymous$$y finished version:
void OnCollisionExit()
{
exit = controller.transform.position.y;
}
void OnCollisionEnter()
{
enter = controller.transform.position.y;
fallDistance = exit - enter;
}