تنظيم صفحاتك في مجموعات
يمكنك حفظ المحتوى وتصنيفه حسب إعداداتك المفضّلة.
يمكنك استخدام Firebase Authentication للسماح للمستخدمين بتسجيل الدخول إلى لعبتك باستخدام طريقة واحدة أو أكثر من طرق تسجيل الدخول، بما في ذلك تسجيل الدخول باستخدام عنوان البريد الإلكتروني وكلمة المرور، وموفّري خدمات الهوية الموحّدة، مثل "تسجيل الدخول باستخدام Google" و"تسجيل الدخول باستخدام Facebook". يساعدك هذا البرنامج التعليمي في بدء استخدام Firebase Authentication من خلال توضيح كيفية إضافة ميزة تسجيل الدخول باستخدام عنوان البريد الإلكتروني وكلمة المرور إلى لعبتك.
سجِّل مشروع Unity الخاص بك وأعدَّه لاستخدام Firebase.
إذا كان مشروع Unity يستخدم Firebase، يكون قد تم تسجيله وإعداده لاستخدام Firebase.
إذا لم يكن لديك مشروع Unity، يمكنك تنزيل تطبيق نموذجي.
أضِف FirebaseUnity SDK (FirebaseAuth.unitypackage تحديدًا) إلى مشروع Unity.
يُرجى العِلم أنّ إضافة Firebase إلى مشروع Unity يتضمّن مهامًا في كل من
وحدة تحكّم Firebase ومشروع Unity المفتوح (على سبيل المثال، يمكنك تنزيل ملفات إعداد 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);});
ضبط معالج أحداث لتغيير حالة المصادقة والحصول على بيانات المستخدم
للردّ على أحداث تسجيل الدخول وتسجيل الخروج، أرفِق معالج أحداث بكائن المصادقة العام. يتم استدعاء هذا المعالج كلما تغيّرت حالة تسجيل الدخول للمستخدم. وبما أنّ المعالج لا يتم تشغيله إلا بعد اكتمال تهيئة عنصر المصادقة وبعد اكتمال أي طلبات على الشبكة، فإنّه المكان الأفضل للحصول على معلومات حول المستخدم الذي سجّل الدخول.
سجِّل معالج الأحداث باستخدام الحقل StateChanged الخاص بالكائن FirebaseAuth. عندما يسجّل المستخدم الدخول بنجاح، يمكنك الحصول على معلومات عنه في معالج الأحداث.
أخيرًا، عندما يتم استدعاء هذا العنصر باستخدام Destroy، سيتم تلقائيًا استدعاء OnDestroy. نظِّف مراجع عنصر Auth في 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;}
الخطوات التالية
تعرَّف على كيفية إضافة دعم لموفّري الهوية الآخرين وحسابات الضيوف المجهولة الهوية:
تاريخ التعديل الأخير: 2025-08-23 (حسب التوقيت العالمي المتفَّق عليه)
[[["يسهُل فهم المحتوى.","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-23 (حسب التوقيت العالمي المتفَّق عليه)"],[],[],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)"]]