简体   繁体   中英

How to communicate properly between unity c# scripts and android activity?

The whole system is not clear for me. Let's say I want to create a toast on a button click. How do I do that? I'm aware of the AndroidJavaClass, but in this case I need the activity for the toast. I can't make a jar out of the extended UnityPlayerActivity, or can I? (I also know about the way to create toast in unity, this question is not about that)

In reality I want to implement the firebase authentication. For this I need to get the user's email and a password. Of course I can easly create a scene in unity where I get those, but I need to call a createAccount method which can only be implemented in an activity (because we need the context)

Also I don't really want to create a plugin, because than I can't call back to the unity, or can I?

Actually it seems like the way I want will create only spaghetti. If anyone understand my problem and know a better solution, please help.

the createAccount method from firebase:

mAuth.createUserWithEmailAndPassword(email, password)
    .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if (task.isSuccessful()) {
                // Sign in success, update UI with the signed-in user's information
                Log.d(TAG, "createUserWithEmail:success");
                FirebaseUser user = mAuth.getCurrentUser();
                updateUI(user);
            } else {
                // If sign in fails, display a message to the user.
                Log.w(TAG, "createUserWithEmail:failure", task.getException());
                Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
                        Toast.LENGTH_SHORT).show();
                updateUI(null);
            }

            // ...
        }
    });

I would really recommend you to use the Firebase Unity SDK instead of trying to implement everything by yourself. See here for info on how to do authentication with the SDK: Get Started with Firebase Authentication in Unity

This is way easier, already battle-tested and then you also have multi-platform support right away.

Also I don't really want to create a plugin, because than I can't call back to the unity, or can I?

In case you really want to build your own native plugin to do this: yes, you can fairly easy communicated back to C# from native code. See example 3 about "UnitySendMessage" on this page: Unity - Manual: JAR plug-ins

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM