温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

[Unity3D]Unity3d开发常用代码集合

发布时间:2020-02-29 21:47:21 来源:网络 阅读:514 作者:蓬莱仙羽 栏目:游戏开发
  1. function OnGUI() {
  2. GUI.Label(Rect(1,1,100,20),"I'm a Label"); //1
  3. GUI.Box(Rect(1,21,100,20),"I'm a Box"); //2
  4. GUI.Button(Rect(1,41,100,20),"I'm a Button"); //3
  5. GUI.RepeatButton(Rect(1,61,120,20),"I'm a RepeatButton"); //4
  6. GUI.TextField(Rect(1,81,100,20),"I'm a TextFielld"); //5
  7. GUI.TextArea(Rect(1,101,100,40),"I'm a TextArea,\nMultiline"); //6
  8. GUI.Toggle(Rect(1,141,120,20),true,"I'm a Toggle true"); //7
  9. GUI.Toggle(Rect(1,161,120,20),false,"I'm a Toggle false"); //8
  10. GUI.Toolbar(Rect(1,181,160,20),-1,["Toolbar","Tool2","Tool3"); //9
  11. GUI.SelectionGrid(Rect(1,201,190,20),2,["Selection","Grid","select3"],3); //10
  12. GUI.HorizontalSlider(Rect(1,221,180,20),3.0,0,10.0); //11
  13. GUI.VerticalScrollbar(Rect(1,241,20,100),3.0,1,0.0,10.0); //12
  14.  
  15. //13
  16. GUI.BeginScrollView (Rect (200,10,100,100),Vector2.zero, Rect (0, 0, 220, 200));
  17. GUI.Label(Rect(0,0,100,20),"I'm a Label");
  18. GUI.EndScrollView();
  19. //14
  20. GUI.Window(0,Rect(200,129,100,100),funcwin,"window");
  21. }
  22.  
  23. function funcwin(windowID:int)
  24. {
  25. GUI.DragWindow(Rect(0,0,10000,2000));
  26. }

2 JS调用DLL

  1. import System;
  2. import System.Runtime.InteropServices;
  3. @DllImport("user32.dll")
  4. public static function MessageBox(Hwnd : int,text : String,Caption : String,iType : int) : int {};
  5.  
  6. function Start()
  7. {
  8. MessageBox(0, "API Message Box", "Win32 API", 64) ;
  9. }
  10. function Update () {
  11. }

3 物体标签

  1. var target : Transform; // Object that this label should follow
  2.  
  3. var offset = Vector3.up; // Units in world space to offset; 1 unit above object by default
  4. var clampToScreen = false; // If true, label will be visible even if object is off screen
  5. var clampBorderSize = .05; // How much viewport space to leave at the borders when a label is being clamped
  6. var useMainCamera = true; // Use the camera tagged MainCamera
  7. var cameraToUse : Camera; // Only use this if useMainCamera is false
  8. private var cam : Camera;
  9. private var thisTransform : Transform;
  10. private var camTransform : Transform;
  11.  
  12. function Start () {
  13. thisTransform = transform;
  14. if (useMainCamera)
  15. cam = Camera.main;
  16. else
  17. cam = cameraToUse;
  18. camTransform = cam.transform;
  19. }
  20.  
  21. function Update () {
  22. if (clampToScreen) {
  23. var relativePosition = camTransform.InverseTransformPoint(target.position);
  24. relativePosition.z = Mathf.Max(relativePosition.z, 1.0);
  25. thisTransform.position = cam.WorldToViewportPoint(camTransform.TransformPoint(relativePosition + offset));
  26. thisTransform.position = Vector3(Mathf.Clamp(thisTransform.position.x, clampBorderSize, 1.0-clampBorderSize),
  27. Mathf.Clamp(thisTransform.position.y, clampBorderSize, 1.0-clampBorderSize),
  28. thisTransform.position.z);
  29. }
  30. else {
  31. thisTransform.position = cam.WorldToViewportPoint(target.position + offset);
  32. }
  33. }
  34.  
  35. @script RequireComponent(GUIText)

4 unity3d读取保存xml文件

  1. import System;
  2. import System.Xml;
  3. import System.Xml.Serialization;
  4. import System.IO;
  5. import System.Text;
  6.  
  7. class CeshiData{
  8. var Ceshi1 : String;
  9. var Ceshi2 : String;
  10. var Ceshi3 : float;
  11. var Ceshi4 : int;
  12. }
  13.  
  14. class UserData
  15. {
  16. public var _iUser : CeshiData = new CeshiData();
  17. function UserData() { }
  18. }
  19.  
  20. private var c1 : String;
  21. private var c2 : String;
  22. private var c3 : float;
  23. private var c4 : int;
  24. private var _FileLocation : String;
  25. private var _FileName : String = "CeshiData.xml";
  26.  
  27. var myData : UserData[];
  28. private var tempData : UserData = new UserData();
  29.  
  30. var i : int = 0;
  31.  
  32. var GUISkin1 : GUISkin;
  33. var ShowData : int = 0;
  34. function Awake(){
  35. _FilelocationApplication.dataPath;
  36. }
  37.  
  38. function Start(){
  39. FirstSave();
  40. }
  41.  
  42. function FirstSave(){//初始化XML
  43. tempData._iUser.Ceshi1 = "?";
  44. tempData._iUser.Ceshi2 = "?";
  45. tempData._iUser.Ceshi3 = 0;
  46. tempData._iUser.Ceshi4 = 0;
  47. var writer : StreamWriter;
  48. var t : FileInfo = new FileInfo(_FileLocation+"/"+ _FileName);
  49. if(!t.Exists)
  50. {
  51. writer = t.CreateText();
  52. _data = SerializeObject(tempData);
  53. for(i=0;i<10;i++){
  54. writer.WriteLine(_data);
  55. }
  56. writer.Close();
  57. }
  58.  
  59. }
  60.  
  61. function Save(sc1 : String,sc2 : String,sc3 : float,sc4 : int){//保存数据到指定的XMl里
  62.  
  63. tempData._iUser.Ceshi1 = sc1;
  64. tempData._iUser.Ceshi2 = sc2;
  65. tempData._iUser.Ceshi3 = sc3;
  66. tempData._iUser.Ceshi4 = sc4;
  67.  
  68. var writer : StreamWriter;
  69. var t : FileInfo = new FileInfo(_FileLocation+"/"+ _FileName);
  70. t.Delete();
  71. writer = t.CreateText();
  72. _data = SerializeObject(tempData);
  73. for(i=0;i<10;i++){
  74. writer.WriteLine(_data);
  75. }
  76. writer.Close();
  77.  
  78. }
  79.  
  80. function Load(){//读取保存在XML里的数据
  81. var r : StreamReader = File.OpenText(_FileLocation+"/"+ _FileName);
  82. var _info : String ;
  83. for(i=0;i<10;i++){
  84. _info = r.ReadLine();
  85. _data_info;
  86. myData[i] = DeserializeObject(_data);
  87. }
  88. r.Close();
  89. }
  90.  
  91. function OnGUI() {
  92. GUI.skin = GUISkin1;
  93. if(GUI.Button(Rect(0,0,100,40),"save")){
  94. Save("ceshi1","ceshi2",1.23,50);//要显示中文需设定中文字体
  95. }
  96. if(GUI.Button(Rect(200,0,100,40),"load")){
  97. Load();
  98. ShowData = 1;
  99. }
  100. if(ShowData == 1){
  101. GUI.Label(Rect(170,170+53*0,150,50),myData[0]._iUser.Ceshi1);
  102. GUI.Label(Rect(370,170+53*0,150,50),myData[0]._iUser.Ceshi2);
  103. GUI.Label(Rect(550,170+53*0,150,50),myData[0]._iUser.Ceshi3 + "");
  104. GUI.Label(Rect(760,170+53*0,150,50),myData[0]._iUser.Ceshi4 + "");
  105.  
  106. GUI.Label(Rect(170,170+53*1,150,50),myData[1]._iUser.Ceshi1);
  107.  
  108. GUI.Label(Rect(370,170+53*2,150,50),myData[2]._iUser.Ceshi2);
  109.  
  110. GUI.Label(Rect(550,170+53*3,150,50),myData[3]._iUser.Ceshi3 + "");
  111.  
  112. GUI.Label(Rect(760,170+53*4,150,50),myData[4]._iUser.Ceshi4 + "");
  113. }
  114. }
  115.  
  116. //================================================================================
  117. function UTF8ByteArrayToString(characters : byte[] )
  118. {
  119. var encoding : UTF8Encoding = new UTF8Encoding();
  120. var constructedString : String = encoding.GetString(characters);
  121. return (constructedString);
  122. }
  123.  
  124. //byte[] StringToUTF8ByteArray(string pXmlString)
  125. function StringToUTF8ByteArray(pXmlString : String)
  126. {
  127. var encoding : UTF8Encoding = new UTF8Encoding();
  128. var byteArray : byte[] = encoding.GetBytes(pXmlString);
  129. return byteArray;
  130. }
  131.  
  132. // Here we serialize our UserData object of myData
  133. //string SerializeObject(object pObject)
  134. function SerializeObject(pObject : Object)
  135. {
  136. var XmlizedString : String = null;
  137. var memoryStream : MemoryStream = new MemoryStream();
  138. var xs : XmlSerializer = new XmlSerializer(typeof(UserData));
  139. var xmlTextWriter : XmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
  140. xs.Serialize(xmlTextWriter, pObject);
  141. memoryStream = xmlTextWriter.BaseStream; // (MemoryStream)
  142. XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
  143. return XmlizedString;
  144. }
  145.  
  146. // Here we deserialize it back into its original form
  147. //object DeserializeObject(string pXmlizedString)
  148. function DeserializeObject(pXmlizedString : String)
  149. {
  150. var xs : XmlSerializer = new XmlSerializer(typeof(UserData));
  151. var memoryStream : MemoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));
  152. var xmlTextWriter : XmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
  153. return xs.Deserialize(memoryStream);
  154. }

