I'm making 3d animation for charachter movement, and Animator.SetFloat(...) doesn't response in functions that I call in if statements, code below. Interesting thing that these Debug.Log's work properly, when I walk console has "Walk", when I run console has "Run" etc. I think I have problem with Scope, but I'm really sure. Screenshots: animator props console logs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private float moveSpeed;
[SerializeField] private float walkSpeed;
[SerializeField] private float runSpeed;
[SerializeField] private float groundCheckDistance;
[SerializeField] private float gravity;
[SerializeField] private bool isGrounded;
[SerializeField] private LayerMask groundMask;
[SerializeField] private float jumpHeight;
private Vector3 moveDirection;
private Vector3 velocity;
private CharacterController controller;
private Animator anim;
void Start()
{
controller = GetComponent<CharacterController>();
anim = GetComponentInChildren<Animator>();
}
void Update()
{
Move();
}
private void Move()
{
isGrounded = Physics.CheckSphere(transform.position, groundCheckDistance, groundMask);
if(isGrounded && velocity.y < 0) velocity.y = -2f;
float moveZ = Input.GetAxis("Vertical");
moveDirection = new Vector3(0, 0, moveZ);
moveDirection = transform.TransformDirection(moveDirection);
if (isGrounded)
{
if (Input.GetKeyDown(KeyCode.Space)) Jump();
if (moveDirection != Vector3.zero && !Input.GetKey(KeyCode.LeftShift)) Walk();
else if (moveDirection != Vector3.zero && Input.GetKey(KeyCode.LeftShift)) Run();
Idle();
moveDirection *= moveSpeed;
}
controller.Move(moveDirection * Time.deltaTime);
velocity.y = gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
private void Idle()
{
anim.SetFloat("speed", 0);
}
private void Walk()
{
anim.SetFloat("speed", 0.5f);
moveSpeed = walkSpeed;
Debug.Log("Walk");
}
private void Run()
{
moveSpeed = runSpeed;
Debug.Log("Run");
anim.SetFloat("speed", 1);
}
private void Jump()
{
velocity.y = Mathf.Sqrt(jumpHeight * -2 * gravity);
isGrounded = false;
}
}
CodePudding user response:
Ok, I've found the solution, I missed "else", because of that Function Idle() always had control under Animator.SetFloat(...)
if (isGrounded)
{
if (Input.GetKeyDown(KeyCode.Space)) Jump();
if (moveDirection != Vector3.zero && !Input.GetKey(KeyCode.LeftShift)) Walk();
else if (moveDirection != Vector3.zero && Input.GetKey(KeyCode.LeftShift)) Run();
else Idle(); //this how it must looks like
moveDirection *= moveSpeed;
}