[Picture]我正在开发游戏,并试图创建一个保存和加载按钮。我相信自己编码正确,但是我的问题是找不到想要访问的播放器。我怀疑它与我编写代码的方式有关。
由于具有多个级别,因此我使用了以下代码:
GameObject player = GameObject.FindWithTag(“ Player”);尝试在场景中找到给定的球员,但我认为这没有用。
我没有将播放器设置为公共变量,因为它在每个场景中都会发生变化。
例如,我尝试使用以下代码访问玩家当前的健康状况,这些代码保存在名为Gamecontrol.cs的脚本中的GameController空游戏对象中:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using UnityEngine.SceneManagement;
public class GameControl : MonoBehaviour {
public static GameControl controller;
int shooterHealth;
int shooterScore;
//public GameObject player;
//public GameObject gun;
int level;
// Use this for initialization
void Awake() {
GameObject player = GameObject.FindWithTag("Player");
shooterHealth = player.GetComponent<PlayerHealth>().currentHealth;
shooterScore = player.GetComponent<Gun>().score;
level = player.GetComponent<PlayerHealth>().level;
if(controller == null) {
DontDestroyOnLoad(gameObject);
controller = this;
}
else if(controller != this) {
Destroy(gameObject);
}
}
public void SaveGame() {
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/shooter.dat");
PlayerData data = new PlayerData();
data.shooterHealth = shooterHealth;
data.shooterScore = shooterScore;
data.level = level;
bf.Serialize(file, data);
file.Close();
}
public void LoadGame() {
if(File.Exists(Application.persistentDataPath + "/shooter.dat"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/shooter.dat", FileMode.Open);
PlayerData data = (PlayerData)bf.Deserialize(file);
file.Close();
GameObject player = GameObject.FindWithTag("Player");
player.GetComponent<PlayerHealth>().currentHealth = data.shooterHealth;
player.GetComponent<Gun>().score = data.shooterScore;
level = player.GetComponent<PlayerHealth>().level;
SceneManager.LoadScene(level);
}
}
}
[Serializable]
class PlayerData
{
public int shooterHealth;
public int shooterScore;
public int level;
}
我得到的错误是:
NullReferenceException:对象引用未设置为对象的实例
GameControl.Awake()(位于Assets / GameControl.cs:20)
有谁知道解决这个问题的方法吗?先感谢您:)
最佳答案
错误在shooterScore = player.GetComponent<Gun>().score;
中
您正在尝试访问组件Gun
,但是Player GameObject没有附加的Gun
组件。也许您忘记了附加它,或者它有另一个名字。
也许您在运行时附加了Gun
组件。在这种情况下,请检查脚本执行顺序以验证在运行时附加GameControl
组件的脚本之后是否已执行Gun
脚本。
关于c# - 如何找到标记为“玩家”的GameObject,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55418552/