【发布时间】:2018-10-03 17:09:44
【问题描述】:
我有 void Start(),其中声明了字符串 snapshotJson,我有私有 void LoadGameData() 需要调用 snapshotJson 的值。声明 snapshotJson public 不起作用,我认为是因为无效。从我读到的内容来看,我应该使用 getter 和 setter,但我不知道它们是如何工作的,而且我读过的每一篇解释它的指南都让它看起来很简单,但它们解释得如此简单,我不明白我到底是怎么做到的我应该使用它,或者在使用 get/set 函数后如何调用该值。
谁能解释我如何将变量从一个类传递到另一个类?在我的代码中,LoadGameData 无法调用 snapshotJson 的值,我不确定我缺少什么。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using System.IO;
using Firebase;
using Firebase.Unity.Editor;
using Firebase.Database;
using System;
public class DataController : MonoBehaviour
{
private RoundData[] allRoundData;
private PlayerProgress playerProgress;
[Serializable]
public class FirebaseStart : MonoBehaviour
{
public string snapshotJson { get; set; }
void Start()
{
// Set up the Editor before calling into the realtime database.
FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://FIREBASEDATABASE");
// Get the root reference location of the database.
DatabaseReference reference =
FirebaseDatabase.DefaultInstance.RootReference;
FirebaseDatabase.DefaultInstance
.GetReference("allRoundData")
.GetValueAsync().ContinueWith(task => {
if (task.IsFaulted)
{
// Handle the error...
}
else if (task.IsCompleted)
{
// DataSnapshot snapshot = task.Result;
snapshotJson = JsonUtility.ToJson(task.Result);
}
});
}
}
// Use this for initialization
void Start ()
{
DontDestroyOnLoad(gameObject);
LoadGameData();
LoadPlayerProgress();
SceneManager.LoadScene("MenuScreen");
}
public RoundData GetCurrentRoundData()
{
return allRoundData [0];
}
public void SubmitNewPlayerScore(int newScore)
{
if (newScore > playerProgress.highestScore)
{
playerProgress.highestScore = newScore;
SavePlayerProgress();
}
}
public int GetHighestPlayerScore()
{
return playerProgress.highestScore;
}
// Update is called once per frame
void Update () {
}
private void LoadPlayerProgress()
{
playerProgress = new PlayerProgress();
if (PlayerPrefs.HasKey("highestScore"))
{
playerProgress.highestScore = PlayerPrefs.GetInt("highestScore");
}
}
private void SavePlayerProgress()
{
PlayerPrefs.SetInt("highestScore", playerProgress.highestScore);
}
public void LoadGameData()
{
GameData loadedData = JsonUtility.FromJson<GameData>(snapshotJson);
Console.WriteLine(snapshotJson);
allRoundData = loadedData.allRoundData;
}
【问题讨论】:
-
嗨@JohnZ12,我可以看到你是 StackOverflow 的新手,我想欢迎你!如果您发现男生的回答很有帮助,您可以使用他们答案分数上的向上和向下图标来表示感谢。如果任何答案满足您的问题,请随时标记他们的答案以帮助其他有相同问题的人。干杯队友
标签: c#