unity做单机游戏,按键修改,更换场景或者退出游戏,按键依旧保存

在Unity中制作单机游戏时,如何确保按键设置在更换场景或退出游戏后仍能保存?本文分享作者在毕业设计过程中的心得,介绍如何定义新的按键并使用PlayerPrefs保存用户设置。代码示例中,通过KeyCode和PlayerPrefs实现按键的持久化保存,需要注意变量的赋值方式和使用条件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

unity做单机游戏,按键修改,更换场景按键依旧保存(做毕业设计过程中的一些心得,第一次发文,有错误的敬请谅解)


定义新按键
KeyCode newKey;
newKey= (KeyCode)System.Enum.Parse(typeof(KeyCode), PlayerPrefs.GetString(“forward”, “W”));

直接上代码(说明一点,有的东西定义的是public公有类型的变量,需要自己在unity里赋值,最好看一下代码,然后根据条件来使用),

//自定义按键代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ChangeKey : MonoBehaviour {
    //这里本来是能定义按钮的,但是我的Unity出了点毛病,暂时这样了
    public GameObject  forward;
    public GameObject back;
    public GameObject left;
    public GameObject right;
    public GameObject attack;
    public GameObject skill1;
    public GameObject skill2;
    public GameObject skill3;
    //定义的新按键
    KeyCode backkey;
    KeyCode forwardkey;
    KeyCode rightkey;
    KeyCode leftkey;
    KeyCode attackkey;
    KeyCode skill1key;
    KeyCode skill2key;
    KeyCode skill3key;
   //临时按键
    KeyCode curKey;
   //新的按键
    KeyCode newKey;
    //存储按键的事件名称
    string functionName = string.Empty;
    //临时按钮
    GameObject  currentBtn;
    void Awake()
    {
        GetBindKeys();
    }
    bool isPlaying = true;
    bool isWaitingForKey = false;
    //切换按键的输入与显示
    void OnGUI()
    {
        if (isWaitingForKey)
        {
            Event e = Event.current;
            if (e.isKey)
            {
                newKey = e.keyCode;
                currentBtn.transform.Find("Text").GetComponent<Text>().text = newKey.ToString();
                PlayerPrefs.SetString(functionName, newKey.ToString());
                isWaitingForKey = false;
                //call when config has changed
                GetBindKeys();
                StartCoroutine(WaitUpdate());
            }
        }
    }

    IEnumerator WaitUpdate()
    {
        yield return new WaitForEndOfFrame();
        isPlaying = true;
    }
    //按钮事件,需要给按钮手动添加事件
    public  void ForwardBtnClick()
    {
        currentBtn = forward;
        isPlaying = false;
        currentBtn.transform.Find("Text").GetCo
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值