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

问题描述

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

在带有三个按钮的暂停菜单中选择播放器皮肤。这些按钮中的每个按钮都在下面的脚本中调用一个函数。我试图根据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");