简体   繁体   中英

Unity - How do I increase a value while a key is held down?

   public int power;
// Start is called before the first frame update
void Start()
{
    player = GameObject.Find("Whyareyoulikethis");
    while (Input.GetKey(KeyCode.Space))
    {
        power = power + 10;
    }

    // Places the ball at the player's current position.
    transform.Translate(-player.transform.forward);
        rb = GetComponent<Rigidbody>();
        rb.AddForce(-player.transform.forward * power);
}

What this is meant to do is while the space key is held down, power will increase by 10. Unfortunately, this does absolutely nothing. When the ball is spawned, it simply just drops down with no force added whatsoever. I have also tried GetKeyUp and GetKeyDown as opposed to Getkey, but they made no difference to the final result. I have also tried this in an if statement under void Update(), but the same happened. As stupid as it was, I also tried it in its while statement under void Update() and crashed the engine as expected.

That while loop blocks your game until it is done. So as soon as you enter it you will never come out since the Input is not updated inside of your while loop.

Also it makes no sense in Start which is only called once when your GameObject is initialized and the space key won't be pressed there.

Move the check for Input.GetKey it to Update which is called every frame.

Than Cid's comment is correct and this will increase the power quite fast and frame dependent. You probably want to increase rather with a frame-independent 60/second so rather use Time.deltaTime

in this case power should be a float instead

Than it depends where the rest should be executed but I guess eg at button up

public float power;

private void Start()
{
    player = GameObject.Find("Whyareyoulikethis");
    rb = GetComponent<Rigidbody>();
}

private void Update()
{
    if(Input.GetKey(KeyCode.Space))
    {
        power += 10 * Time.deltaTime;
    }

    if(Input.GetKeyUp(KeyCode.Space))
    {
        // Places the ball at the player's current position
        transform.position = player.transform.position;
        // you don't want to translate it but set it to the players position here

        // rather than using addforce you seem to simply want to set a certain velocity
        // though I don't understand why you shoot backwards...
        rb.velocity = -player.transform.forward * power;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM