Firebase Authentication을 사용하면 사용자가 게임에 로그인할 때 이메일 주소와 비밀번호를 통한 로그인 방법이나 Google 로그인, Facebook 로그인과 같은 제휴 ID 공급업체를 통한 로그인 등 1개 이상의 로그인 방법을 사용하여 로그인할 수 있습니다. 이 튜토리얼에서는 Firebase Authentication을 시작할 수 있도록 게임에 이메일 주소와 비밀번호를 통한 로그인을 추가하는 방법을 보여줍니다.
Unity 프로젝트에 Firebase를 추가할 때 Firebase Console 및 열려 있는 Unity 프로젝트 모두에서 작업을 수행해야 합니다. 예를 들어 Console에서 Firebase 구성 파일을 다운로드한 후 이 파일을 Unity 프로젝트로 이동하는 작업이 필요합니다.
신규 사용자 가입
신규 사용자가 자신의 이메일 주소와 비밀번호를 사용해 게임에 가입할 수 있는 양식을 만듭니다. 사용자가 양식을 작성하면 사용자가 입력한 이메일 주소와 비밀번호의 유효성을 검사한 후 CreateUserWithEmailAndPasswordAsync 메서드에 전달합니다.
auth.CreateUserWithEmailAndPasswordAsync(email,password).ContinueWith(task=>{if(task.IsCanceled){Debug.LogError("CreateUserWithEmailAndPasswordAsync was canceled.");return;}if(task.IsFaulted){Debug.LogError("CreateUserWithEmailAndPasswordAsync encountered an error: "+task.Exception);return;}// Firebase user has been created.Firebase.Auth.AuthResultresult=task.Result;Debug.LogFormat("Firebase user created successfully: {0} ({1})",result.User.DisplayName,result.User.UserId);});
기존 사용자 로그인
기존 사용자가 자신의 이메일 주소와 비밀번호를 사용해 로그인할 수 있는 양식을 만듭니다. 사용자가 양식을 작성하면 SignInWithEmailAndPasswordAsync 메서드를 호출합니다.
auth.SignInWithEmailAndPasswordAsync(email,password).ContinueWith(task=>{if(task.IsCanceled){Debug.LogError("SignInWithEmailAndPasswordAsync was canceled.");return;}if(task.IsFaulted){Debug.LogError("SignInWithEmailAndPasswordAsync encountered an error: "+task.Exception);return;}Firebase.Auth.AuthResultresult=task.Result;Debug.LogFormat("User signed in successfully: {0} ({1})",result.User.DisplayName,result.User.UserId);});
인증 상태 변경 이벤트 핸들러 설정 및 사용자 데이터 가져오기
로그인 및 로그아웃 이벤트에 응답하려면 전역 인증 객체에 이벤트 핸들러를 연결합니다. 사용자의 로그인 상태가 변경될 때마다 이 핸들러가 호출됩니다. 인증 객체가 완전히 초기화되고 네트워크 호출이 완료된 후에만 핸들러가 실행되므로 전역 인증 객체는 로그인한 사용자에 대한 정보를 가져오기에 가장 적합한 위치입니다.
FirebaseAuth 객체의 StateChanged 필드를 사용해 이벤트 핸들러를 등록합니다. 사용자가 로그인되면 이벤트 핸들러에서 사용자에 대한 정보를 가져올 수 있습니다.
마지막으로 이 객체에 Destroy가 호출되면 자동으로 OnDestroy를 호출합니다. OnDestroy에서 인증 객체의 참조를 삭제합니다.
voidInitializeFirebase(){auth=Firebase.Auth.FirebaseAuth.DefaultInstance;auth.StateChanged+=AuthStateChanged;AuthStateChanged(this,null);}voidAuthStateChanged(objectsender,System.EventArgseventArgs){if(auth.CurrentUser!=user){boolsignedIn=user!=auth.CurrentUser && auth.CurrentUser!=null && auth.CurrentUser.IsValid();if(!signedIn && user!=null){DebugLog("Signed out "+user.UserId);}user=auth.CurrentUser;if(signedIn){DebugLog("Signed in "+user.UserId);displayName=user.DisplayName??"";emailAddress=user.Email??"";photoUrl=user.PhotoUrl??"";}}}voidOnDestroy(){auth.StateChanged-=AuthStateChanged;auth=null;}
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-08-08(UTC)"],[],[],null,["You can use Firebase Authentication to allow users to sign in to your game using one\nor more sign-in methods, including email address and password sign-in, and\nfederated identity providers such as Google Sign-in and Facebook Login. This\ntutorial gets you started with Firebase Authentication by showing you how to add\nemail address and password sign-in to your game.\n\nBefore you begin\n\nBefore you can use\n[Firebase Authentication](/docs/reference/unity/namespace/firebase/auth),\nyou need to:\n\n- Register your Unity project and configure it to use Firebase.\n\n - If your Unity project already uses Firebase, then it's already\n registered and configured for Firebase.\n\n - If you don't have a Unity project, you can download a\n [sample app](//github.com/google/mechahamster).\n\n- Add the [Firebase Unity SDK](/download/unity) (specifically, `FirebaseAuth.unitypackage`) to\n your Unity project.\n\n| **Find detailed instructions for these initial\n| setup tasks in\n| [Add Firebase to your Unity project](/docs/unity/setup#prerequisites).**\n\nNote that adding Firebase to your Unity project involves tasks both in the\n[Firebase console](//console.firebase.google.com/) and in your open Unity project\n(for example, you download Firebase config files from the console, then move\nthem into your Unity project).\n\nSign up new users\n\nCreate a form that allows new users to register with your game using their email\naddress and a password. When a user completes the form, validate the email\naddress and password provided by the user, then pass them to the\n`CreateUserWithEmailAndPasswordAsync` method: \n\n auth.CreateUserWithEmailAndPasswordAsync(email, password).ContinueWith(task =\u003e {\n if (task.IsCanceled) {\n Debug.LogError(\"CreateUserWithEmailAndPasswordAsync was canceled.\");\n return;\n }\n if (task.IsFaulted) {\n Debug.LogError(\"CreateUserWithEmailAndPasswordAsync encountered an error: \" + task.Exception);\n return;\n }\n\n // Firebase user has been created.\n Firebase.Auth.AuthResult result = task.Result;\n Debug.LogFormat(\"Firebase user created successfully: {0} ({1})\",\n result.User.DisplayName, result.User.UserId);\n });\n\nSign in existing users\n\nCreate a form that allows existing users to sign in using their email address\nand password. When a user completes the form, call the\n`SignInWithEmailAndPasswordAsync` method: \n\n auth.SignInWithEmailAndPasswordAsync(email, password).ContinueWith(task =\u003e {\n if (task.IsCanceled) {\n Debug.LogError(\"SignInWithEmailAndPasswordAsync was canceled.\");\n return;\n }\n if (task.IsFaulted) {\n Debug.LogError(\"SignInWithEmailAndPasswordAsync encountered an error: \" + task.Exception);\n return;\n }\n\n Firebase.Auth.AuthResult result = task.Result;\n Debug.LogFormat(\"User signed in successfully: {0} ({1})\",\n result.User.DisplayName, result.User.UserId);\n });\n\nSet an authentication state change event handler and get user data\n\nTo respond to sign-in and sign-out events, attach an event handler to the global\nauthentication object. This handler gets called whenever the user's sign-in\nstate changes. Because the handler runs only after the authentication object is\nfully initialized and after any network calls have completed, it is the best\nplace to get information about the signed-in user.\n\nRegister the event handler using the `FirebaseAuth` object's `StateChanged`\nfield. When a user successfully signs in, you can get information about the user\nin the event handler.\n\nFinally, when this object has `Destroy` called on it, it will automatically call\n`OnDestroy`. Clean up the Auth object's references in `OnDestroy`. \n\n void InitializeFirebase() {\n auth = Firebase.Auth.FirebaseAuth.DefaultInstance;\n auth.StateChanged += AuthStateChanged;\n AuthStateChanged(this, null);\n }\n\n void AuthStateChanged(object sender, System.EventArgs eventArgs) {\n if (auth.CurrentUser != user) {\n bool signedIn = user != auth.CurrentUser && auth.CurrentUser != null\n && auth.CurrentUser.IsValid();\n if (!signedIn && user != null) {\n DebugLog(\"Signed out \" + user.UserId);\n }\n user = auth.CurrentUser;\n if (signedIn) {\n DebugLog(\"Signed in \" + user.UserId);\n displayName = user.DisplayName ?? \"\";\n emailAddress = user.Email ?? \"\";\n photoUrl = user.PhotoUrl ?? \"\";\n }\n }\n }\n\n void OnDestroy() {\n auth.StateChanged -= AuthStateChanged;\n auth = null;\n }\n\nNext steps\n\nLearn how to add support for other identity providers and anonymous guest\naccounts:\n\n- [Google Sign-in](/docs/auth/unity/google-signin)\n- [Facebook Login](/docs/auth/unity/facebook-login)\n- [Twitter Login](/docs/auth/unity/twitter-login)\n- [GitHub Login](/docs/auth/unity/github-auth)\n- [Microsoft Login](/docs/auth/cpp/microsoft-oauth)\n- [Yahoo Login](/docs/auth/cpp/yahoo-oauth)\n- [Anonymous sign-in](/docs/auth/unity/anonymous-auth)\n- [Phone Authentication](/docs/auth/unity/phone-auth)"]]