如何找到标记为“玩家”的GameObject

时间:2019-03-29 13:30:10

标签: c# unity3d

[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)

有人知道这种方法吗?预先谢谢您:)

1 个答案:

答案 0 :(得分:0)

错误在shooterScore = player.GetComponent<Gun>().score;中 您正在尝试访问组件Gun,但是Player GameObject没有附加Gun组件。也许您忘记附加它了,或者它有另一个名字。

也许您在运行时附加了Gun组件。在这种情况下,请检查脚本执行顺序以验证在运行时附加了GameControl组件的脚本之后,是否执行了Gun脚本。

相关问题