I am trying to create a walk-run-sprint system (similar to the one in the fallout series) where your character walks only when caps-lock is toggled, runs by default, and sprints when a key is held down. The bool for checking if the caps lock key is toggled resets less than a second after I press it however. Any/All help is appreciated, thank you!
using UnityEngine;
using System.Collections;
public class PlayerController: MonoBehaviour
{
public Animator Anim;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
bool toggleCapsLock = false;
if(Input.GetKeyUp(KeyCode.CapsLock)){
toggleCapsLock = !toggleCapsLock;
}
//Anim.SetFloat("Speed", Input.GetAxis("Vertical")*2);
Anim.SetBool("Walking", toggleCapsLock);
Anim.SetFloat("Direction", Input.GetAxis("Horizontal"));
Anim.SetBool("Running", Input.GetKey(KeyCode.LeftShift));
}
}
I haven’t scripted Unity in a while but from what I can see you’ve created your toggle boolean inside the update method, which makes it local to the update method. This means every time update is called (30 times a second?) your boolean is being deleted at the end of the function, and recreated again when it starts (as false, because you’ve told it to).
Try declaring the boolean as a global variable, just after you initialize the class, something like this:
public class PlayerController: MonoBehaviour
{
bool toggleCapsLock = false;
public Animator Anim;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyUp(KeyCode.CapsLock)){
toggleCapsLock = !toggleCapsLock;
}
//Anim.SetFloat("Speed", Input.GetAxis("Vertical")*2);
Anim.SetBool("Walking", toggleCapsLock);
Anim.SetFloat("Direction", Input.GetAxis("Horizontal"));
Anim.SetBool("Running", Input.GetKey(KeyCode.LeftShift));
}
}
Let me know if that works for you.
Still not working, here is my code now… Disappointing because I actually understand why that way would make much more sense…
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(CapsuleCollider))]
public class PlayerController: MonoBehaviour
{
bool toggleCapsLock = false;
public Animator Anim;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.GetKey(KeyCode.CapsLock)){
toggleCapsLock = !toggleCapsLock;
}
//Anim.SetFloat("Speed", Input.GetAxis("Vertical")*2);
Anim.SetBool("Walking", toggleCapsLock);
Anim.SetFloat("Direction", Input.GetAxis("Horizontal"));
Anim.SetBool("Moving", Input.GetKey(KeyCode.W));
Anim.SetBool("Sprinting", Input.GetKey(KeyCode.LeftShift));
}
}
EDIT: Nvm, see my fix above
Ahh, fixed it. All I needed to do was not set it to false, and also check for GetKeyDown instead of GetKey