1. 环境
unity2018
2. 运行截图
3. 功能
1. 场景漫游
提供第一视角模式和自由模式。第一视角使用unity自带的角色控制器包实现角色移动视角移动,自由模式实现鼠标拖拽,场景缩放。
2. 商品定位
通过输入商品信息,在三维场景中定位到商品模型并标识,在模型上方生成2D图形标记。
3. 存取档
通过xml、json、二进制、数据库等方式存储场景内容,本项目连接sqlserver数据库存储读取。
4. 网页(或窗体)交互
提供网页(或窗体)与unity数据传输,将unity页面嵌入浏览器网页或windows客户端(参考前面博客功能)。
4.项目搭建
1. 结构:
设主相机、灯光、plane平面、gameobject(游戏 控制器)、newCube(cube预设体生成位置)、shelves_2xs(场景货架放置位置)、canvas(ui界面)。
2. 实现代码
1)cube预设体
预设体半透明(通过Material材质球设置fade模式,如下图),添加统一标签test(方便后续统一调用),
cube预设体添加脚本moveController控制球体移动旋转,初始关闭moveController组件(后面需要时会在代码中开启)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class moveController : MonoBehaviour
{public float speed = 3; //人物移动速度public float rotatinDamping = 4; //人物旋转的速度public float mouse1RotateDamping = 4;public bool cameraIsRotate = true; //判断相机是否跟随人物旋转(点击鼠标左键可观看角色)private float h1; //点击鼠标右键,存储鼠标X方向位移private float h2; //点击鼠标左键,存储鼠标X方向位移private float currentOnClickMouse1AngleY = 0; //鼠标右击时人物当前的Y轴度数private float currentCameraAngleY = 0; //鼠标左击时相机当前的Y轴度数public GameObject cam; //人物后面的相机private CharacterController characterContro; //角色控制器组件// Use this for initializationprivate void Start(){characterContro = this.GetComponent<CharacterController>();cam = GameObject.FindGameObjectWithTag("MainCamera");}// Update is called once per frameprivate void Update(){forwardOrBack();rotate();mouseControllerRotation();}/// <summary>/// 向前向后移动/// </summary>private void forwardOrBack(){if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow)){characterContro.Move(transform.forward * speed * Time.deltaTime);}elseif (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow)){characterContro.Move(-transform.forward * speed * Time.deltaTime);}else if (Input.GetKey(KeyCode.Q)){characterContro.Move(transform.up * speed * Time.deltaTime);}else if (Input.GetKey(KeyCode.E)){characterContro.Move(-transform.up * speed * Time.deltaTime);}}/// <summary>/// 按左右旋转/// </summary>private void rotate(){if (Input.GetKey(KeyCode.D)){transform.Rotate(Vector3.up * rotatinDamping);}if (Input.GetKey(KeyCode.A)){transform.Rotate(-Vector3.up * rotatinDamping);}}/// <summary>/// 鼠标控制旋转/// </summary>private void mouseControllerRotation(){if (Input.GetMouseButtonDown(1)){currentOnClickMouse1AngleY = transform.eulerAngles.y;h1 = 0;}if (Input.GetMouseButton(1)){h1 += Input.GetAxis("Mouse X") * mouse1RotateDamping;transform.eulerAngles = new Vector3(transform.eulerAngles.x, h1 + currentOnClickMouse1AngleY, transform.eulerAngles.z);}if (Input.GetMouseButtonDown(0)){currentCameraAngleY = cam.transform.eulerAngles.y;h2 = 0;}if (Input.GetMouseButton(0)){// float currentOnClickMouse1Angle = transform.eulerAngles.y;cameraIsRotate = false;h2 += Input.GetAxis("Mouse X") * mouse1RotateDamping;cam.transform.eulerAngles = new Vector3(cam.transform.eulerAngles.x, h2 + currentCameraAngleY, cam.transform.eulerAngles.z);}else{cameraIsRotate = true;}}
}
2)货架模型shelves_2xs,2D定位预设体
可自行搭建相关货架模型机及定位标记模型
3)主相机main camerra 脚本挂置
cameraController(控制第一人称移动旋转)
CameraMover (控制漫游视角)
ModelDrage(控制物体鼠标点击拖拽)
初始关闭cameraController组件
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class cameraController : MonoBehaviour
{private moveController mc; //获取人物控制组件private Transform target; //相机跟随的目标位置public float rotationDamping = 6; //相机跟随人物的旋转速度public float zoomSpeed = 4; //鼠标滚轮滑动速度private float h1; //点击鼠标右键,存储鼠标Y方向位移private float distance = 0; //相机和目标的距离//private float height = 1f; //相机和目标的高度//private float heightDamping = 1;// Vector3 offsetPosition;// Use this for initialization// OnEnable是在Awake之后Start之前执行的,这个函数二次调用时仍会执行,而Start和Awake不会。
// 当然这里有个缺点:第一次执行时,Start函数会执行两遍。之后每次激活这个脚本。便会执行一次Start函数.
// 运行顺序为awake > onenable > start//此处控制第一视角可以转换目标(如 新建一个cube后直接转到新的cube第一视角)private void OnEnable(){Start();}private void Start(){// distance = Vector3.Distance(new Vector3(0, 0, target.position.z), new Vector3(0, 0, target.position.z));//offsetPosition = target.position - transform.position;int tagLength = GameObject.FindGameObjectsWithTag("test").Length;target = GameObject.FindGameObjectsWithTag("test")[tagLength - 1].transform;Debug.Log("start方法" + target.name);mc = target.gameObject.GetComponent<moveController>();distance = Vector3.Distance(new Vector3(0, 0, target.position.z), new Vector3(0, 0, transform.position.z));}// Update is called once per frameprivate void Update(){//transform.position = target.position - offsetPosition;flowTarget();zoomView();UpAndDownView();}/// <summary>/// 相机跟随人物移动旋转/// </summary>private void flowTarget(){float wantedRotationAngle = target.eulerAngles.y; //要达到的旋转角度//float wantedHeight = target.position.y + height; //要达到的高度float currentRotationAngle = transform.eulerAngles.y; //当前的旋转角度float currentHeight = transform.position.y; //当前的高度if (mc.cameraIsRotate){currentRotationAngle = Mathf.LerpAngle(currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);}// currentHeight = Mathf.Lerp(currentHeight, wantedHeight, heightDamping * Time.deltaTime); //由当前高度达到要达到的高度Quaternion currentRotation = Quaternion.Euler(transform.eulerAngles.x, currentRotationAngle, 0);// float currentRotation=1; //防止主角回头摄像机发生旋转, 这里不用Vector3 ca = target.position - currentRotation * Vector3.forward * distance; //tt是相机的位置// transform.position = target.position-currentRotation * Vector3.forward * distance;// transform.position = new Vector3(ca.x, transform.position.y, ca.z); //最后得到的相机位置transform.position = new Vector3(ca.x, target.position.y + 2, ca.z);transform.rotation = currentRotation; //最后得到相机的旋转角度// transform.LookAt(target.position);}/// <summary>/// 滚轮控制缩放/// </summary>private void zoomView(){float scrollWheel = Input.GetAxis("Mouse ScrollWheel") * zoomSpeed;distance -= scrollWheel;if (distance > 5.6f){distance = 5.6f;}if (distance < 0.9f){distance = 0.9f;}}/// <summary>/// 摄像头上下视角/// </summary>private void UpAndDownView(){if (Input.GetMouseButton(1)){h1 = Input.GetAxis("Mouse Y") * rotationDamping;Vector3 originalPosition = transform.position;Quaternion originalRotation = transform.rotation;transform.RotateAround(target.position, -target.right, h1); //决定因素position和rotationfloat x = transform.eulerAngles.x;if (x < -10 || x > 80){transform.position = originalPosition;transform.rotation = originalRotation;}}}
}
using UnityEngine;
using System.Collections;public class CameraMover : MonoBehaviour
{public float cameraMoveSpeed = 30f;public float cameraRotSpeed = 30f;private bool isRotateCamera = false;private float trans_y = 0;private float trans_x = 0;private float trans_z = 0;private float eulerAngles_x;private float eulerAngles_y;// Use this for initializationprivate void Start(){Vector3 eulerAngles = this.transform.eulerAngles;//当前物体的欧拉角//Vector3 eulerAngles = new Vector3(20, 0, 0); //当前物体的欧拉角// Debug.Log(eulerAngles);this.eulerAngles_x = eulerAngles.y;this.eulerAngles_y = eulerAngles.x;}private void FixedUpdate(){if (Input.GetMouseButton(1)){this.eulerAngles_x += (Input.GetAxis("Mouse X") * this.cameraRotSpeed) * Time.deltaTime;this.eulerAngles_y -= (Input.GetAxis("Mouse Y") * this.cameraRotSpeed) * Time.deltaTime;Quaternion quaternion = Quaternion.Euler(this.eulerAngles_y, this.eulerAngles_x, (float)0);this.transform.rotation = quaternion;moveCameraByKey(cameraMoveSpeed);}this.trans_z = (Input.GetAxis("Mouse ScrollWheel") * this.cameraMoveSpeed * 30) * Time.deltaTime;this.transform.Translate(Vector3.forward * this.trans_z);//if (Input.GetMouseButton(2))//{// this.trans_y = (Input.GetAxis("Mouse Y") * this.ySpeed / 2) * 0.02f;// this.trans_x = (Input.GetAxis("Mouse X") * this.xSpeed / 2) * 0.02f;// this.transform.Translate(-1 *Vector3.right * this.trans_x);// this.transform.Translate(-1 *Vector3.up * this.trans_y);//}}private void moveCameraByKey(float speed){if (Input.GetKey(KeyCode.Q)){this.transform.Translate(Vector3.down * speed * Time.deltaTime);}if (Input.GetKey(KeyCode.E)){this.transform.Translate(Vector3.up * speed * Time.deltaTime);}float moveV = Input.GetAxis("Vertical");float moveH = Input.GetAxis("Horizontal");this.transform.Translate(Vector3.forward * speed * moveV * Time.deltaTime + Vector3.right * speed * moveH * Time.deltaTime);}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class ModelDrage : MonoBehaviour
{private Camera cam;//发射射线的摄像机private GameObject go;//射线碰撞的物体public static string btnName;//射线碰撞物体的名字private Vector3 screenSpace;private Vector3 offset;private bool isDrage = false;private void Start(){cam = cam = Camera.main;// cam = Camera.current;}private void Update(){//整体初始位置Ray ray = cam.ScreenPointToRay(Input.mousePosition);//从摄像机发出到点击坐标的射线RaycastHit hitInfo;if (isDrage == false){if (Physics.Raycast(ray, out hitInfo)){//划出射线,只有在scene视图中才能看到Debug.DrawLine(ray.origin, hitInfo.point);go = hitInfo.collider.gameObject;//print(btnName);screenSpace = cam.WorldToScreenPoint(go.transform.position);offset = go.transform.position - cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z));//物体的名字btnName = go.name;//发送给winform// Application.ExternalEval(btnName);//组件的名字}else{btnName = null;}}if (Input.GetMouseButton(0)){Vector3 currentScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z);Vector3 currentPosition = cam.ScreenToWorldPoint(currentScreenSpace) + offset;if (btnName != null){go.transform.position = currentPosition;}isDrage = true;}else{isDrage = false;}}
}
4)GameObject脚本挂置
包括新建cube预设体,存读挡,第一人称自由视角变更等操作。
sqlserver,二进制存读挡可以实现,json,xml暂存错误。
(内容较多,暂时把功能代码都放在里面了,后续会分离出来)
using LitJson;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;[System.Serializable]
public class newCube : MonoBehaviour
{public Text cubeNo;private GameObject[] targetGOs;public GameObject boxBody; //障碍物public GameObject mark;private static int i = 1;private static int a = 0;private string path;private bool isActive = true;private void Awake(){}// Use this for initializationprivate void Start(){}// Update is called once per frameprivate void Update(){int tagLength = GameObject.FindGameObjectsWithTag("test").Length;if (Input.GetKeyDown(KeyCode.R)){GameObject.FindGameObjectWithTag("MainCamera").GetComponent<cameraController>().enabled = false;AppearPosition();}if (Input.GetKeyDown(KeyCode.T)){//ExportSceneInfoToXML e = new ExportSceneInfoToXML();//e.ExportXML();//SaveByBin();SaveBySql();}if (Input.GetKeyDown(KeyCode.Y)){GameObject.FindGameObjectWithTag("MainCamera").GetComponent<cameraController>().enabled = false;LoadBySql();}if (Input.GetKeyDown(KeyCode.U)){for (int i = 0; i < tagLength; i++){GameObject.FindGameObjectsWithTag("test")[i].GetComponent<moveController>().enabled = false;}GameObject.FindGameObjectWithTag("MainCamera").GetComponent<cameraController>().enabled = false;GameObject.FindGameObjectWithTag("MainCamera").GetComponent<CameraMover>().enabled = true;GameObject.FindGameObjectWithTag("MainCamera").GetComponent<ModelDrage>().enabled = true;}if (Input.GetKeyDown(KeyCode.I)){GameObject.FindGameObjectsWithTag("test")[tagLength - 1].GetComponent<moveController>().enabled = true;GameObject.FindGameObjectWithTag("MainCamera").GetComponent<cameraController>().enabled = true;GameObject.FindGameObjectWithTag("MainCamera").GetComponent<CameraMover>().enabled = false;GameObject.FindGameObjectWithTag("MainCamera").GetComponent<ModelDrage>().enabled = false;}}private void AppearPosition(){GameObject newCube = GameObject.Find("newCube");Vector3 bodyAppearPosition = new Vector3(0, 2, 0);Quaternion bodyAppearRotation = Quaternion.identity;// boxBody.transform.parent = newCube.transform;// Application.ExternalCall(boxBody.name);// Application.ExternalEval(boxBody.name);boxBody = Instantiate(boxBody, bodyAppearPosition, bodyAppearRotation);boxBody.transform.parent = newCube.transform;boxBody.name = "swj" + i;i++;a += 2;// boxBody.GetComponent<move>().enabled = false;int tagLength = GameObject.FindGameObjectsWithTag("test").Length;for (int i = 0; i < tagLength; i++){GameObject.FindGameObjectsWithTag("test")[i].GetComponent<moveController>().enabled = false;}GameObject.FindGameObjectsWithTag("test")[tagLength - 1].GetComponent<moveController>().enabled = true;GameObject.FindGameObjectWithTag("MainCamera").GetComponent<cameraController>().enabled = true;GameObject.FindGameObjectWithTag("MainCamera").GetComponent<CameraMover>().enabled = false;GameObject.FindGameObjectWithTag("MainCamera").GetComponent<ModelDrage>().enabled = false;}//创建Save对象并存储当前游戏状态信息private Save CreateSaveGO(){targetGOs = GameObject.FindGameObjectsWithTag("test");Save save = new Save();foreach (GameObject targetGO in targetGOs){Transform tra = targetGO.transform;VectorToSave vtf = new VectorToSave();// vtf.VectorToFloat01(tra);save.listDouble.Add(vtf.VectorToDouble(tra));save.cubeNames.Add(tra.name);// save.list.Add(targetGO);}return save;}private void SaveByJson(){Save save = CreateSaveGO();path = Application.dataPath + "/test" + "/byJson.json";//利用JsonMapper将save对象转换为Json格式的字符串string saveJsonStr = JsonMapper.ToJson(save);//将这个字符串写入到文件中//创建一个StreamWriter,并将字符串写入StreamWriter sw = new StreamWriter(path);sw.Write(saveJsonStr);//关闭写入流sw.Close();AssetDatabase.Refresh();// UIManager._instance.ShowMessage("保存成功");}private void LoadByJson(){// JsonData j;path = Application.dataPath + "/test" + "/byJson.json";//创建一个StreamReader,用来读取流StreamReader sr = new StreamReader(path);//将读取到的流赋值给saveJsonStrstring saveJsonStr = sr.ReadToEnd();sr.Close();//将字符串转换为Save对象// j = JsonMapper.ToObject<JsonData>(saveJsonStr);Save save = JsonMapper.ToObject<Save>(saveJsonStr);SetGame(save);// UIManager._instance.ShowMessage("加载成功");}/// <summary>/// 二进制存档/// </summary>//存档private void SaveByBin(){//序列化过程(将save对象转换为字节流)//创建save对象并保存当前游戏状态Save save = CreateSaveGO();//创建一个二进制格式化程序BinaryFormatter bf = new BinaryFormatter();//创建一个文件流path = Application.dataPath + "/test" + "/byBin.txt";FileStream fileStream = File.Create(path);//用二进制格式化程序的序列化方法来序列化Save对象,参数:创建的文件流和需要序列化的对象bf.Serialize(fileStream, save);//关闭流fileStream.Close();//即时刷新Project工程文件AssetDatabase.Refresh();}// 读档private void LoadByBin(){path = Application.dataPath + "/test" + "/byBin.txt";//反序列化过程//创建一个二进制格式化程序BinaryFormatter bf = new BinaryFormatter();//打开一个文件流FileStream fileStream = File.Open(path, FileMode.Open);//调用格式化程序的反序列化方法,将文件流转换为一个save对象Save save = bf.Deserialize(fileStream) as Save;SetGame(save);//关闭文件流fileStream.Close();}//保存到数据库private void SaveBySql(){//SqlConnection conn = new SqlConnection();sqlAceess sql = new sqlAceess();sql.Conn();//删除数据库旧存档sql.delete();// sql.Insert(conn);Save save = new Save();targetGOs = GameObject.FindGameObjectsWithTag("test");foreach (GameObject targetGO in targetGOs){Transform tra = targetGO.transform;save.x = tra.position.x;save.y = tra.position.y;save.z = tra.position.z;save.l = tra.rotation.x;save.m = tra.rotation.y;save.n = tra.rotation.z;save.w = tra.rotation.w;save.cubeName = tra.name;//插入到数据库sql.Insert(save);}sql.ConnClose();}//从数据库读取private void LoadBySql(){//读取存档前 删除目前正在运行的cubetargetGOs = GameObject.FindGameObjectsWithTag("test");foreach (GameObject targetGO in targetGOs){Destroy(targetGO);}sqlAceess sql = new sqlAceess();sql.Conn();List<Save> listSave = sql.select();for (int i = 0; i < listSave.Count; i++){Save sa = listSave[i];string name = sa.cubeName;float a = (float)sa.x;float b = (float)sa.y;float c = (float)sa.z;float d = (float)sa.l;float e = (float)sa.m;float f = (float)sa.n;float w = (float)sa.w;Vector3 v = new Vector3(a, b, c);Quaternion bodyAppearRotation = new Quaternion(d, e, f, w);boxBody = Instantiate(boxBody, v, bodyAppearRotation);GameObject newCube = GameObject.Find("newCube");boxBody.transform.parent = newCube.transform;boxBody.name = name;}sql.ConnClose();GameObject.FindGameObjectWithTag("MainCamera").GetComponent<cameraController>().enabled = true;}private void SetGame(Save save){int length = save.listDouble.Count;for (int i = 0; i < length; i++){// boxBody = Instantiate(save.list[i]);double[] dou = save.listDouble[i];float a = (float)dou[0];float b = (float)dou[1];float c = (float)dou[2];float d = (float)dou[3];float e = (float)dou[4];float f = (float)dou[5];float w = (float)dou[6];Vector3 v = new Vector3(a, b, c);Quaternion bodyAppearRotation = new Quaternion(d, e, f, w);// Quaternion bodyAppearRotation = Quaternion.identity;boxBody = Instantiate(boxBody, v, bodyAppearRotation);GameObject newCube = GameObject.Find("newCube");boxBody.transform.parent = newCube.transform;boxBody.name = save.cubeNames[i];}// Vector3 v = new Vector3(a, b, c);// Vector3 bodyAppearPosition = new Vector3(0, 2, 0);// Quaternion bodyAppearRotation = Quaternion.identity;// boxBody.transform.parent = newCube.transform;// Application.ExternalCall(boxBody.name);// Application.ExternalEval(boxBody.name);// GameObject.FindGameObjectWithTag("test").GetComponent<moveController>().enabled = true;// GameObject.FindGameObjectWithTag("MainCamera").GetComponent<cameraController>().enabled = true;}//根据输入内容定位cube并在上方生成标签public void selectCube(string cubeNo){GameObject[] ga = GameObject.FindGameObjectsWithTag("mark");for (int i = 0; i < ga.Length; i++){Destroy(ga[i]);}cubeNo = this.cubeNo.text;Save save = CreateSaveGO();int length = save.cubeNames.Count;if (save.cubeNames.Contains(cubeNo)){Debug.Log("找到了" + cubeNo);GameObject gam = GameObject.Find(cubeNo);Vector3 v = gam.transform.position;Vector3 v2 = v + new Vector3(0, 1, 0);Instantiate(mark, v2, Quaternion.identity);}else{Debug.Log("不存在" + cubeNo);}// boxBody.name = CreateSaveGO().cubeNames[0];}
}
5)其余script脚本
Save 持久类(存储类型)
sqlAceess数据库连接 (暂实现查询,插入,删除三个功能代码,有需要可补充)
VectorToSave(二进制时需要,将位置信息转储为小数行式)
run(2D定位标签自转脚本,放在2D应为标签 mark预设体下)
使用sqlserver数据库需导包到项目
到unity安装目录下D:\Program Files\Unity\Editor\Data\Mono\lib\mono\unity 将以下dll文件放置到assets/Plugins文件夹下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;[System.Serializable]
public class Save
{// public List<GameObject> list = new List<GameObject>();public List<double[]> listDouble = new List<double[]>();public List<float[]> listFloat = new List<float[]>();public List<string> cubeNames = new List<string>();public double x;public double y;public double z;public double l;public double m;public double n;public double w;public string cubeName;//public Vector3 v = new Vector3();
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using UnityEditor.MemoryProfiler;
using UnityEngine;public class sqlAceess
{private string connsql = "Data Source=127.0.0.1;DataBase=test;uid=sa;pwd=Oraps123";private SqlConnection conn = new SqlConnection();// Use this for initialization//private void Start()//{// SqlConnection conn = new SqlConnection();// //链接数据库// Conn(conn);// Insert(conn);// //关闭连接 Conn这个对象本身还存在内存中,需要在使用的时候,可以直接使用// conn.Close();// //释放对象 Conn对象已经不存在了,下次再需要使用的时候,对象就不存在了,需要重新创建(New)// conn.Dispose();// Console.ReadLine();// SqlConnection connstr = new SqlConnection("Data Source=127.0.0.1;DataBase=test;uid=sa;pwd=Oraps123");// connstr.Close();// connstr.Open();// SqlCommand cmd = new SqlCommand();// cmd.Connection = connstr;// cmd.CommandType = System.Data.CommandType.Text;// //设置sql连接语句// cmd.CommandText = "delete from TEST01 where id =1";// SqlDataAdapter sda = new SqlDataAdapter(cmd);// sda.SelectCommand.Connection.Close();// sda.SelectCommand.Connection.Open();// string strtemp = sda.SelectCommand.ExecuteScalar().ToString();// sda.SelectCommand.Connection.Close();// // print("连接数据库成功!" + strtemp);// connstr.Close();// sda.SelectCommand.Connection.Close();//}// Update is called once per frame//连接数据库public void Conn(){//获取或设置用于打开 SQL Server 数据库的字符串conn.ConnectionString = connsql;try{//打开数据库conn.Open();//打印数据库连接状态Console.WriteLine(conn.State);}catch (SqlException ex){Console.WriteLine("数据库打开失败!");Console.WriteLine(ex.Message);}}public void ConnClose(){conn.Close();conn.Dispose();}//insertpublic void Insert(Save save){String sql_insert = "insert into cubeInfo(cubeName,position_x,position_y,position_z,rotation_x,rotation_y,rotation_z,rotation_w) values(@NAME,@px,@py,@pz,@rx,@ry,@rz,@rw)";SqlCommand cmd_insert = new SqlCommand(sql_insert, conn);SqlParameter para1 = new SqlParameter("@NAME", save.cubeName);cmd_insert.Parameters.Add(para1);SqlParameter para2 = new SqlParameter("@px", save.x);cmd_insert.Parameters.Add(para2);SqlParameter para3 = new SqlParameter("@py", save.y);cmd_insert.Parameters.Add(para3);SqlParameter para4 = new SqlParameter("@pz", save.z);cmd_insert.Parameters.Add(para4);SqlParameter para5 = new SqlParameter("@rx", save.l);cmd_insert.Parameters.Add(para5);SqlParameter para6 = new SqlParameter("@ry", save.m);cmd_insert.Parameters.Add(para6);SqlParameter para7 = new SqlParameter("@rz", save.n);cmd_insert.Parameters.Add(para7);SqlParameter para8 = new SqlParameter("@rw", save.w);cmd_insert.Parameters.Add(para8);//对连接执行 Transact-SQL 语句并返回受影响的行数int res_1 = cmd_insert.ExecuteNonQuery();Console.WriteLine(res_1);}//updatepublic void update(){string sql_update = "update Table_1 set name=@NAME where id=@ID;";SqlCommand cmd_update = new SqlCommand(sql_update, conn);cmd_update.Parameters.AddWithValue("@ID", "3");cmd_update.Parameters.AddWithValue("@NAME", "Bit100");int res_2 = cmd_update.ExecuteNonQuery();Console.WriteLine(res_2);}//deletepublic void delete(){string sql_delete = "DELETE FROM cubeInfo ";SqlCommand cmd_delete = new SqlCommand(sql_delete, conn);int res_3 = cmd_delete.ExecuteNonQuery();//string sql_delete = "DELETE FROM Table_1 WHERE name=@NAME;";//SqlCommand cmd_delete = new SqlCommand(sql_delete, conn);//cmd_delete.Parameters.AddWithValue("@NAME", "Bit106");//int res_3 = cmd_delete.ExecuteNonQuery();//Console.WriteLine(res_3);}//selectpublic List<Save> select(){List<Save> listSave = new List<Save>();//定义查询语句String sql = "select * from cubeInfo";SqlCommand sqlComm = new SqlCommand(sql, conn);//接收查询到的sql数据SqlDataReader reader = sqlComm.ExecuteReader();//读取数据while (reader.Read()){// save.cubeName = reader["cubeName"].ToString();Save save = new Save();save.cubeName = reader.GetString(2);save.x = reader.GetDouble(3);save.y = reader.GetDouble(4);save.z = reader.GetDouble(5);save.l = reader.GetDouble(6);save.m = reader.GetDouble(7);save.n = reader.GetDouble(8);save.w = reader.GetDouble(9);listSave.Add(save);/*** vector 中xyz等坐标都是float类型 坐标存为float时 SqlDataReader读取却只能为double 不然报错 double丢失精度* 目前将save里float改为了double类型 目测可以改为存为string 取出来后再转float*///float ss = (float)reader.GetDouble(3);//save.x = float.Parse(reader.GetValue(3).ToString()); float sss = reader.GetFloat(4);//save.x = reader.GetFloat(3);//save.y = (float)reader.GetValue(4);//save.x = reader["position_x"].;//save.y = reader["position_y"].ToString();//reader["position_z"].ToString();//reader["rotation_x"].ToString();//reader["rotation_y"].ToString();//reader["rotation_z"].ToString();//reader["rotation_w"].ToString();//打印// Console.WriteLine(reader["uid"].ToString());// Console.WriteLine(reader["name"].ToString());}reader.Close();return listSave;}//调用存储过程public void procedure(){SqlCommand cmd = new SqlCommand("testInsert", conn);cmd.CommandType = CommandType.StoredProcedure;//告知执行存储过程//传参数cmd.Parameters.AddWithValue("@Uid", "106");cmd.Parameters.AddWithValue("@Name", "Bit106");int res = cmd.ExecuteNonQuery();Console.WriteLine(res);}//批量写入public void insertBulk(){DataTable dt = GetTableSchema();SqlBulkCopy bulkCopy = new SqlBulkCopy(conn);//获取服务器上目标表的名称bulkCopy.DestinationTableName = "Table_1";bulkCopy.BatchSize = dt.Rows.Count;for (int i = 0, j = 107; i < 100; i++, j++){//创建与该表结构相同的行DataRow dr = dt.NewRow();dr[1] = j;dr[2] = "Bit" + j;dt.Rows.Add(dr);}if (dt != null && dt.Rows.Count != 0){try{//将内存中数据表的记录写到服务器上的目标表中bulkCopy.WriteToServer(dt);}catch (Exception ex){Console.WriteLine(ex.Message);}}//Console.WriteLine(string.Format("插入{0}条记录", 100));}private static DataTable GetTableSchema(){//内存中建一个数据表DataTable dt = new DataTable();//获取该数据表的列dt.Columns.AddRange(new DataColumn[] {new DataColumn("id",typeof(int)),new DataColumn("uid",typeof(int)),new DataColumn("name",typeof(string))});return dt;}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class run : MonoBehaviour
{public GameObject Axis;//轴,用于选择围绕中心public float RotateSpeed;//旋转速度// Use this for initialization// Use this for initializationprivate void Start(){}// Update is called once per frameprivate void Update(){this.transform.RotateAround(Axis.transform.position, Vector3.up, RotateSpeed);}
}
后续再看情况更新…
相关文档
基于unity3D的可视化仓储.pdf