如何从另一个脚本调用函数?

时间:2018-10-05 16:37:14

标签: c#

我已经阅读了一堆有关如何执行此操作的指南,但是对于编程新手来说,我并没有真正理解它。

我有一个名为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);
}

0 个答案:

没有答案