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

Question GameObject keeps moving forward even after releasing the key

Discussion in '2D' started by dollarmonk07, Dec 2, 2022.

  1. dollarmonk07

    dollarmonk07

    Joined:
    Oct 9, 2022
    Posts:
    1
    So here's what I'm trying to do:
    You click on player one, and then control/move that player. You click on player two, then you control that and not control player one.

    Here's what is happening:
    When I click on player one and move it, it moves. But when I leave the key and click on player two, player one still keeps moving.

    Here's a video that shows the problem:


    I've created two scripts:
    Movement script (which is on Player)
    GameManager script (which is on game manager)

    Here are the scripts:

    Movement
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Movement : MonoBehaviour
    6. {
    7.     float inputX;
    8.     Rigidbody2D rb;
    9.     [SerializeField] float jumpPower;
    10.  
    11.     public Transform GroundCheck;
    12.     public LayerMask GroundLayer;
    13.     bool isGrounded;
    14.  
    15.     private AudioSource audioSource;
    16.     public AudioClip jumpSound;
    17.  
    18.     bool isSelected = false;
    19.  
    20.     GameManager gameManager;
    21.  
    22.     void Start()
    23.     {
    24.          Application.targetFrameRate = 60;
    25.          rb = GetComponent<Rigidbody2D>();
    26.          audioSource = GetComponent<AudioSource>();
    27.  
    28.          gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
    29.     }
    30.    
    31.     // Update is called once per frame
    32.     void Update()
    33.     {
    34.         if(isSelected)
    35.         {
    36.             inputX = Input.GetAxis("Horizontal");
    37.             if(Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.A))
    38.             {
    39.                 transform.rotation = Quaternion.Euler(0,180f,0);
    40.             }else if(Input.GetKeyDown(KeyCode.RightArrow) || Input.GetKeyDown(KeyCode.D))
    41.             {
    42.                 transform.rotation = Quaternion.Euler(0,0,0);
    43.             }
    44.  
    45.             isGrounded = Physics2D.OverlapCapsule(GroundCheck.position,new Vector2(0.5f,0.3f),CapsuleDirection2D.Horizontal,0,GroundLayer);
    46.  
    47.             if(Input.GetKeyDown(KeyCode.Space) && isGrounded)
    48.             {
    49.                 rb.velocity = Vector2.up * jumpPower;
    50.                 audioSource.PlayOneShot(jumpSound);
    51.             }
    52.  
    53.             rb.velocity = new Vector2(inputX*200f*Time.deltaTime,rb.velocity.y);
    54.         }
    55.          
    56.     }
    57.  
    58.     private void FixedUpdate() {
    59.        
    60.     }
    61.  
    62.     public void DeselectPlayer()
    63.     {
    64.         isSelected = false;
    65.     }
    66.  
    67.     private void OnMouseDown() {
    68.         gameManager.DeselectAllPlayers();
    69.         isSelected = true;
    70.     }
    71. }
    72.  
    GameManager
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class GameManager : MonoBehaviour
    6. {
    7.     public GameObject[] Players;
    8.  
    9.     public void DeselectAllPlayers()
    10.     {
    11.         for(int i = 0;i<Players.Length;i++)
    12.         {
    13.             Players[i].GetComponent<Movement>().DeselectPlayer();
    14.         }
    15.     }
    16. }
    17.  
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,514
    Looks like perhaps
    isSelected
    is false, which ignores all input.

    Instead:

    - read the input and set a temporary variable with how you want to move

    - only put that variable into the player's movement when it is selected.

    If that isn't it, then here is how you can get more information about what is happening:

    You must find a way to get the information you need in order to reason about what the problem is.

    Once you understand what the problem is, you may begin to reason about a solution to the problem.

    What is often happening in these cases is one of the following:

    - the code you think is executing is not actually executing at all
    - the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is
    - you're getting an error or warning and you haven't noticed it in the console window

    To help gain more insight into your problem, I recommend liberally sprinkling
    Debug.Log()
    statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?
    - are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

    Knowing this information will help you reason about the behavior you are seeing.

    You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as
    Debug.Log("Problem!",this);


    If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

    You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

    You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: https://forum.unity.com/threads/how-to-capturing-device-logs-on-ios.529920/ or this answer for Android: https://forum.unity.com/threads/how-to-capturing-device-logs-on-android.528680/

    Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494

    When in doubt, print it out!(tm)

    Note: the
    print()
    function is an alias for Debug.Log() provided by the MonoBehaviour class.

    Remember the first rule of GameObject.Find():

    Do not use GameObject.Find();

    More information: https://starmanta.gitbooks.io/unitytipsredux/content/first-question.html

    More information: https://forum.unity.com/threads/why-cant-i-find-the-other-objects.1360192/#post-8581066