在Unity中实现简单的伪时间同步
在Unity中实现简单的伪时间同步,只是读取数据库所在电脑的当前时间
usingUnityEngine;
usingSystem.Collections;
usingSystem.Runtime.InteropServices;
usingSystem.Data;
usingSystem.Data.SqlClient;
publicclassChangeTime
{
//Kernel32.dll在32位系统和64位系统有区别,64位系统中需要设置为以管理员身份运行
[DllImport("Kernel32.dll",SetLastError=true,EntryPoint="SetLocalTime")]
staticexternintSetLocalTime(refSystemDateTimelpSystemDateTime);
publicstaticstringGetCurrentTimeFromDB()
{
stringresult="";
//从数据库中获取系统当前时间
//设置连接字符串
SqlConnectioncon=newSqlConnection("DataSource=192.168.0.1;InitialCatalog=DB;UserID=sa;password=123456");
SqlCommandcmd=newSqlCommand();
cmd.Connection=con;
cmd.CommandType=System.Data.CommandType.Text;
//设置连接语句
cmd.CommandText="selectgetdate()";
SqlDataAdaptersda=newSqlDataAdapter(cmd);
//开启
sda.SelectCommand.Connection.Open();
result=sda.SelectCommand.ExecuteScalar().ToString();
//关闭
sda.SelectCommand.Connection.Close();
returnresult;
}
publicstaticvoidSetLocalDae(stringdateTime)
{
System.DateTimedate=System.DateTime.Parse(dateTime);
SystemDateTimesysNew=newSystemDateTime();
//设置属性
sysNew.tYear=short.Parse(date.Year.ToString());
sysNew.tMonth=short.Parse(date.Month.ToString());
sysNew.tDay=short.Parse(date.Day.ToString());
sysNew.tHour=short.Parse(date.Hour.ToString());
sysNew.tMinute=short.Parse(date.Minute.ToString());
sysNew.tSecond=short.Parse(date.Second.ToString());
//调用API,更新系统时间
SetLocalTime(refsysNew);
}
}
///<summary>
///定义变量用于接收
///</summary>
publicclassSystemDateTime
{
publicshorttYear;
publicshorttMonth;
publicshorttDayOfWeek;
publicshorttDay;
publicshorttHour;
publicshorttMinute;
publicshorttSecond;
publicshorttMilliseconds;
}
以上就是本文所述的全部内容了,希望大家能够喜欢。