I'd like to know why this error happens in the code below.
I assigned the correspondent GO's (Game Objects) in the inspector.
PhotonNetwork.ConnectUsingSettings, OnConnectedToMaster, OnJoinedLobby working ok
The method On_PlayerNameInput_changed() already assigned to PlayerName InputField in hierarchy (and PlayerName InputField as PlayerNameScreen's child).
GO's attached to MenuManager GO slots
Now, I have this code
public class MenuManager : MonoBehaviourPunCallbacks
{
[SerializeField] private GameObject connectScreen, playerNameScreen, playerNameButton;
[SerializeField] private InputField createRoomInput, joinRoomInput, playerNameInput;
public void OnClick_PlayerNameButton()
{
PhotonNetwork.NickName = playerNameInput.text;
}
public void On_PlayerNameInput_changed()
{
if (playerNameInput.text.Length > 2 && playerNameInput.text.Length < 11)
playerNameButton.SetActive(true);
else
playerNameButton.SetActive(false);
}
And no warning is shown, but if I do the next:
public void On_PlayerNameInput_changed()
{
if (playerNameInput != null)
{
if (playerNameInput.text.Length > 2 && playerNameInput.text.Length < 11)
playerNameButton.SetActive(true);
else
playerNameButton.SetActive(false);
}
else
Debug.Log("PlayerNameInput is null");
}
Immediately appear the next warning messages:
Assets\Scripts\MenuManager.cs(11,57): warning CS0649: Field 'MenuManager.playerNameButton' is never assigned to, and will always have its default value null
Assets\Scripts\MenuManager.cs(14,56): warning CS0649: Field 'MenuManager.playerNameInput' is never assigned to, and will always have its default value null
Assets\Scripts\MenuManager.cs(11,39): warning CS0649: Field 'MenuManager.playerNameScreen' is never assigned to, and will always have its default value null
And as shown in the picture, the GO's are already dragged and dropped in the MenuManager slots.
Thanks for any help.
As it says, you have created symbols which are always going to be null. There is nothing here that would ever assign an instance of an object to the symbols mentioned in the warnings.
You need to either construct objects and assign them to those symbols before you try to use them, or you can make the fields public and assign a constructed object from the outside. As it is, the compiler correctly assumes that a declared private symbol that is never assigned to a constructed object is going to throw a null-reference exception at runtime when you try to operate on it.
If you don't yet understand the concepts of reference and instance in C#, then that's the concept to read up on. A symbol is always "null" unless something creates, then assigns, a runtime instance of an object.