Passing variable from one class to another

I have a project which I need to pass the players username and password to a player data c# file but whenever I attempt to do it I fail. In the project I have an input box for username and one for password. I get those data in two separate c# files. I want to merge these in one player data file as I said
but I don’t know how to do it (I know it is so easy for you guys. I have started game dev recently)

2 Answers

2

Passing data from one class to another is always a two step process.

  1. Get a reference to the class you want to talk to.
  2. Use some public interface on the target class pass the data.

There are several ways to do this. As you are just starting out, I will give an example of the most straightforward method (in my opinion).

For the class that wants to receive the data, you need to provide a public way to talk to the class. This could be as simple as a public method:

public class PlayerData : MonoBehaviour
{
    public void SetPlayerName(string name)
    {
        Debug.Log("SetPlayerName:: name = " + name);
    }
}

For the class providing the data, you need to get a reference to previous class. In some cases this can be done with the FindObjectOfType function, but it is often safer to set the reference explicitly in the editor so that you know you have the right object. Declaring a [SerializeField] or public variable in your class will add an entry in the Inspector where you can set the reference by dragging an object.

Once you have a reference to the target class, you can access its public function.

public class InputHandler : MonoBehaviour
{

    [SerializeField] private TMP_InputField inputField;
    [SerializeField] private PlayerData playerData;

    public void ReportData()
    {
        string playerName = inputField.text;
        playerData.SetPlayerName(playerName);
    }
}

This is what the inspector will look like and this is where you would drag the object that contains the target class.
image

question
do I need to fill all of these to reference the player data class?(I am talking about the Nicknamecollector and the Passwordcollector)

Yes, when you declare a public or [SerializeField] variable it does not point to anything by default. It will be a null reference until you define what it points to in the inspector.