目录
一、序言
本文主要描述unity连接mysql数据库,获取其中的数据,并实时控制unity的物体位置,到达某个位置后,另一个物体发生反应的内容。
二、连接mysql数据库
具体操作方法如下:
数据库和表数据例子:
注意:rate最好与x数值相近 ,间隔1s运行1的距离
在unity项目中创建一个C#文件,名为SqlAccess,是连接数据库与调用交互数据库方法的类
SqlAccess.cs:
using System;
using System.Data;
using MySql.Data.MySqlClient;
using UnityEngine;
using System.Text;
public class SqlAccess
{
public static MySqlConnection dbConnection;
//如果只是在本地的话,写localhost就可以。
// static string host = "localhost";
//如果是局域网,那么写上本机的局域网IP
static string host = "localhost";
static string port = "3306";
static string username = "myroot"; //用户名
static string pwd = "myroot"; //密码
static string database = "testdb"; //数据库名
public SqlAccess()
{
OpenSql();
}
/// <summary>
/// 连接数据库
/// </summary>
public static void OpenSql()
{
try
{
string connectionString = string.Format("server = {0};port={1};database = {2};user = {3};password = {4};charset=utf8;", host, port, database, username, pwd);
dbConnection = new MySqlConnection(connectionString);
dbConnection.Open();
Debug.Log("建立连接...");
}
catch (Exception e)
{
throw new Exception("服务器连接失败,请重新检查是否打开MySql服务。" + e.Message.ToString());
}
}
/// <summary>
/// 关闭数据库连接
/// </summary>
public void Close()
{
if (dbConnection != null)
{
dbConnection.Close();
dbConnection.Dispose();
dbConnection = null;
Debug.Log("连接已关闭...");
}
}
/// <summary>
/// 查询
/// </summary>
/// <param name="tableName">表名</param>
/// <param name="items"></param>
/// <param name="col">字段名</param>
/// <param name="operation">运算符</param>
/// <param name="values">字段值</param>
/// <returns>DataSet</returns>
public DataSet SelectWhere(string tableName, string[] items, string[] col, string[] operation, string[] values)
{
if (col.Length != operation.Length || operation.Length != values.Length)
throw new Exception("col.Length != operation.Length != values.Length");
StringBuilder query = new StringBuilder();
query.Append("SELECT ");
query.Append(items[0]);
for (int i = 1; i < items.Length; ++i)
{
query.Append(", ");
query.Append(items[i]);
}
query.Append(" FROM ");
query.Append(tableName);
query.Append(" WHERE 1=1");
for (int i = 0; i < col.Length; ++i)
{
query.Append(" AND ");
query.Append(col[i]);
query.Append(operation[i]);
query.Append("'");
query.Append(values[0]);
query.Append("' ");
}
//Debug.Log(query.ToString());
return ExecuteQuery(query.ToString());
}
/// <summary>
/// 执行sql语句
/// </summary>
/// <param name="sqlString">sql语句</param>
/// <returns></returns>
public static DataSet ExecuteQuery(string sqlString)
{
if (dbConnection.State == ConnectionState.Open)
{
DataSet ds = new DataSet();
try
{
MySqlDataAdapter da = new MySqlDataAdapter(sqlString, dbConnection);
da.Fill(ds);
}
catch (Exception ee)
{
throw new Exception("SQL:" + sqlString + " Error:" + ee.Message.ToString());
}
finally
{
}
return ds;
}
return null;
}
}
三、unity获取数据后实时控制物体位置
打开unity项目创建一个C#文件,名为:PositonController
PositonController.cs:
using System.Data;
using UnityEngine;
//[System.Serializable]
//public class EventVector3 : UnityEvent<Vector3> { }
public class PositonController : MonoBehaviour
{
//public EventVector3 postionVector3;
public new GameObject gameObject;
public float x;
public float y;
public float z;
float speed = .5f;
float nextTime;
float rate = 2f;
DataTable table;
int count = 0;
int currentInt = -1;
DataSet ds = null;
//注意这里不同的对象的权重不一致,否则运动会变得一致
private Vector3 velocity = Vector3.zero;
private Vector3 velocity2 = Vector3.zero;
GameObject object2;
Vector3 position;
// Start is called before the first frame update
void Start()
{
object2 = GameObject.Find("Object2");
Debug.Log(gameObject.transform.position.ToString() + "Cube");
SqlAccess sql = new SqlAccess();
string[] items = { "x", "y", "z", "speed", "rate" };
string[] col = { };
string[] op = { };
string[] val = { };
ds = sql.SelectWhere("position", items, col, op, val);
if (ds != null)
{
table = ds.Tables[0];
count = table.Rows.Count;
}
}
void Update()
{
Vector3 size = object2.GetComponent<Renderer>().bounds.size;
//Debug.Log(size.x + "直径");
if (Mathf.Abs(object2.transform.position.x - gameObject.transform.position.x) <= size.x + 0.02)
{
currentInt = -1;
ds = null;
Debug.Log(gameObject.transform.position + "位置");
object2.transform.position = Vector3.SmoothDamp(object2.transform.position, new Vector3(4f, 0.5f, 2f), ref velocity2, 1.5f);
}
while (Time.time > nextTime && currentInt < (count - 1) && ds != null)
{
currentInt++;
//时间间隔越大,移动速度越慢
rate = (float)table.Rows[currentInt][table.Columns[4]];
nextTime = Time.time + rate;
x = (float)table.Rows[currentInt][table.Columns[0]];
y = (float)table.Rows[currentInt][table.Columns[1]];
z = (float)table.Rows[currentInt][table.Columns[2]];
speed = (float)table.Rows[currentInt][table.Columns[3]];
Debug.Log(" currentInt:" + currentInt + " Position:" + x + " , " + y + " , " + z + " Speed:" + speed);
Debug.Log(gameObject.transform.position.ToString() + "Cube");
}
//postionVector3?.Invoke(position);
if (Mathf.Abs(x) < 0.01 && Mathf.Abs(y) < 0.01 && Mathf.Abs(z) < 0.01)
{
//位置校正
gameObject.transform.position = Vector3.SmoothDamp(transform.position, position, ref velocity, speed);
}
gameObject.transform.position = Vector3.SmoothDamp(transform.position, new Vector3(x, y, z), ref velocity, speed);
}
}
然后创建一个球体,命名为Cude,并设置它的位置、添加刚体、碰撞体的组件,如图‘;
然后挂载PositonController文件到Cude球体上,然后选中游戏对象为Cude
然后在场景中创建一个新对象,命名为Object2(注意这里一定要设置为Object2,因为程序中涉及根据名称赋值该对象的相关信息),并设置它的位置、添加刚体、碰撞体的组件,如图;
然后点击运行效果
unity-mysql获取数据控制物体移动小demo