5 单击物体弹出对话框

  1. static var WindowSwitch : boolean = false;
  2. var mySkin : GUISkin;
  3. var windowRect = Rect (200, 80, 240, 100);
  4. function OnGUI ()
  5. {
  6. if(WindowSwitch == true)
  7. {
  8. GUI.skin = mySkin;
  9. windowRect = GUI.Window (0, windowRect, WindowContain, "测试视窗");
  10. }
  11. }
  12. function WindowContain (windowID : int)
  13. {
  14. if (GUI.Button (Rect (70,40,100,20), "关闭视窗"))
  15. {
  16. WindowSwitch = false;
  17. }
  18. }
  19.  
  20. function OnMouseEnter ()
  21. {
  22. renderer.material.color = Color.red;
  23. }
  24. function OnMouseDown ()
  25. {
  26. Func_GUIWindow.WindowSwitch = true;
  27. }
  28. function OnMouseExit ()
  29. {
  30. renderer.material.color = Color.white;
  31. }

6 读取txt文本

  1. using UnityEngine;
  2. using System.Collections;
  3. using System.IO;
  4. using System.Text;
  5.  
  6. public class ReadTxt : MonoBehaviour {
  7. string path = "D:\\txtName.txt";
  8. StreamReader smRead = new StreamReader(path,
  9. Encoding.Default); //设置路径
  10.  
  11. string line;
  12.  
  13. void Update () {
  14.  
  15. if ((line = smRead.ReadLine()) != null) {
  16. string[] arrStr = line.Split('|'); //分割符 “|”
  17. id1 = arrStr[0].ToString();
  18. name = arrStr[1].ToString();
  19. sfz = arrStr[2].ToString();
  20. }
  21. }
  22. }

