sql >> Databáze >  >> RDS >> Sqlserver

Jak se připojit k databázi z Unity

Při tomto přístupu prosím ignorujte jakákoli bezpečnostní rizika

Nedělejte to takto . Nezáleží na tom, zda zabezpečení přijde dříve nebo potom. Skončíte s přepisováním celého kódu, protože heslo je pevně zakódováno ve vaší aplikaci, které lze dekompilovat a načíst snadno . Nyní proveďte připojení správným způsobem, abyste nemuseli přepisovat celou aplikaci.

Spusťte svůj databázový příkaz na svém serveru pomocí php, perlu nebo jiného jazyka, který vám vyhovuje, ale toto by mělo být provedeno na serveru.

Z Unity použijte WWW nebo UnityWebRequest třídy komunikovat s tímto skriptem a poté budete moci odesílat a přijímat informace z Unity na server. Existuje mnoho příkladů. I v tomto případě stále musíte implementovat své vlastní zabezpečení, ale toto je mnohem lepší než to, co máte nyní.

Pomocí json můžete také přijímat více dat.

Níže je kompletní příklad z této wiki Unity. Ukazuje, jak komunikovat s databází v Unity pomocí php na straně serveru a Unity + C# na straně klienta.

Na straně serveru :

Přidat skóre pomocí PDO :

<?php
        // Configuration
        $hostname = 'localhot';
        $username = 'yourusername';
        $password = 'yourpassword';
        $database = 'yourdatabase';

        $secretKey = "mySecretKey"; // Change this value to match the value stored in the client javascript below 

        try {
            $dbh = new PDO('mysql:host='. $hostname .';dbname='. $database, $username, $password);
        } catch(PDOException $e) {
            echo '<h1>An error has ocurred.</h1><pre>', $e->getMessage() ,'</pre>';
        }

        $realHash = md5($_GET['name'] . $_GET['score'] . $secretKey); 
        if($realHash == $hash) { 
            $sth = $dbh->prepare('INSERT INTO scores VALUES (null, :name, :score)');
            try {
                $sth->execute($_GET);
            } catch(Exception $e) {
                echo '<h1>An error has ocurred.</h1><pre>', $e->getMessage() ,'</pre>';
            }
        } 
?>
 

Načtení skóre pomocí PDO :

<?php
    // Configuration
    $hostname = 'localhost';
    $username = 'yourusername';
    $password = 'yourpassword';
    $database = 'yourdatabase';

    try {
        $dbh = new PDO('mysql:host='. $hostname .';dbname='. $database, $username, $password);
    } catch(PDOException $e) {
        echo '<h1>An error has occurred.</h1><pre>', $e->getMessage() ,'</pre>';
    }

    $sth = $dbh->query('SELECT * FROM scores ORDER BY score DESC LIMIT 5');
    $sth->setFetchMode(PDO::FETCH_ASSOC);

    $result = $sth->fetchAll();

    if(count($result) > 0) {
        foreach($result as $r) {
            echo $r['name'], "\t", $r['score'], "\n";
        }
    }
?>
 

Povolit na serveru zásady pro více domén :

Tento soubor by se měl jmenovat „crossdomain.xml“ a měl by být umístěn v kořenovém adresáři vašeho webového serveru. Unity vyžaduje, aby webové stránky, ke kterým chcete přistupovat prostřednictvím požadavku WWW, měly zásady pro více domén.

<?xml version="1.0"?>
<cross-domain-policy>
<allow-access-from domain="*"/>
</cross-domain-policy>
 

Strana klienta/jednoty :

Klientský kód z Unity se připojí k serveru, interaguje s PDO a přidá nebo načte skóre v závislosti na tom, která funkce je volána. Tento klientský kód je mírně upraven pro kompilaci s nejnovější verzí Unity.

private string secretKey = "mySecretKey"; // Edit this value and make sure it's the same as the one stored on the server
public string addScoreURL = "http://localhost/unity_test/addscore.php?"; //be sure to add a ? to your url
public string highscoreURL = "http://localhost/unity_test/display.php";

//Text to display the result on
public Text statusText;

void Start()
{
    StartCoroutine(GetScores());
}

// remember to use StartCoroutine when calling this function!
IEnumerator PostScores(string name, int score)
{
    //This connects to a server side php script that will add the name and score to a MySQL DB.
    // Supply it with a string representing the players name and the players score.
    string hash = Md5Sum(name + score + secretKey);

    string post_url = addScoreURL + "name=" + WWW.EscapeURL(name) + "&score=" + score + "&hash=" + hash;

    // Post the URL to the site and create a download object to get the result.
    WWW hs_post = new WWW(post_url);
    yield return hs_post; // Wait until the download is done

    if (hs_post.error != null)
    {
        print("There was an error posting the high score: " + hs_post.error);
    }
}

// Get the scores from the MySQL DB to display in a GUIText.
// remember to use StartCoroutine when calling this function!
IEnumerator GetScores()
{
    statusText.text = "Loading Scores";
    WWW hs_get = new WWW(highscoreURL);
    yield return hs_get;

    if (hs_get.error != null)
    {
        print("There was an error getting the high score: " + hs_get.error);
    }
    else
    {
        statusText.text = hs_get.text; // this is a GUIText that will display the scores in game.
    }
}

public string Md5Sum(string strToEncrypt)
{
    System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding();
    byte[] bytes = ue.GetBytes(strToEncrypt);

    // encrypt bytes
    System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
    byte[] hashBytes = md5.ComputeHash(bytes);

    // Convert the encrypted bytes back to a string (base 16)
    string hashString = "";

    for (int i = 0; i < hashBytes.Length; i++)
    {
        hashString += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
    }

    return hashString.PadLeft(32, '0');
}
 

Toto je jen příklad toho, jak to správně udělat. Pokud potřebujete implementovat funkci relace a záleží vám na zabezpečení, podívejte se na OAuth 2.0 protokol. Měly by existovat existující knihovny, které vám pomohou začít s OAuth protokol.



  1. Navicat pro MySQL

  2. PostgreSQL High Availability instalací Patroni

  3. Znamená omezení Postgres UNIQUE index?

  4. Seznam všech funkcí v databázi Oracle