I was trying to do a login and load script but this error occurred and I have looked through many tutorials but still don’t know how to fix this. Basically, it will switch to a loading screen when the function is activated.
Script:
static void LoadLevel(int sceneIndex)
{
StartCoroutine(LoadAsynchronously(sceneIndex));
}
IEnumerator LoadAsynchronously (int sceneIndex)
{
AsyncOperation operation = SceneManager.LoadSceneAsync(sceneIndex);
loadingScreen.SetActive(true);
mainScreen.SetActive(false);
optionsScreen.SetActive(false);
while (!operation.isDone)
{
float progress = Mathf.Clamp01(operation.progress / .9f);
slider.value = progress;
progressText.text = progress * 100f + "%";
yield return null;
}
}
So this is the function that I am trying to activate when something happened.
The code I made to activate this function: LoadLevel(2);
What I expect is that it will switch to the scene according to the scene index but instead, this error occured: (error CS0120: An object reference is required for the non-static field, method, or property ‘AuthManager.LoadAsynchronously(int)’)
The full script if you want:
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using Firebase;
using Firebase.Auth;
using TMPro;
using System.Threading.Tasks;
public class AuthManager : MonoBehaviour
{
public gameLoader gameLoader;
//Firebase variables
[Header("Firebase")]
public DependencyStatus dependencyStatus;
public FirebaseAuth auth;
public FirebaseUser User;
//Login variables
[Header("Login")]
public TMP_InputField emailLoginField;
public TMP_InputField passwordLoginField;
public TMP_Text warningLoginText;
public TMP_Text confirmLoginText;
//Register variables
[Header("Register")]
public TMP_InputField usernameRegisterField;
public TMP_InputField emailRegisterField;
public TMP_InputField passwordRegisterField;
public TMP_InputField passwordRegisterVerifyField;
public TMP_Text warningRegisterText;
[Header("Loading Screen")]
public GameObject loadingScreen;
public GameObject mainScreen;
public GameObject optionsScreen;
public TMPro.TMP_Text progressText;
public Slider slider;
static void LoadLevel(int sceneIndex)
{
StartCoroutine(LoadAsynchronously(sceneIndex));
}
IEnumerator LoadAsynchronously (int sceneIndex)
{
AsyncOperation operation = SceneManager.LoadSceneAsync(sceneIndex);
loadingScreen.SetActive(true);
mainScreen.SetActive(false);
optionsScreen.SetActive(false);
while (!operation.isDone)
{
float progress = Mathf.Clamp01(operation.progress / .9f);
slider.value = progress;
progressText.text = progress * 100f + "%";
yield return null;
}
}
void Awake()
{
//Check that all of the necessary dependencies for Firebase are present on the system
FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task =>
{
dependencyStatus = task.Result;
if (dependencyStatus == DependencyStatus.Available)
{
//If they are avalible Initialize Firebase
InitializeFirebase();
}
else
{
Debug.LogError("Could not resolve all Firebase dependencies: " + dependencyStatus);
}
});
}
private void InitializeFirebase()
{
Debug.Log("Setting up Firebase Auth");
//Set the authentication instance object
auth = FirebaseAuth.DefaultInstance;
}
//Function for the login button
public void LoginButton()
{
//Call the login coroutine passing the email and password
StartCoroutine(Login(emailLoginField.text, passwordLoginField.text));
}
//Function for the register button
public void RegisterButton()
{
//Call the register coroutine passing the email, password, and username
StartCoroutine(Register(emailRegisterField.text, passwordRegisterField.text, usernameRegisterField.text));
}
private IEnumerator Login(string _email, string _password)
{
//Call the Firebase auth signin function passing the email and password
Task<AuthResult> LoginTask = auth.SignInWithEmailAndPasswordAsync(_email, _password);
//Wait until the task completes
yield return new WaitUntil(predicate: () => LoginTask.IsCompleted);
if (LoginTask.Exception != null)
{
//If there are errors handle them
Debug.LogWarning(message: $"Failed to register task with {LoginTask.Exception}");
FirebaseException firebaseEx = LoginTask.Exception.GetBaseException() as FirebaseException;
AuthError errorCode = (AuthError)firebaseEx.ErrorCode;
string message = "Login Failed!";
switch (errorCode)
{
case AuthError.MissingEmail:
message = "Missing Email";
break;
case AuthError.MissingPassword:
message = "Missing Password";
break;
case AuthError.WrongPassword:
message = "Wrong Password";
break;
case AuthError.InvalidEmail:
message = "Invalid Email";
break;
case AuthError.UserNotFound:
message = "Account does not exist";
break;
}
warningLoginText.text = message;
}
else
{
//User is now logged in
//Now get the result
User = LoginTask.Result.User;
Debug.LogFormat("User signed in successfully: {0} ({1})", User.DisplayName, User.Email);
warningLoginText.text = "";
confirmLoginText.text = "Logged In";
LoadLevel(2);
}
}
private IEnumerator Register(string _email, string _password, string _username)
{
if (_username == "")
{
//If the username field is blank show a warning
warningRegisterText.text = "Missing Username";
}
else if(passwordRegisterField.text != passwordRegisterVerifyField.text)
{
//If the password does not match show a warning
warningRegisterText.text = "Password Does Not Match!";
}
else
{
//Call the Firebase auth signin function passing the email and password
Task<AuthResult> RegisterTask = auth.CreateUserWithEmailAndPasswordAsync(_email, _password);
//Wait until the task completes
yield return new WaitUntil(predicate: () => RegisterTask.IsCompleted);
if (RegisterTask.Exception != null)
{
//If there are errors handle them
Debug.LogWarning(message: $"Failed to register task with {RegisterTask.Exception}");
FirebaseException firebaseEx = RegisterTask.Exception.GetBaseException() as FirebaseException;
AuthError errorCode = (AuthError)firebaseEx.ErrorCode;
string message = "Register Failed!";
switch (errorCode)
{
case AuthError.MissingEmail:
message = "Missing Email";
break;
case AuthError.MissingPassword:
message = "Missing Password";
break;
case AuthError.WeakPassword:
message = "Weak Password";
break;
case AuthError.EmailAlreadyInUse:
message = "Email Already In Use";
break;
}
warningRegisterText.text = message;
}
else
{
//User has now been created
//Now get the result
User = RegisterTask.Result.User;
if (User != null)
{
//Create a user profile and set the username
UserProfile profile = new UserProfile{DisplayName = _username};
//Call the Firebase auth update user profile function passing the profile with the username
Task ProfileTask = User.UpdateUserProfileAsync(profile);
//Wait until the task completes
yield return new WaitUntil(predicate: () => ProfileTask.IsCompleted);
if (ProfileTask.Exception != null)
{
//If there are errors handle them
Debug.LogWarning(message: $"Failed to register task with {ProfileTask.Exception}");
FirebaseException firebaseEx = ProfileTask.Exception.GetBaseException() as FirebaseException;
AuthError errorCode = (AuthError)firebaseEx.ErrorCode;
warningRegisterText.text = "Username Set Failed!";
}
else
{
//Username is now set
//Now return to login screen
warningRegisterText.text = "";
confirmLoginText.text = "Successfully registered!";
usernameRegisterField.text = "";
emailRegisterField.text = "";
passwordRegisterField.text = "";
passwordRegisterVerifyField.text = "";
}
}
}
}
}
}