My solution to Debug Keys

I’ve put the Debug Keys into a separate script, also added Level Reload. For some reason collision toggling is inconsistent. Could this be because it’s in a separate script from movement? I’ve noticed it’s most inconsistent while in-motion. So when Spacebar or A/D are pushed down.

using UnityEngine.SceneManagement;
using UnityEngine;

public class DebugKeys : MonoBehaviour
{
    Collider boxCollider;

    void Start()
    {
        boxCollider = GetComponent<Collider>();    

    }

    void Update()
    {
        DebugActions();
    }

    void DebugActions() {
        if (Input.GetKey(KeyCode.L))
        {
            LoadNextLevel();
        }
        if (Input.GetKey(KeyCode.P))
        {
            ReloadLevel();
        }
        if (Input.GetKey(KeyCode.C))
        {
            ColliderToggle();
        }

    }

    private void ColliderToggle()
    {
        boxCollider.enabled = !boxCollider.enabled;
        Debug.Log("Collider.enabled = " + boxCollider.enabled);
    }

    void ReloadLevel() 
    {
        int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
        SceneManager.LoadScene(currentSceneIndex);
    }

    void LoadNextLevel() 
    {
        int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
        int nextSceneIndex = currentSceneIndex +1;
        if(nextSceneIndex == SceneManager.sceneCountInBuildSettings) 
        {
            nextSceneIndex = 0;   
        }
        SceneManager.LoadScene(nextSceneIndex);
    }
}

What do you mean by this?

Very unlikely.

When flying, while I press “C”, sometimes collision turns off, and sometimes it doesn’t. And it’s very inconsistent. Like 3 times out of five it will turn off, but the 2 times it won’t. Although after doing some more testing I’ve also noticed that it sometimes doesn’t toggle on the Launching Pad either, even though I’m not pressing any other keys at the time. So I’m at a loss.

Not a big deal, just a bit weird.

This is likely because you used Input.GetKey(KeyCode.C). Frames are usually much faster than you can press and release a button, so ColliderToggle() is being called several times when you press the key. The collider is toggled off in this frame , then on in the next frame, then off again in the frame after that, etc. until the key is no longer pressed, at which point it will be in whatever state the last toggle put it. You should be using Input.GetKeyDown(KeyCode.C). Then the toggle will only happen on the frame where you pressed the key. In subsequent frames it will no longer execute, even if the key is still pressed.

2 Likes

As Bix said, this is the answer to your issue.

Privacy & Terms