HTTP score of the leaderboard

Unity is sent to the server user name and score, and stored in the database, tell the database downloaded to score Unity in accordance with descending order.

First, create a database

First of all, we want to create a simple database in MySQL database is used to save the username and score, use MySQL Workbench tool provided by MySQL just a few steps to complete the job.

  • 1. Determine the complete installation of MySQL, start MySQL Workbench (I use version 8.0+), which is a graphical tool for database software.
  • 2. Click on the + sign in the menu bar to create a database model and the following figure named myscoresdbHere Insert Picture Description
    Here Insert Picture Description
  • 3. Enter the following interface open database model you just created and find Tables right to create a high score table
    Here Insert Picture Description
    Here Insert Picture Description

Second, create a PHP script

Here you need to create two php scripts, a user name used to upload scores and other scores used to download and sort it sent to Unity.

  • 1. Create UploadScore.php script, here first need to read data from the Unity username and score, and then open the database, the last use SQL statements to insert data into the database, as follows:
<?php 
//UploadScore.php
require_once ("PHPStream.php");

//读入用户名和分数
$webstream=new PHPStream();
$webstream->BeginRead("123456");
$UserID=$webstream->Read('username');       // user name
$hiscore=$webstream->Read('score');         // hi score
$b=$webstream->EndRead();
if ( !$b )
{
    exit("md5 error");
}
//连接数据库
$myData=mysqli_connect("localhost","root","163888");
if (mysqli_connect_errno())
{
    echo mysqli_connect_error();
    return;
}

//校验用户名是否合法(防止SQL注入)
$UserID=mysqli_real_escape_string($myData,$UserID);

//选择数据库
mysqli_query($myData,"set names utf8");
mysqli_select_db($myData,"myscoresdb");

//插入新数据
$sql="insert into hiscores value(NULL,'$UserID','$hiscore')";
mysqli_query($myData,$sql);


//关闭数据库
mysqli_close($myData);

?>
  • 2. Create DownloadScores.php script, we will query the database records the highest score of 20, and then sent to Unity in the user name and score a loop, as follows:
<?php 
require_once ("PHPStream.php");

//连接数据库
$myData=mysqli_connect("localhost","root","163888");
if (mysqli_connect_errno())
{
    echo mysqli_connect_error();
    return;
}

//选择数据库
mysqli_query($myData,"set name utf8");
mysqli_select_db($myData,"myscoresdb");

//查询得分最高的20个记录
$sql = "SELECT name,score FROM hiscores ORDER by score DESC LIMIT 20";

$result = mysqli_query($myData,$sql) or die("<br>SQL error!<br/>");
$num_results = mysqli_num_rows($result);

//准备发送数据到Unity
$webstream=new PHPStream();
$webstream->BeginWrite(PKEY);

//发送排行榜分数的数量
$webstream->WriteInt($num_results);

for ($i=0;$i<$num_results;$i++)
{
    $row = mysqli_fetch_array($result,MYSQLI_ASSOC);
    
    $data[$i][0]=$row['name'];
    $data[$i][1]=$row['score'];
    
    //发送用户名和得分
    $webstream->WriteString($data[$i][0]);
    $webstream->WriteString($data[$i][1]);
    
    //echo $data[$i][0];
    //echo $data[$i][1];
}

$webstream->EndWrite();

mysqli_free_result($result);

//关闭数据库
mysqli_close($myData);

//发送
echo $webstream->bytes;

?>

Third, upload and download scores

In Unity, is a user name and upload the score, and the other is the user name and score points before downloading the top 20, the contents of the PHP script to update the database of fact, we used the corresponding WWW Unity function calls, and feedback to the Unity . As shown below:

Here Insert Picture Description

- 1. Create a space object and named Score, create a new script ScoreScript hung onto Score Space Objects

Here Insert Picture Description

- script-defined attributes 2. Open ScoreScript
  public const string UploadScoreUrl = "http://192.168.1.5:8088/UploadScore.php";

    public const string DownloadScoresUrl = "http://192.168.1.5:8088/DownloadScores.php";

    private string[] m_hiscores;
- 3. Add UploadScore upload function scores:
 IEnumerator UploadScore(string name,string score)
    {
        PostStream poststream = new PostStream();

        poststream.BeginWrite(true);
        poststream.Write("username",name);
        poststream.Write("score",score);
        poststream.EndWrite();

        WWW www = new WWW(UploadScoreUrl,poststream.BYTES,poststream.Headers);

        yield return www;

        if (www.error != null)
        {
            Debug.LogError("www.error:" + www.error);
        }
        else
        {
            Debug.LogError("www.text:"+ www.text);
        }
    }
- Download 4. Add function:
IEnumerator DownloadScores()
    {
        WWW www = new WWW(DownloadScoresUrl);
        yield return www;
        if (www.error != null)
        {
            Debug.LogError("www.error:" + www.error);
        }
        else
        {
            int count = 0;
            PostStream poststream = new PostStream();
            poststream.BeginRead(www,true);
            poststream.ReadInt(ref count);
            if (count > 0)
            {
                m_hiscores = new string[count];

                //在循环中读入用户名和分数
                for (int i = 0; i < count; i++)
                {
                    string tname = "";
                    string tscore = "";
                    poststream.ReadString(ref tname);
                    poststream.ReadString(ref tscore);

                    m_hiscores[i] = tname + ":" + tscore;
                    Debug.LogError(m_hiscores[i]);
                }
                bool ok = poststream.EndRead();
                if (!ok) Debug.LogError("MD5 error");
                
            }
        }
    }
- 5. Draw the GUI ( OnGUI foundation can look at this article )
string userName = "";
    string score = "";
    Vector2 vector2;
    private void OnGUI()
    {
        if (GUI.Button(new Rect(10, 110, 150, 30), "上传"))
        {
            StartCoroutine(UploadScore(userName,score));
            score = "";
            userName = "";
        }
        if (GUI.Button(new Rect(10, 140, 150, 30), "下载"))
        {
            StartCoroutine(DownloadScores());
        }

        //GUI.color = Color.blue;
        GUI.Label(new Rect(10, 10, 100, 50), "用户名:");
        GUI.Label(new Rect(10, 50, 100, 50), "密  码:");

        userName = GUI.TextField(new Rect(80, 10, 100, 30), userName);
        score = GUI.PasswordField(new Rect(80, 50, 100, 30), score,'*');


        //开始滚动视图
        vector2 = GUI.BeginScrollView(new Rect(180, 0, 500, 500), vector2, new Rect(0, 0, 500, 500), true, true);
        if (m_hiscores != null)
        {
            for (int i = 0; i < 20; i++)
            {
                if (i < m_hiscores.Length) GUI.Button(new Rect(0, 25 * i, 500, 20), m_hiscores[i]);
                else GUI.Button(new Rect(0, 25 * i, 500, 20),"");
            }
        }
        GUI.EndScrollView(); 
    }

Fourth, the test

Here Insert Picture Description

Published 62 original articles · won praise 5 · Views 3919

Guess you like

Origin blog.csdn.net/qq_42194657/article/details/103239176
Recommended