首页 > 解决方案 > 如何从另一个脚本调用函数?

问题描述

我已经阅读了很多关于如何做到这一点的指南,但是作为编程新手,我并没有真正理解它。

我有一个名为 DatabaseHandler 的脚本,我在其中编写了一个新类和函数,用于在有人创建新帐户时将一些基本用户信息写入 Firebase 数据库。

DatabaseReference userRef = FirebaseDatabase.DefaultInstance.RootReference;
public class User
{
    public string email;
    public int score;
    public int round;
    public int lives;

    public User()
    {
    }

    public User(string email)
    {
        this.email = email;
        this.score = 0;
        this.round = 1;
        this.lives = 3;
    }
}

public void writeNewUser(string email, int score, int round, int lives)
{
    User user = new User(email);
    string json = JsonUtility.ToJson(user);

    userRef.Child("users").Child(email).SetRawJsonValueAsync(json);
}

此外,我还有另一个名为 LoginHandler 的脚本,当有人单击按钮创建帐户时,它会调用 CreateUserAsync()。我正在使用我在这部分的在线指南上找到的代码片段,并试图弄清楚我可以在哪里以及如何从 LoginHandler 中调用在 DatabaseHandler 中编写的 writeNewUser 函数?我是否应该在 auth.CurrentUser != null 之后从 Task HandleCreateUserAsync 调用它以确保仅在尚未创建用户名的情况下才写入数据?

public void CreateUserAsync() {
DebugLog(String.Format("Attempting to create user {0}...", email));

// This passes the current displayName through to HandleCreateUserAsync
// so that it can be passed to UpdateUserProfile().  displayName will be
// reset by AuthStateChanged() when the new user is created and signed in.
string newDisplayName = displayName;
auth.CreateUserWithEmailAndPasswordAsync(email, password)
  .ContinueWith((task) => {
    return HandleCreateUserAsync(task, newDisplayName: newDisplayName);
  }).Unwrap();
 }

 Task HandleCreateUserAsync(Task<Firebase.Auth.FirebaseUser> authTask,
                         string newDisplayName = null) {
 if (LogTaskCompletion(authTask, "User Creation")) {
  if (auth.CurrentUser != null) {
    DebugLog(String.Format("User Info: {0}  {1}", auth.CurrentUser.Email,
                           auth.CurrentUser.ProviderId));
    return UpdateUserProfileAsync(newDisplayName: newDisplayName);
  }
}
// Nothing to update, so just return a completed Task.
return Task.FromResult(0);
}

标签: c#

解决方案


推荐阅读