主要流程是:unity 通过www类访问后台的php脚本,php脚本里对mysql进行操作
apache 的安装(集成mysql,php):
装完后需要注意:局域网默认是不能访问的。需要到wamp\bin\apache\apache2.2.8\conf\ 下的httpd.conf以及wamp\alias\ 下的 phpmyadmin.confAllow from 127.0.0.1 改成 Allow from all;
重启wamp,然后局域网也可以访问了让使用wamp一键搭建的环境外部也可以访问,安卓端测试也能访问到。
php脚本:
<?php
$connect =mysql_connect("127.0.0.1","root","");
if($connect==0)
{
echo "SORRY SCORE SERVER CONNECTION ERROR";
}
echo "OK";
mysql_select_db("数据库名字",$connect);
$user_name=$_POST["name"];
$user_score=$_POST["score"];
$sql ="INSERT INTO 表名字(name,score)";
$sql .=" VALUES('".$user_name."',".$user_score.")";
$result=mysql_query($sql,$connect);
if($result){
echo "save Ok";
}
else echo "save error";
mysql_close($connect);
?>
C#脚本:
private string url= "http://127.0.0.1/save_score.php";
//保存分数的协程
public IEnumerator SaveScore(string name,int fenshu) {
WWWForm form = new WWWForm();
form.AddField("name",name);
form.AddField("score", fenshu);
WWW www = new WWW(url,form);
yield return www;
if (string.IsNullOrEmpty(www.error))
{
Debug.Log(www.text);
}
else
{
Debug.Log(www.error);
}
}
php脚本
<?php
$connect =mysql_connect("10.10.10.18","root","");
if($connect==0)
{
echo "SORRY SCORE SERVER CONNECTION ERROR";
}
//echo "OK";
mysql_select_db("unity3dzsb",$connect);
$sql ="SELECT *from score";
$result=mysql_query($sql,$connect);
$rows=array();
$return=array();
while($row=mysql_fetch_array($result)){
$rows["name"]=$row['name'];
$rows["score"]=$row['score'];
array_push($return,$rows);
}
echo json_encode($return);
mysql_close($connect);
?>
c# 脚本:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using LitJson;//需要引入这个dll文件
private string url2 = "http://127.0.0.1/get_score.php";
public IEnumerator GetAllScore() {
WWW www = new WWW(url2);
yield return www;
if (string.IsNullOrEmpty(www.error))
{
Debug.Log(www.text);
getScore(www.text);
}
else
{
Debug.Log(www.error);
}
}
public void getScore(string strJson) {
JsonData jd = JsonMapper.ToObject(strJson);
for (int i = 0; i < jd.Count; i++)
{
Debug.Log(jd[i]["name"]);
Debug.Log(jd[i]["score"]);
}
}