热门IT资讯网

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

发表于:2024-11-23 作者:热门IT资讯网编辑
编辑最后更新 2024年11月23日,function OnGUI() {GUI.Label(Rect(1,1,100,20),"I'm a Label"); //1GUI.Box(Rect(1,21,100,20),"I'm a Box
  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. //13
  15. GUI.BeginScrollView (Rect (200,10,100,100),Vector2.zero, Rect (0, 0, 220, 200));
  16. GUI.Label(Rect(0,0,100,20),"I'm a Label");
  17. GUI.EndScrollView();
  18. //14
  19. GUI.Window(0,Rect(200,129,100,100),funcwin,"window");
  20. }
  21. function funcwin(windowID:int)
  22. {
  23. GUI.DragWindow(Rect(0,0,10000,2000));
  24. }

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. function Start()
  6. {
  7. MessageBox(0, "API Message Box", "Win32 API", 64) ;
  8. }
  9. function Update () {
  10. }

3 物体标签

  1. var target : Transform; // Object that this label should follow
  2. var offset = Vector3.up; // Units in world space to offset; 1 unit above object by default
  3. var clampToScreen = false; // If true, label will be visible even if object is off screen
  4. var clampBorderSize = .05; // How much viewport space to leave at the borders when a label is being clamped
  5. var useMainCamera = true; // Use the camera tagged MainCamera
  6. var cameraToUse : Camera; // Only use this if useMainCamera is false
  7. private var cam : Camera;
  8. private var thisTransform : Transform;
  9. private var camTransform : Transform;
  10. function Start () {
  11. thisTransform = transform;
  12. if (useMainCamera)
  13. cam = Camera.main;
  14. else
  15. cam = cameraToUse;
  16. camTransform = cam.transform;
  17. }
  18. function Update () {
  19. if (clampToScreen) {
  20. var relativePosition = camTransform.InverseTransformPoint(target.position);
  21. relativePosition.z = Mathf.Max(relativePosition.z, 1.0);
  22. thisTransform.position = cam.WorldToViewportPoint(camTransform.TransformPoint(relativePosition + offset));
  23. thisTransform.position = Vector3(Mathf.Clamp(thisTransform.position.x, clampBorderSize, 1.0-clampBorderSize),
  24. Mathf.Clamp(thisTransform.position.y, clampBorderSize, 1.0-clampBorderSize),
  25. thisTransform.position.z);
  26. }
  27. else {
  28. thisTransform.position = cam.WorldToViewportPoint(target.position + offset);
  29. }
  30. }
  31. @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. class CeshiData{
  7. var Ceshi1 : String;
  8. var Ceshi2 : String;
  9. var Ceshi3 : float;
  10. var Ceshi4 : int;
  11. }
  12. class UserData
  13. {
  14. public var _iUser : CeshiData = new CeshiData();
  15. function UserData() { }
  16. }
  17. private var c1 : String;
  18. private var c2 : String;
  19. private var c3 : float;
  20. private var c4 : int;
  21. private var _FileLocation : String;
  22. private var _FileName : String = "CeshiData.xml";
  23. var myData : UserData[];
  24. private var tempData : UserData = new UserData();
  25. var i : int = 0;
  26. var GUISkin1 : GUISkin;
  27. var ShowData : int = 0;
  28. function Awake(){
  29. _FilelocationApplication.dataPath;
  30. }
  31. function Start(){
  32. FirstSave();
  33. }
  34. function FirstSave(){//初始化XML
  35. tempData._iUser.Ceshi1 = "?";
  36. tempData._iUser.Ceshi2 = "?";
  37. tempData._iUser.Ceshi3 = 0;
  38. tempData._iUser.Ceshi4 = 0;
  39. var writer : StreamWriter;
  40. var t : FileInfo = new FileInfo(_FileLocation+"/"+ _FileName);
  41. if(!t.Exists)
  42. {
  43. writer = t.CreateText();
  44. _data = SerializeObject(tempData);
  45. for(i=0;i<10;i++){
  46. writer.WriteLine(_data);
  47. }
  48. writer.Close();
  49. }
  50. }
  51. function Save(sc1 : String,sc2 : String,sc3 : float,sc4 : int){//保存数据到指定的XMl里
  52. tempData._iUser.Ceshi1 = sc1;
  53. tempData._iUser.Ceshi2 = sc2;
  54. tempData._iUser.Ceshi3 = sc3;
  55. tempData._iUser.Ceshi4 = sc4;
  56. var writer : StreamWriter;
  57. var t : FileInfo = new FileInfo(_FileLocation+"/"+ _FileName);
  58. t.Delete();
  59. writer = t.CreateText();
  60. _data = SerializeObject(tempData);
  61. for(i=0;i<10;i++){
  62. writer.WriteLine(_data);
  63. }
  64. writer.Close();
  65. }
  66. function Load(){//读取保存在XML里的数据
  67. var r : StreamReader = File.OpenText(_FileLocation+"/"+ _FileName);
  68. var _info : String ;
  69. for(i=0;i<10;i++){
  70. _info = r.ReadLine();
  71. _data_info;
  72. myData[i] = DeserializeObject(_data);
  73. }
  74. r.Close();
  75. }
  76. function OnGUI() {
  77. GUI.skin = GUISkin1;
  78. if(GUI.Button(Rect(0,0,100,40),"save")){
  79. Save("ceshi1","ceshi2",1.23,50);//要显示中文需设定中文字体
  80. }
  81. if(GUI.Button(Rect(200,0,100,40),"load")){
  82. Load();
  83. ShowData = 1;
  84. }
  85. if(ShowData == 1){
  86. GUI.Label(Rect(170,170+53*0,150,50),myData[0]._iUser.Ceshi1);
  87. GUI.Label(Rect(370,170+53*0,150,50),myData[0]._iUser.Ceshi2);
  88. GUI.Label(Rect(550,170+53*0,150,50),myData[0]._iUser.Ceshi3 + "");
  89. GUI.Label(Rect(760,170+53*0,150,50),myData[0]._iUser.Ceshi4 + "");
  90. GUI.Label(Rect(170,170+53*1,150,50),myData[1]._iUser.Ceshi1);
  91. GUI.Label(Rect(370,170+53*2,150,50),myData[2]._iUser.Ceshi2);
  92. GUI.Label(Rect(550,170+53*3,150,50),myData[3]._iUser.Ceshi3 + "");
  93. GUI.Label(Rect(760,170+53*4,150,50),myData[4]._iUser.Ceshi4 + "");
  94. }
  95. }
  96. //================================================================================
  97. function UTF8ByteArrayToString(characters : byte[] )
  98. {
  99. var encoding : UTF8Encoding = new UTF8Encoding();
  100. var constructedString : String = encoding.GetString(characters);
  101. return (constructedString);
  102. }
  103. //byte[] StringToUTF8ByteArray(string pXmlString)
  104. function StringToUTF8ByteArray(pXmlString : String)
  105. {
  106. var encoding : UTF8Encoding = new UTF8Encoding();
  107. var byteArray : byte[] = encoding.GetBytes(pXmlString);
  108. return byteArray;
  109. }
  110. // Here we serialize our UserData object of myData
  111. //string SerializeObject(object pObject)
  112. function SerializeObject(pObject : Object)
  113. {
  114. var XmlizedString : String = null;
  115. var memoryStream : MemoryStream = new MemoryStream();
  116. var xs : XmlSerializer = new XmlSerializer(typeof(UserData));
  117. var xmlTextWriter : XmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
  118. xs.Serialize(xmlTextWriter, pObject);
  119. memoryStream = xmlTextWriter.BaseStream; // (MemoryStream)
  120. XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
  121. return XmlizedString;
  122. }
  123. // Here we deserialize it back into its original form
  124. //object DeserializeObject(string pXmlizedString)
  125. function DeserializeObject(pXmlizedString : String)
  126. {
  127. var xs : XmlSerializer = new XmlSerializer(typeof(UserData));
  128. var memoryStream : MemoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));
  129. var xmlTextWriter : XmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
  130. return xs.Deserialize(memoryStream);
  131. }

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. function OnMouseEnter ()
  20. {
  21. renderer.material.color = Color.red;
  22. }
  23. function OnMouseDown ()
  24. {
  25. Func_GUIWindow.WindowSwitch = true;
  26. }
  27. function OnMouseExit ()
  28. {
  29. renderer.material.color = Color.white;
  30. }

6 读取txt文本

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

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