Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

What is wrong with my player move script? (C#)

Discussion in 'Editor & General Support' started by MeltingFire, May 15, 2020.

  1. MeltingFire

    MeltingFire

    Joined:
    Jan 22, 2020
    Posts:
    4
    Whenever I run this, Unity Freezes. I am pretty new to this skill. If you have any pointers on my code, or great ways to learn, I would love the input!
    ~Thanks.
    The Code:

    Code (CSharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. public class PlayerMove : MonoBehaviour
    7. {
    8.  
    9.     public float speed = 5f;
    10.     public Rigidbody2D rb;
    11.     private Vector2 Move;
    12.  
    13.     // Start is called before the first frame update
    14.     void Start()
    15.     {
    16.  
    17.      
    18.     }
    19.  
    20.     // Update is called once per frame
    21.     void Update()
    22.     //This should give a number for moving the player with a key input to use on the function below
    23.     {
    24.  
    25.         {
    26.             Move.x = 0; Move.y = 0;
    27.         }
    28.  
    29.         while (Input.GetKeyDown("w"))
    30.         {
    31.             Move.y = 1;
    32.         }
    33.  
    34.         while (Input.GetKeyDown("s"))
    35.         {
    36.             Move.y = -1;
    37.         }
    38.  
    39.         while (Input.GetKeyDown("a"))
    40.         {
    41.             Move.x = -1;
    42.         }
    43.  
    44.        while (Input.GetKeyDown("d"))
    45.         {
    46.             Move.x = 1;
    47.         }
    48.  
    49.  
    50.  
    51.     }
    52.  
    53.  
    54.     void FixedUpdate()
    55.         //This is the function for the movement
    56.     {
    57.         rb.MovePosition(rb.position + Move * speed * Time.fixedDeltaTime);
    58.  
    59.     }
    60. }
    61.  
     
    Last edited: May 15, 2020
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,888
    Replace all of your "while"s with "if"s. While is a loop: the code inside the while will keep running until the condition becomes false. But you are checking input in your conditions so it will never become false since you will never leave the current frame because you are stuck in your while loop!

    An if statement will run the code inside just once instead, which is what you want.
     
  3. MeltingFire

    MeltingFire

    Joined:
    Jan 22, 2020
    Posts:
    4