7 截屏

  1. function OnMouseDown() {
  2. Application.CaptureScreenshot("Screenshot.png");
  3. }

8 下拉菜单

  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Text.RegularExpressions;
  5. public class DropDownList : MonoBehaviour
  6. {
  7. private Rect DropDownRect; // Size and Location for drop down
  8. private Transform currentRoot; // selected object transform
  9. private Vector2 ListScrollPos; // scroll list position
  10. public string selectedItemCaption; // name of selected item
  11. private string lastCaption; // last selected item
  12. private int guiWidth; // width of drop list
  13. private int guiHight; // hight of drop list
  14. private bool textChanged; // if text in text box has changed look for item
  15. private bool clearDropList; // clear text box
  16. public bool DropdownVisible; // show drop down list
  17. public bool updateInfo; // update info window
  18.  
  19. public Transform root; // top of the Hierarchy
  20. public GUISkin dropSkin; // GUISkin for drop down list
  21. public int itemtSelected; // index of selected item
  22. public bool targetChange; // text in text box was changed, update list
  23.  
  24. public class GuiListItem //The class that contains our list items
  25. {
  26. public string Name; // name of the item
  27. public int GuiStyle; // current style to use
  28. public int UnSelectedStyle; // unselected GUI style
  29. public int SelectedStyle; // selected GUI style
  30. public int Depth; // depth in the Hierarchy
  31. public bool Selected; // if the item is selected
  32. public bool ToggleChildren; // show child objects in list
  33.  
  34. // constructors
  35. public GuiListItem(bool mSelected, string mName, int iGuiStyle, bool childrenOn, int depth)
  36. {
  37. Selected = mSelected;
  38. Name = mName;
  39. GuiStyle = iGuiStyle;
  40. ToggleChildren = childrenOn;
  41. Depth = depth;
  42. UnSelectedStyle = 0;
  43. SelectedStyle = 0;
  44.  
  45. }
  46. public GuiListItem(bool mSelected, string mName)
  47. {
  48. Selected = mSelected;
  49. Name = mName;
  50. GuiStyle = 0;
  51. ToggleChildren = true;
  52. Depth = 0;
  53. UnSelectedStyle = 0;
  54. SelectedStyle = 0;
  55. }
  56. public GuiListItem(string mName)
  57. {
  58. Selected = false;
  59. Name = mName;
  60. GuiStyle = 0;
  61. ToggleChildren = true;
  62. Depth = 0;
  63. UnSelectedStyle = 0;
  64. SelectedStyle = 0;
  65. }
  66.  
  67. // Accessors
  68. public void enable()// don't show in list
  69. {
  70. Selected = true;
  71. }
  72. public void disable()// show in list
  73. {
  74. Selected = false;
  75. }
  76. public void setStlye(int stlye)
  77. {
  78. GuiStyle = stlye;
  79. }
  80. public void setToggleChildren(bool childrenOn)
  81. {
  82. ToggleChildren = childrenOn;
  83. }
  84. public void setDepth(int depth)
  85. {
  86. Depth = depth;
  87. }
  88. public void SetStyles(int unSelected, int selected)
  89. {
  90. UnSelectedStyle = unSelected;
  91. SelectedStyle = selected;
  92. }
  93. }
  94.  
  95. //Declare our list of stuff
  96. public List MyListOfStuff;
  97.  
  98. // Initialization
  99. void Start()
  100. {
  101. guiWidth = 400;
  102. guiHight = 28;
  103. // Manually position our list, because the dropdown will appear over other controls
  104. DropDownRect = new Rect(10, 10, guiWidth, guiHight);
  105. DropdownVisible = false;
  106. itemtSelected = -1;
  107. targetChange = false;
  108. lastCaption = selectedItemCaption = "Select a Part...";
  109.  
  110. if (!root)
  111. root = gameObject.transform;
  112.  
  113. MyListOfStuff = new List(); //Initialize our list of stuff
  114. // fill the list
  115. BuildList(root);
  116. // set GUI for each item in list
  117. SetupGUISetting();
  118. // fill the list
  119. FillList(root);
  120. }
  121.  
  122. void OnGUI()
  123. {
  124. //Show the dropdown list if required (make sure any controls that should appear behind the list are before this block)
  125. if (DropdownVisible)
  126. {
  127. GUI.SetNextControlName("ScrollView");
  128. GUILayout.BeginArea(new Rect(DropDownRect.xMin, DropDownRect.yMin + DropDownRect.height, guiWidth, Screen.height * .25f), "", "box");
  129. ListScrollPos = GUILayout.BeginScrollView(ListScrollPos, dropSkin.scrollView);
  130. GUILayout.BeginVertical(GUILayout.Width(120));
  131.  
  132. for (int i = 0; i < MyListOfStuff.Count; i++)
  133. {
  134. if (MyListOfStuff[i].Selected && GUILayout.Button(MyListOfStuff[i].Name, dropSkin.customStyles[MyListOfStuff[i].GuiStyle]))
  135. {
  136. HandleSelectedButton(i);
  137. }
  138. }
  139. GUILayout.EndVertical();
  140. GUILayout.EndScrollView();
  141. GUILayout.EndArea();
  142. }
  143. //Draw the dropdown control
  144. GUILayout.BeginArea(DropDownRect, "", "box");
  145. GUILayout.BeginHorizontal();
  146. string ButtonText = (DropdownVisible) ? "<<" : ">>";
  147. DropdownVisible = GUILayout.Toggle(DropdownVisible, ButtonText, "button", GUILayout.Width(32), GUILayout.Height(20));
  148. GUI.SetNextControlName("PartSelect");
  149. selectedItemCaption = GUILayout.TextField(selectedItemCaption);
  150. clearDropList = GUILayout.Toggle(clearDropList, "Clear", "button", GUILayout.Width(40), GUILayout.Height(20));
  151. GUILayout.EndHorizontal();
  152. GUILayout.EndArea();
  153. }
  154.  
  155. void Update()
  156. {
  157. //check if text box info changed
  158. if (selectedItemCaption != lastCaption)
  159. {
  160. textChanged = true;
  161. }
  162.  
  163. // if text box info changed look for part matching text
  164. if (textChanged)
  165. {
  166. lastCaption = selectedItemCaption;
  167. textChanged = false;
  168. // go though list to find item
  169. for (int i = 0; i < MyListOfStuff.Count; ++i)
  170. {
  171. if (MyListOfStuff[i].Name.StartsWith(selectedItemCaption, System.StringComparison.CurrentCultureIgnoreCase))
  172. {
  173.  
  174. MyListOfStuff[i].enable();
  175. MyListOfStuff[i].ToggleChildren = false;
  176. MyListOfStuff[i].GuiStyle = MyListOfStuff[i].UnSelectedStyle;
  177. }
  178. else
  179. {
  180. MyListOfStuff[i].disable();
  181. MyListOfStuff[i].ToggleChildren = false;
  182. MyListOfStuff[i].GuiStyle = MyListOfStuff[i].UnSelectedStyle;
  183. }
  184. }
  185.  
  186. for (int i = 0; i < MyListOfStuff.Count; ++i) { // check list for item int test = string.Compare(selectedItemCaption, MyListOfStuff[i].Name, true); if (test == 0) { itemtSelected = i; targetChange = true; break; // stop looking when found } } } // reset message if list closed and text box is empty if (selectedItemCaption == "" && !DropdownVisible) { lastCaption = selectedItemCaption = "Select a Part..."; ClearList(root); FillList(root); } // if Clear button pushed if (clearDropList) { clearDropList = false; selectedItemCaption = ""; } } public void HandleSelectedButton(int selection) { // do the stuff, camera etc itemtSelected = selection;//Set the index for our currently selected item updateInfo = true; selectedItemCaption = MyListOfStuff[selection].Name; currentRoot = GameObject.Find(MyListOfStuff[itemtSelected].Name).transform; // toggle item show child MyListOfStuff[selection].ToggleChildren = !MyListOfStuff[selection].ToggleChildren; lastCaption = selectedItemCaption; // fill my drop down list with the children of the current selected object if (!MyListOfStuff[selection].ToggleChildren) { if (currentRoot.childCount > 0)
  187. {
  188. MyListOfStuff[selection].GuiStyle = MyListOfStuff[selection].SelectedStyle;
  189. }
  190. FillList(currentRoot);
  191. }
  192. else
  193. {
  194. if (currentRoot.childCount > 0)
  195. {
  196. MyListOfStuff[selection].GuiStyle = MyListOfStuff[selection].UnSelectedStyle;
  197. }
  198. ClearList(currentRoot);
  199. }
  200. targetChange = true;
  201.  
  202. }
  203.  
  204. // show only items that are the root and its children
  205. public void FillList(Transform root)
  206. {
  207. foreach (Transform child in root)
  208. {
  209. for (int i = 0; i < MyListOfStuff.Count; ++i)
  210. {
  211. if (MyListOfStuff[i].Name == child.name)
  212. {
  213. MyListOfStuff[i].enable();
  214. MyListOfStuff[i].ToggleChildren = false;
  215. MyListOfStuff[i].GuiStyle = MyListOfStuff[i].UnSelectedStyle;
  216. }
  217. }
  218. }
  219. }
  220. // turn off children objects
  221. public void ClearList(Transform root)
  222. {
  223. //Debug.Log(root.name);
  224. Transform[] childs = root.GetComponentsInChildren();
  225. foreach (Transform child in childs)
  226. {
  227. for (int i = 0; i < MyListOfStuff.Count; ++i) { if (MyListOfStuff[i].Name == child.name && MyListOfStuff[i].Name != root.name) { MyListOfStuff[i].disable(); MyListOfStuff[i].ToggleChildren = false; MyListOfStuff[i].GuiStyle = MyListOfStuff[i].UnSelectedStyle; } } } } // recursively build the list so the hierarchy is in tact void BuildList(Transform root) { // for every object in the thing we are viewing foreach (Transform child in root) { // add the item MyListOfStuff.Add(new GuiListItem(false, child.name)); // if it has children add the children if (child.childCount > 0)
  228. {
  229. BuildList(child);
  230. }
  231. }
  232. }
  233.  
  234. public void ResetDropDownList()
  235. {
  236. selectedItemCaption = "";
  237. ClearList(root);
  238. FillList(root);
  239. }
  240.  
  241. public string RemoveNumbers(string key)
  242. {
  243. return Regex.Replace(key, @"\d", "");
  244. }
  245.  
  246. // sets the drop list elements to use the correct GUI skin custom style
  247. private void SetupGUISetting()
  248. {
  249. // set drop down list gui
  250. int depth = 0;
  251. // check all the parts for hierarchy depth
  252. for (int i = 0; i < MyListOfStuff.Count; ++i) { GameObject currentObject = GameObject.Find(MyListOfStuff[i].Name); Transform currentTransform = currentObject.transform; depth = 0; if (currentObject.transform.parent == root) // if under root { if (currentObject.transform.childCount > 0)
  253. {
  254. MyListOfStuff[i].GuiStyle = depth;
  255. MyListOfStuff[i].UnSelectedStyle = depth;
  256. MyListOfStuff[i].SelectedStyle = depth + 2;
  257. }
  258. else
  259. {
  260. MyListOfStuff[i].GuiStyle = depth + 1;
  261. MyListOfStuff[i].UnSelectedStyle = depth + 1;
  262. MyListOfStuff[i].SelectedStyle = depth + 1;
  263. }
  264.  
  265. MyListOfStuff[i].Depth = depth;
  266.  
  267. }
  268. else // if not under root find depth
  269. {
  270. while (currentTransform.parent != root)
  271. {
  272. ++depth;
  273. currentTransform = currentTransform.parent;
  274. }
  275. MyListOfStuff[i].Depth = depth;
  276. // set gui basied on depth
  277. if (currentObject.transform.childCount > 0)
  278. {
  279. MyListOfStuff[i].GuiStyle = depth * 3;
  280. MyListOfStuff[i].UnSelectedStyle = depth * 3;
  281. MyListOfStuff[i].SelectedStyle = (depth * 3) + 2;
  282. }
  283. else
  284. {
  285. MyListOfStuff[i].GuiStyle = depth * 3 + 1;
  286. MyListOfStuff[i].UnSelectedStyle = depth * 3 + 1;
  287. MyListOfStuff[i].SelectedStyle = depth * 3 + 1;
  288. }
  289. }
  290. }
  291. }
  292. }
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI