Unity MYSQL Connection (Account Creation and Login Verification)
Unity MYSQL Connection (Account Creation and Login Verification)
Hello everyone, in this article I will explain how you can create a user login and a player account creation system for your game in Unity. Actually, you can control these quite easily with a simple method. The only thing you really need here is to have some knowledge of web design because in Unity, the MYSQL connection is not established directly with C# but via a website using the WWW structures in Unity.
If you don't know what WWW and WWWForm are, those who came here without directly researching the topic, I recommend you read this article first. After you learn about WWW and WWWForm, I think you will better understand what I am trying to explain here.
Understanding the Logic
You can use a program by rote, but such a thing is not really possible in software development, so I want to briefly talk about the logic of this work. Let’s grasp the logic of how to connect MySQL from Unity using WWW, and see how the system works.
First, we write a simple PHP script to send the user's data to the database. I coded 2 PHP pages for this project. The first is to create a user account and the second is to handle user login.
After creating the interface in Unity, I created a C# file called MySQLHelper and made it send the necessary data from the user to the required pages and display Debug output on the screen based on the responses from the site.
Setting Up the Database and Web Part
Creating a Database
Writing the Web Scripts
<?PHP
$host = "localhost"; // MySQL Host
$host_username = "root"; // MySQL username
$host_password = "root"; // MySQL password
$host_database = "deneme"; // MySQL database
?><?PHP
include "config.php"; // calling config.php
if(isset($_POST["kullaniciAdi"], $_POST["sifre"])){
try{ // Start error controller
$kullaniciAdi = $_POST["kullaniciAdi"];
$sifre = $_POST["sifre"];
$baglanti = new PDO("mysql:host=".$host.";dbname=".$host_database."" , $host_username, $host_password);
$baglanti -> exec("SET NAMES utf8");
$baglanti -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sorgu = $baglanti -> query("SELECT * FROM hesaplar WHERE kadi = '$kullaniciAdi' && pass = '$sifre'", PDO::FETCH_ASSOC);
if($sorgu->rowCount()){
echo "1";
}else{
echo "0";
}
}catch(PDOException $e){
die($e->getMessage());
}
}
?><?PHP
include "config.php";
if(isset($_POST["kullaniciAdi"], $_POST["mail"], $_POST["sifre"])){
try{
$kullaniciAdi = $_POST["kullaniciAdi"];
$mail = $_POST["mail"];
$sifre = $_POST["sifre"];
$baglanti = new PDO("mysql:host=".$host.";dbname=".$host_database."" , $host_username, $host_password);
$baglanti -> exec("SET NAMES utf8");
$baglanti -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sorgu = $baglanti -> prepare("INSERT INTO hesaplar(kadi, mail, pass) VALUES(?,?,?)");
$sorgu -> bindParam(1, $kullaniciAdi, PDO::PARAM_STR);
$sorgu -> bindParam(2, $mail, PDO::PARAM_STR);
$sorgu -> bindParam(3, $sifre, PDO::PARAM_STR);
$sorgu -> execute();
echo "1";
}catch(PDOException $e){
die($e->getMessage());
}
}
Writing the Unity Codes
MySQLHelper
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement; // Library used for scene switching
public class MYSQLHelper:MonoBehaviour
{
[SerializeField] // Makes the variable accessible from the Inspector window
private string hesapOlusturURL = ""; // Variable for the account creation URL
[SerializeField]
private string girisYapURL = ""; // Variable for the login URL
// Two variables called HesapOlustur and GirisYap accessible from anywhere, calling the main functions used inside StartCoroutine
public void HesapOlustur(string kullaniciAdi, string ePosta, string sifre){
StartCoroutine(_HesapOlustur(kullaniciAdi, ePosta, sifre));
}
public void GirisYap(string kullaniciAdi, string sifre, int acilacakSayfa){
StartCoroutine(_GirisYap(kullaniciAdi, sifre , acilacakSayfa));
}
// Function to reload the current scene if login is successful,
public void GirisYapildi(int sahneID){
PlayerPrefs.SetInt("giris", 1); // Using PlayerPrefs to keep whether the user is logged in, thus not always showing the login screen.
// PlayerPrefs = 1 means logged in.
SceneManager.LoadScene(sahneID, LoadSceneMode.Single); // Reloading the scene
}
IEnumerator _HesapOlustur(string kullaniciAdi, string ePosta, string sifre)
{
yield return new WaitForEndOfFrame(); // Waits for the end of the last frame
WWWForm hesapOlusturmaForm = new WWWForm(); // Creating a WWW form
hesapOlusturmaForm.AddField("kullaniciAdi", kullaniciAdi); // Adding username to the form
hesapOlusturmaForm.AddField("mail", ePosta); // Adding email to the form
hesapOlusturmaForm.AddField("sifre", sifre); // Adding password to the form
WWW veriGonder = new WWW(hesapOlusturURL, hesapOlusturmaForm); // Connects to the site via WWW to send data
yield return veriGonder; // Sending the data
if(veriGonder.text == "1"){ // If received 1 from the site
Debug.Log("Account creation successful"); // Shows successful login
}else{
Debug.Log("An error occurred while creating the account! \nThe problem is not you, it's me. :')"); // If response is not 1, shows an error message
}
}
IEnumerator _GirisYap(string kullaniciAdi, string sifre, int acilacakSayfa){
yield return new WaitForEndOfFrame();
WWWForm girisYapForm = new WWWForm();
girisYapForm.AddField("kullaniciAdi", kullaniciAdi);
girisYapForm.AddField("sifre", sifre);
WWW veriGonder = new WWW(girisYapURL, girisYapForm);
yield return veriGonder;
if(veriGonder.text == "1"){
Debug.Log("Login Successful");
GirisYapildi(acilacakSayfa);
}else if(veriGonder.text == "0"){
Debug.Log("Username or password is incorrect!");
}else {
Debug.Log("An error occurred during login! \nThe problem is not you, it's me :')");
}
}
}
UIManager
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIManager : MonoBehaviour
{
public GameObject[] paneller; // Assigns main screen, login and account creation panels here so you can toggle between them.
public MYSQLHelper _mysqlHelper; // Drag the MySQL Helper Script here and access its functions from this.
public InputField _hesapOlusturKullaniciAdi; // Account creation panel username input
public InputField _hesapOlusturSifre; // Account creation panel password input
public InputField _hesapOlusturEPosta; // Account creation panel email input
public InputField _girisYapKullaniciAdi; // Login panel username input
public InputField _girisYapSifre; // Login panel password input
// Panel order
// 0 MainScreen
// 1 Login Panel
// 2 Account Creation Panel
void Awake(){
if(PlayerPrefs.GetInt("giris") == 1){ // Check if the user is already logged in
GirisEkraniKapat(); // If so, hide the login and account creation panels
}
}
// Function to close login and account creation panels
public void GirisEkraniKapat(){
paneller[0].SetActive(false); // hides main panel
paneller[1].SetActive(false); // hides login panel
paneller[2].SetActive(false); // hides account creation panel
}
// Function called when login button is clicked
public void GirisYap(){
_mysqlHelper.GirisYap(_girisYapKullaniciAdi.text, _girisYapSifre.text, 0); // Calls login function in MYSQLHelper and sends required info
}
// Function called when create account button is clicked
public void HesapOlustur(){
_mysqlHelper.HesapOlustur(_hesapOlusturKullaniciAdi.text, _hesapOlusturEPosta.text, _hesapOlusturSifre.text); // Calls account creation function in MYSQLHelper script
}
// Opens or closes the login panel
public void GirisPaneliAcKapat()
{
if (paneller[0].activeSelf)
{
paneller[0].SetActive(false);
paneller[2].SetActive(false);
paneller[1].SetActive(true);
}
else if (paneller[0].activeSelf == false)
{
paneller[0].SetActive(true);
paneller[1].SetActive(false);
paneller[2].SetActive(false);
}
}
// Opens or closes the register panel
public void KayitPaneliAcKapat()
{
if (paneller[0].activeSelf)
{
paneller[0].SetActive(false);
paneller[1].SetActive(false);
paneller[2].SetActive(true);
}
else if (paneller[0].activeSelf == false)
{
paneller[0].SetActive(true);
paneller[1].SetActive(false);
paneller[2].SetActive(false);
}
}
}


Yorum Gönder