1.加载资源路径
在Assets路径里创建Resources文件夹
a.加载配置好的界面
GameObject obj = (GameObject)Resources.Load ("config/backbg"); if (obj) { Debug.Log ("Debug-------Debug--------"); obj = Instantiate (obj); obj.transform.localScale = new Vector3 (1, 1, 1); obj.transform.localPosition = new Vector3 (1, 1, 1); }
b.加载场景
SceneManager.LoadScene("scence_1");
c.加载控件
//查找控件---【文本框】 GameObject obj = GameObject.Find ("bind_gold_label"); //类型转换 Text bindGold = obj.GetComponent<Text>(); bindGold.text = "45678 <color=\"0xffff00\">zxxxczvc</color> "; //【按钮】 GameObject.Find ("Button").GetComponent<Button>().onClick.AddListener(delegate() { this.onBtnClick(); }) ; //【复选框】 Toggle Toggle3 = GameObject.Find ("Toggle3").GetComponent<Toggle> (); Toggle1.onValueChanged.AddListener(delegate(bool isTrue) { onToggleClick(isTrue); }) ; //【图片】, 资源路径 从Resources开始查询,不需要写文件后缀名 GameObject.Find ("gold").GetComponent<Image> ().sprite = Resources.Load("UI/mainui/coin", typeof(Sprite))as Sprite; //【RawImage】原生图片 GameObject.Find ("RawImage").GetComponent<RawImage> ().texture = Resources.Load ("UI/mainui/bg",typeof(Texture)) as Texture; //进度条 Slider sld = GameObject.Find ("Slider").GetComponent<Slider> (); sld.value = 0.30f; //滑动条 Scrollbar scb = GameObject.Find ("Scrollbar").GetComponent<Scrollbar> (); scb.value = 0.30f; //下拉框 Dropdown dropdown = GameObject.Find ("Dropdown").GetComponent<Dropdown> ();
2.疑难杂症
a.在画布(Canvas)上显示3D模型,需要添加一个摄像头(ui_Camera),观察这个界面 设置ui_Camera属性: <Clear nFlags> 为 【Depth only】 <Culling Mask> 为 【UI, Default】(勾选两项) <Depth> 为 【1】 主摄像机属性: <Culling Mask> 不勾选 【UI】
b.获取某个ugui界面的实例类型GameObject获取挂载的脚本
GameObject obj;
obj.GetComponent<脚本类名>(); //根据这个获得脚本下public的变量和方法
3.常用的
//--------------------------------- // 获取控件宽高 // 1.用作悬浮窗点击范围判断 // 2. //--------------------------------- Rect rect = GetComponent<RectTransform> ().rect; //--------------------------------- // 控件隐藏 //--------------------------------- Text ttext = new Text(); ttext.SetActive (false); //隐藏,反之显示
4.ugui 子节点坐标 与 点击坐标 的坐标系处于一致性
//参数是 画布上某个控件的子节点。 private bool checkRect(UnityEngine.GameObject obj){ Vector2 touchpos; Vector2 pos; Canvas UI = GetComponent<Canvas> (); //画布 Rect rect = obj.GetComponent<RectTransform> ().rect; RectTransformUtility.ScreenPointToLocalPointInRectangle(UI.transform as RectTransform, Input.mousePosition, UI.worldCamera, out touchpos); RectTransformUtility.ScreenPointToLocalPointInRectangle (UI.transform as RectTransform, obj.transform.position, UI.worldCamera, out pos); // Debug.Log("-------------touch---------------------"+ touchpos.x +" " + touchpos.y +" pos L" + pos); if ( touchpos.x > pos.x + rect.width/2 || touchpos.x < pos.x - rect.width/2 || touchpos.y > pos.y + rect.height/2 || touchpos.y < pos.y - rect.height/2 ){ return false; //触摸点之外 } return true; //触摸点之内 }