JohnZ12
JohnZ12

Reputation: 183

How to send value from one class to another in C#?

I have void Start() with string snapshotJson declared inside of it, and I have private void LoadGameData() that needs to call the value of snapshotJson. Declaring snapshotJson public doesn't work, I assume because of void. From what I read I should be using getters and setters, but I have no idea how they work and every guide I've read explaining it makes it seem very simple, but they explain it so simply I don't understand how exactly I'm supposed to use it, or how I can call the value after using the get/set functions.

Could anyone explain how I can get the variable from one class to another? In my code, LoadGameData isn't able to call the value of snapshotJson, I'm not sure what I'm missing.

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;


}

Upvotes: 0

Views: 2351

Answers (3)

Allan Chua
Allan Chua

Reputation: 10195

The LoadGameData() method cannot access it from the Main() method because it is local to that function scope. However, you can pass the value from the Main() method to the LoadGameData() using the code below:

using System;
using System.Collections.Generic;
using System.Linq;
                
public class Program
{
    private static void LoadGameData(String input) {
        // Do something inside your input here.
    }

    public static void Main() {
      Start();
    }

    public static void Start()
    {
        string snapshotJson = "Sample data";
    
        // Same Class Call
        LoadGameData(snapshotJson);
    
        // Other Class Call
        var otherClassInstance = new TestClass();
    
        otherClassInstance.LoadGameData(snapshotJson);
    }
}

public class TestClass {
    public void LoadGameData(String input) {
        // Do something inside your input here.
    }
}

Upvotes: 1

Aaron Schaefer
Aaron Schaefer

Reputation: 1

If the variable snapshotJson is declared inside the body of the Start method, it will only be accessible within that method. If you want the variable to be accessible in other methods of your class, you may want to declare it as a member variable. This is how it looks like. You would need to declare it as a public property only if you need to access the value of snapshotJson outside of your class instance.

public class MyClass
{
  string snapshotJson;

  private void Start()
  {
      //  Assign value to snapshotJson here
      snapshotJson = "foo";
  }

  private void LoadGameData
  {
      //  Use value of snapshotJson here
      string s = snapshotJson;
  }
}

Upvotes: 0

Wolfgang Radl
Wolfgang Radl

Reputation: 2349

Assuming you refer to methods instead of classes (or rather: sharing data between objects), this is what you could do. Here's an example of a dedicated class for your Game objects, with SnaphopJson being a public property that can be accessed and changed from any other object. Changing the setter to private would ensure only it can only be read from anything but objects of this class.

public class Game
{
    public string SnapshotJson { get; set; }

    private void LoadGameData()
    {
        // load the json, e.g. by deserialization
        SnapshotJson = "{}";
    }

    public void Start()
    {
        // access the content of your snapshot
        var s = SnapshotJson;
    }

}

Upvotes: 0

Related Questions