OGeek|极客世界-中国程序员成长平台

标题: c# - 暂停不起作用(Unity c#) [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 15:28
标题: c# - 暂停不起作用(Unity c#)

我在 Unity (C#) 上为手机编写运行游戏。

我使用 Canvas - Button 在屏幕上制作了暂停按钮。

我还在 Platformer2DUserControl 脚本中为 Pause 编写了代码。

这里是这个脚本的代码:

   using UnityEngine;
using UnitySampleAssets.CrossPlatformInput;

namespace UnitySampleAssets._2D
{

    [RequireComponent(typeof(PlatformerCharacter2D))]
    public class Platformer2DUserControl : MonoBehaviour
    {
        private PlatformerCharacter2D character;
        private bool jump;
        public bool paused;

        private void Awake()
        {
            character = GetComponent<latformerCharacter2D>();
            paused = false;
        }

        private void Update()
        {

            /*if (Input.GetButton("Fire1"))
            {

            }*/


            if (!jump)
                // Read the jump input in Update so button presses aren't missed.
                 jump = Input.GetButton("Fire1"); //&& CrossPlatformInputManager.GetButtonDown("Jump"); 


        }

        private void FixedUpdate()
        {
            // Read the inputs.
            bool crouch = Input.GetKey(KeyCode.LeftControl);
            // float h = CrossPlatformInputManager.GetAxis("Horizontal");
            // Pass all parameters to the character control script.
            character.Move(1, false, jump);
            jump = false;

        }
        public void Pause()

        {
            if (!jump)
                // Read the jump input in Update so button presses aren't missed.
                jump = Input.GetButton("Fire1"); //&& CrossPlatformInputManager.GetButtonDown("Jump");

            paused = !paused;


            if (paused)
            {
                jump = !jump;
                Time.timeScale = 0;

            }
            else if (!paused)
            {
               // jump = Input.GetButton("Fire1");
                Time.timeScale = 1;
            }
        }
    }
}

我的暂停按钮运行良好。但是当我点击它时,我的角色正在跳跃并且游戏正在暂停。

我想做到这一点,当我点击按钮时游戏只是暂停并且角色不会跳跃。

我怎样才能做到。谢谢你的帮助。



Best Answer-推荐答案


我建议您不要使用相同的输入来进行跳跃和暂停。此外,将您的跳转和暂停功能分离为单独的功能。对于暂停,在屏幕上创建一个 UI 按钮并使其调用暂停脚本上的公共(public)函数,这将切换暂停。然后,在同一个函数中,检查您是否暂停并相应地调整 Time.timescale

您必须将具有暂停功能的脚本附加到始终位于屏幕中的对象(例如, Canvas 或 MainCamera 中的面板)。在按钮下,将带有apt脚本的GO拖到框后添加一个新的onClick()函数。然后,选择前面提到的公共(public)函数。

private bool paused = false;

//The function called by the button OnClick()
public void TogglePause()
{
    paused = !paused;

    if(paused)
        Time.timescale = 0f;
    else
        Time.timescale = 1f;
}

希望这有帮助!

关于c# - 暂停不起作用(Unity c#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36161594/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4