如何通过重启保留玩家皮肤

How to keep player skin through restart

我试图保留玩家皮肤,即使在重新加载场景或移动到新场景时也是如此。播放器对象会改变每个场景。

玩家皮肤是在暂停菜单中选择的,有三个按钮。这些按钮中的每一个都调用下面脚本中的一个函数。我正在尝试根据 PlayerPrefs int 所持有的值来调用其中一个函数,并且确实调用了该函数;但是抛出错误 MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it

以下是我已经尝试过的方法,但这会在场景重新加载时引发错误(死亡) 我不知道我在这里做错了什么。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement; 

public class Pausemenu : MonoBehaviour
{


    public static bool gameIsPaused = false;

    public GameObject pauseMenuUI;

    public Material BelgianMat;

    public Material Ball2;

    public Material Rainbow;

    public GameObject Player;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape)) {

            if (gameIsPaused) {
                Resume();
            } else {
                Pause();
            }

        }
    }
    public void Resume(){
        pauseMenuUI.SetActive(false);
        Time.timeScale = 1f;
        gameIsPaused = false;
    }

    void Pause() {
         pauseMenuUI.SetActive(true);
         Time.timeScale = 0f;
         gameIsPaused = true;
    }
    
    public void LoadMenu() {
        Time.timeScale = 1f;
        gameIsPaused = false;
        SceneManager.LoadScene("Menu");
    }

    public void QuitGame() {
        Debug.Log("Quitting");
        Application.Quit();
    }

    public void ApplyBelgian() {
        Player.GetComponent<Renderer>().material = BelgianMat;
        PlayerPrefs.SetInt("playerMat", 0);
    }

    public void ApplyBall2() {
        Player.GetComponent<Renderer>().material = Ball2;
        Debug.Log("Applied ball two");
        PlayerPrefs.SetInt("playerMat", 1);
    }

    public void ApplyRainbow() {
        Player.GetComponent<Renderer>().material = Rainbow;
        PlayerPrefs.SetInt("playerMat", 2);
        }

     void OnEnable()
    {
        Debug.Log("OnEnable called");
        SceneManager.sceneLoaded += OnSceneLoaded;
    }

    // called second
    void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {
        Debug.Log("OnSceneLoaded: " + scene.name);
        Debug.Log(mode);
        if (PlayerPrefs.GetInt("playerMat") == 0) {
            ApplyBelgian();
        } 
        else if (PlayerPrefs.GetInt("playerMat") == 1) {
            Debug.Log("gonna apply ball 2");
            ApplyBall2();
        } 
        else if (PlayerPrefs.GetInt("playerMat") == 2) {
            ApplyRainbow();
        }
    }
}

我不知道为什么,但似乎在加载场景后对 Player 对象的引用可能被破坏。如果是这种情况,请将“Player”标签添加到您的 Player 对象并将其添加到 OnEnable 函数:Player = GameObject.FindWithTag("Player");