1.canvas,screen模式和world模式区别:screen的绑定摄像机与canvas相对位置不会改变不可改变canvas,world模式下有个event camera相对位置可改变,canvas可改变,canvas就相当于一个3D物体。sorting,order layer规定canvas优先级。
2.富文本支持html标签。
3.控制image fill
public class imagetype : MonoBehaviour {
public Image imagel;
public float i = 0.0f;
}
void Update () {
imagel.type = Image.Type.Filled;
imagel.fillMethod = Image.FillMethod.Radial360;
imagel.fillAmount = i;
if (i >= 1.0f) { i = 0.0f; }
i = i + 0.002f; }
4.控制按钮
public class button : MonoBehaviour { public Image image_sp;
public Text text_sp;
public Text text_btn; public void open_close(){
if(text_btn.text == "打开图片"){
image_sp.gameObject.SetActive(true);
text_btn.text = "关闭图片";
text_sp.text = "无敌是多么寂寞";
}
else {
image_sp.gameObject.SetActive(false);
text_btn.text = "打开图片";
text_sp.text = "无敌?";
}
5.控制按钮,内建图片数组
public class button1 : MonoBehaviour { public Image image_sp;
public Sprite[] image_sps;
private string select_name;
private int i;
public void sp()
{
select_name = EventSystem.current.currentSelectedGameObject.name;
if (select_name == "Button_left")
{
if (i <= 0) { i = image_sps.Length - 1; }
image_sp.overrideSprite = image_sps[--i];
}
else
{
if (i >= image_sps.Length - 1) { i = 0; }
image_sp.overrideSprite = image_sps[++i];
}
6.锚点必须在他的父对象内设置,如果没有父对象或者父对象没有锚点那么他就没有锚点。
7.InputField。Navigation自动匹配发布导航信息。
public class input_js : MonoBehaviour {
public Text text_jg;
public InputField input1;
public InputField input2;
public InputField input_to;
public GameObject panel_tc; public void js(){
text_jg.text = (int.Parse(input1.text) - int.Parse(input2.text)).ToString();
}
public void tc()
{
panel_tc.SetActive(true);
}
public void yes()
{
text_jg.text = input_to.text;
panel_tc.SetActive(false);
}
public void no()
{ panel_tc.SetActive(false);
} }
8.xml本地存储登录案例Application.OpenURL("http://wwww.4399.com");
这里的涉及到未包含的库,需要引入一个dll文件,参考思考问题博客。登录窗口脚本,xml文件的创建。dll的引用。var隐式类型。
using System.IO;
using System.Xml;
public class dengl : MonoBehaviour
{
public Image image_zc;
public Text text_info;
public Image image_ty_xxk;
public Text text_ts;
public InputField inputField_yhzh;
public InputField inputField_yhmm;
public InputField inputField_qrmm;
public InputField inputField_yhdh;
public InputField inputField_yhqq;
public InputField inputField_zh;
public InputField inputField_mm;
private string _xmlpath;//yong hu wen jian,_xmlpath = Application.dataPath + "/user.xml";
//获得date路径只能在主线程赋值,不能再moonbehaviour构造函数赋值如上
/* public void text()
{
ty_xxk("用户名或密码不能为空");
}*/
void Start()
{
_xmlpath = Application.dataPath + "/user.xml";
if (!File.Exists(_xmlpath))
{
XmlDocument xmlDoc = new XmlDocument();//xin jian xml shi li
XmlElement root = xmlDoc.CreateElement("Root");//gen jie dian , zui shang ceng jie dian
xmlDoc.AppendChild(root);//zhi jie dian
XmlElement user = xmlDoc.CreateElement("User");//yong hu jie dian
user.SetAttribute("user_name", "Admin");
user.SetAttribute("user_pass", "123456");
user.SetAttribute("user_tel", "18373290290");
user.SetAttribute("user_qq", "1780585054");
root.AppendChild(user);
xmlDoc.Save(_xmlpath);
Debug.Log("xml creat success");
}
}
public void Quit()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
public void open_zc()
{
image_zc.gameObject.SetActive(true);
}
public void close_zc()
{
image_zc.gameObject.SetActive(false);
}
public void ty_xxk(string str)
{
image_ty_xxk.gameObject.SetActive(true);
text_info.text = str;
text_ts.text = str;
}
public void ty_xxk_close(string str)
{
image_ty_xxk.gameObject.SetActive(false); }
public void zc()
{
if(inputField_yhzh.text == ""|| inputField_yhmm.text == "" || inputField_qrmm.text == "" || inputField_yhdh.text == "" || inputField_yhqq.text == ""){
ty_xxk("信息不完整!有空的项目!");
return;
}
if (inputField_yhmm.text != inputField_qrmm.text)
{
ty_xxk("两次输入的密码不一致");
return;
}
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(_xmlpath);
XmlNodeList nodeList = xmlDoc.SelectSingleNode("Root").ChildNodes;
foreach (XmlElement xe in nodeList)
{
if (xe.GetAttribute("user_name") == inputField_yhzh.text)
ty_xxk("该用户名已被占用!请更换用户名!"); }
//ty_xxk("恭喜该用户名可以使用");
//qu de gen jie dian
XmlNode root = xmlDoc.SelectSingleNode("Root");
//chuang jian xin jie dian
XmlElement user = xmlDoc.CreateElement("User");
user.SetAttribute("user_name", inputField_yhzh.text);
user.SetAttribute("user_pass", inputField_yhmm.text);
user.SetAttribute("user_tel", inputField_yhdh.text);
user.SetAttribute("user_qq", inputField_yhqq.text);
//jiang xin jie dian jia ru gen jie dian
root.AppendChild(user);
//bao cun wen jian
xmlDoc.Save(_xmlpath);
ty_xxk("恭喜注册成功");
inputField_yhzh.text = "";
inputField_yhmm.text = "";
inputField_qrmm.text = "";
inputField_yhdh.text = "";
inputField_yhqq.text = ""; }
public void denglu()
{
if (inputField_zh.text == "" || inputField_mm.text == "")
{
ty_xxk("用户名或者密码不能为空!");
return;
}
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(_xmlpath);
XmlNodeList nodeList = xmlDoc.SelectSingleNode("Root").ChildNodes;
foreach(XmlElement xe in nodeList)
{
if(xe.GetAttribute("user_name") == inputField_zh.text)
{
var mima = xe.GetAttribute("user_pass");
if(inputField_mm.text == mima)
{
ty_xxk("登录成功!");
Application.OpenURL("http://wwww.4399.com");
return;
}else
{
ty_xxk("登录失败!密码错误!");
return;
}
}
}
ty_xxk("此用户账号还没有注册!请注册!");
}
9.Toggle。 GameObject.Find 是不是不能找到一个物体的子物体?bg1,2,3,4是bg的子物体。
public class qh_bj : MonoBehaviour { private GameObject root;
private GameObject oldobj = null;
private GameObject newobj = null;
// Use this for initialization
void Start () {
root = GameObject.Find("bg");
oldobj = root.transform.Find("bg1").gameObject;
Debug.Log(oldobj.name);
}
public void print_name()
{
string s = EventSystem.current.currentSelectedGameObject.name;
//Debug.log(str);
switch (s)
{
case "Toggle1":
newobj = root.transform.Find("bg1").gameObject;
newobj.SetActive(true);
oldobj.SetActive(false);
oldobj = newobj;
oldobj.SetActive(true);
break;
case "Toggle2":
newobj = root.transform.Find("bg2").gameObject;
newobj.SetActive(true);
oldobj.SetActive(false);
oldobj = newobj;
oldobj.SetActive(true);
break;
case "Toggle3":
newobj = root.transform.Find("bg3").gameObject;
newobj.SetActive(true);
oldobj.SetActive(false);
oldobj = newobj;
oldobj.SetActive(true);
break;
case "Toggle4":
newobj = root.transform.Find("bg4").gameObject;
newobj.SetActive(true);
oldobj.SetActive(false);
oldobj = newobj;
oldobj.SetActive(true);
break;
}
}
10.Toggle2 Find子物体
public class qh_wz : MonoBehaviour {
public Text text1;
public void t_event2(bool xz)
{
string tt = transform.FindChild("Label").GetComponent<Text>().text;
bool bl = GetComponent<Toggle>().isOn;
if (bl)
{
text1.text = text1.text + tt + "真" + "\n";
}else
{
text1.text = text1.text + tt + "假" + "\n";
}
}
FindChild改成Find也是可以的。
11.slider模拟血条
public class xuetiao : MonoBehaviour {
public Text text1;
public Slider slider2;
public void dis_slider_value()
{
text1.text = slider2.value.ToString();
}
public void zx()
{
slider2.value = slider2.value + 60;
}
public void jx()
{
slider2.value = slider2.value - 60;
}
12.slider,建立materia彩纸detail动态纹理 ,纹理偏移, Time.time是从程序开始执行到现在的时间,,,,deltaTime=0.0166,要加Position As SUV1组件
public class mov : MonoBehaviour {
public Light l1;
Material mOriginal;
Image mSprite;
public Vector2 scrollPerSecond = Vector2.zero;
public AudioSource myAudio;
public Text text_ln;
public Text text_vn;
// Use this for initialization
void Start () {
mSprite = GetComponent<Image>();
mOriginal = mSprite.material;
}
// Update is called once per frame
void Update () {
if (mOriginal != null){
Texture tex = mOriginal.GetTexture("_DetailTex");
if (tex != null)
{
mOriginal.SetTextureOffset("_DetailTex", scrollPerSecond * Time.time);
}
}
}
public void light1(float v)
{
l1.intensity = v;
text_ln.text = v.ToString();
}
public void vol(float v)
{
myAudio.volume = v;
text_vn.text = v.ToString();
}
13.scrollbar。编写一个带浮点型参数的函数,scrollar传递过去
GetComponent.<RectTransform>().localPosition = new Vector3(1f,1f,1f); GetComponent.<RectTransform>().localScale = new Vector3(1f,1f,1f);
14.Layout。child Force Expand与Flexible功能一样,文字和image自带适宜尺寸,raw image没有适宜尺寸。
15.模拟下拉组合框,迭代访问子物体
public class list : MonoBehaviour {
public GameObject list_close;
public InputField field1;
public Text text_dis;
// Use this for initialization
void Start () { }
public void combox()
{
for(int i = 0; i < this.transform.childCount; i++)
{
field1.text = this.transform.GetChild(i).GetComponent<Text>().text;
text_dis.text = "你选择的是" + field1.text;
}
}
public void combox_close()
{
list_close.SetActive(false);
GameObject.Find("Toggle").GetComponent<Toggle>().isOn = false;
}
}
16.事件类!!!!!!!!!!!!!!!!!!!!!!!!!!接口
public class scroll : MonoBehaviour,IMoveHandler,IScrollHandler{
//默认是事件 是Image 如果鼠标点击了别处 那么事件就变了 就不能控制Image了
public Text text1;
public Camera maincamera;
private static float f1; // Use this for initialization
void Start () { } // Update is called once per frame
void Update () { }
public void OnMove(AxisEventData eventData)
{
text1.text = eventData.moveDir.ToString();
}
public void OnScroll(PointerEventData eventData)
{
f1 = f1 + eventData.scrollDelta.y * 3f;
maincamera.fieldOfView = Mathf.Clamp(f1, 1f, 179f);
text1.text = eventData.scrollDelta.ToString();
}
}
public class select : MonoBehaviour,ISelectHandler,ICancelHandler,IPointerDownHandler,IUpdateSelectedHandler,IDeselectHandler,ISubmitHandler{
//物体身上必须有脚本才能 实现事件功能
public Text text1;
private int i = 0;
public void OnSelect(BaseEventData eventData)
{
//text1.text = "我被选择了" + eventData.selectedObject;
}
public void OnCancel(BaseEventData eventData)//按esc取消事件
{
text1.text = "我被取消了选择" + eventData.selectedObject;
}
public void OnPointerDown(PointerEventData eventData)
{
text1.text = eventData.position.ToString();//position属性可通过查看PointerEventData/Variables改为其他属性
}
public void OnUpdateSelected(BaseEventData eventData)
{
++i;
//text1.text = "我被选择了" + eventData.selectedObject + "OnUpdateSelected" + i;
}
public void OnDeselect(BaseEventData eventData)
{
text1.text = "我被取消了选择" + eventData.selectedObject + "OnDeselect";
}
public void OnSubmit(BaseEventData eventData)
{
text1.text = "我被提交了" + eventData.selectedObject + "Onsubmit";
}
Canvas Group组
CanvasGroup group = m_DraggingIcon.AddComponent<CanvasGroup>();
group.blocksRaycasts = false;
复制拖动装备案例
public class drag_zb : MonoBehaviour,IBeginDragHandler,IDragHandler,IEndDragHandler{
public Canvas cavs;
private GameObject m_DraggingIcon;
private RectTransform m_DraggingPlane;
// Use this for initialization
void Start () {
m_DraggingPlane = cavs.transform as RectTransform;
} // Update is called once per frame
void Update () { }
public void OnBeginDrag(PointerEventData eventData)
{
Debug.Log("OnBeginDrag:拖动开始事件:" + eventData.position);
m_DraggingIcon = new GameObject("icon");
m_DraggingIcon.transform.SetParent(cavs.transform, false);
m_DraggingIcon.transform.SetAsLastSibling();
var image = m_DraggingIcon.AddComponent<Image>();
CanvasGroup group = m_DraggingIcon.AddComponent<CanvasGroup>();
group.blocksRaycasts = false;
image.sprite = GetComponent<Image>().sprite;
image.SetNativeSize();
if(m_DraggingIcon != null)
{
var rt = m_DraggingIcon.GetComponent<RectTransform>();
Vector3 globalMousePos;
if (RectTransformUtility.ScreenPointToWorldPointInRectangle(m_DraggingPlane, eventData.position, eventData.pressEventCamera, out globalMousePos)){
rt.position = globalMousePos;
rt.rotation = m_DraggingPlane.rotation;
}
}
}
public void OnDrag(PointerEventData eventData)
{
Debug.Log("OnDrag:拖动中事件" + eventData.position);
if (m_DraggingIcon != null)
{
var rt = m_DraggingIcon.GetComponent<RectTransform>();
Vector3 globalMousePos;
if(RectTransformUtility.ScreenPointToWorldPointInRectangle(m_DraggingPlane,eventData.position,eventData.pressEventCamera,out globalMousePos))
{
rt.position = globalMousePos;
rt.rotation = m_DraggingPlane.rotation;
}
}
}
public void OnEndDrag (PointerEventData eventData)
{
Debug.Log("OnEndDrag:拖动结束事件" + eventData.position);
if (m_DraggingIcon != null)
{
Destroy(m_DraggingIcon);
}
}
粘贴复制的装备
public class drop_zb : MonoBehaviour,IDropHandler,IPointerEnterHandler,IPointerExitHandler{
public void OnDrop(PointerEventData data)
{
var originalObj = data.pointerDrag;
if (originalObj == null)
return;
var srcImage = originalObj.GetComponent<Image>();
if (srcImage == null)
return;
GetComponent<Image>().sprite = data.pointerDrag.GetComponent<Image>().sprite;
}
public void OnPointerEnter(PointerEventData eventData)
{
var originalObj = eventData.pointerDrag;
if (originalObj != null) { GetComponent<Image>().color = Color.yellow;
}
}
public void OnPointerExit(PointerEventData eventData)
{
var originalObj = eventData.pointerDrag;
if (originalObj == null)
{
return;
}
GetComponent<Image>().color = Color.white;
} }
选择事件提交事件
public class select : MonoBehaviour,ISelectHandler,ICancelHandler,IPointerDownHandler,IUpdateSelectedHandler,IDeselectHandler,ISubmitHandler{
//物体身上必须有脚本才能 实现事件功能
public Text text1;
private int i = 0;
public void OnSelect(BaseEventData eventData)
{
//text1.text = "我被选择了" + eventData.selectedObject;
}
public void OnCancel(BaseEventData eventData)//按esc取消事件
{
text1.text = "我被取消了选择" + eventData.selectedObject;
}
public void OnPointerDown(PointerEventData eventData)
{
text1.text = eventData.position.ToString();//position属性可通过查看PointerEventData/Variables改为其他属性
}
public void OnUpdateSelected(BaseEventData eventData)
{
++i;
//text1.text = "我被选择了" + eventData.selectedObject + "OnUpdateSelected" + i;
}
public void OnDeselect(BaseEventData eventData)
{
text1.text = "我被取消了选择" + eventData.selectedObject + "OnDeselect";
}
public void OnSubmit(BaseEventData eventData)
{
text1.text = "我被提交了" + eventData.selectedObject + "Onsubmit";
}
}
代码生成按钮物体并添加监听器
public class dtai_event : MonoBehaviour { public Canvas cavs;
public Text text1;
public Font f1;
public int counter;
// Use this for initialization
void Start () {
counter = 0;
} // Update is called once per frame
void Update () {
//Instantiate(pre, m_transform.position, m_transform.rotation); }
public void create_btn()
{
if (counter > 4)
return;
++counter;
var m_DraggingIcon = new GameObject("btn_" + counter);
m_DraggingIcon.transform.SetParent(cavs.transform, false);
m_DraggingIcon.transform.localPosition = gameObject.transform.localPosition + new Vector3(0, 60 * counter, 0);
m_DraggingIcon.AddComponent<Image>();
m_DraggingIcon.transform.localScale = new Vector3(0.8f, 0.3f, 1f);
m_DraggingIcon.transform.SetAsLastSibling(); var btn = m_DraggingIcon.AddComponent<Button>(); var tt = new GameObject("text_" + counter);
var text2 = tt.AddComponent<Text>();
text2.text = "按钮" + counter;
text2.color = Color.blue;
text2.resizeTextForBestFit = true;
text2.font = f1;
// text2.fontStyle = FontStyle.Bold;
text2.alignment = TextAnchor.MiddleLeft;
tt.transform.SetParent(m_DraggingIcon.transform, false);
tt.transform.SetAsLastSibling(); btn.onClick.AddListener(delegate ()
{
this.btn1click(m_DraggingIcon);
});// 匿名方法 添加 监听函数 }
public void btn1click(GameObject e)
{
text1.text = "你点击了" + e.name;
}
delegate定义委托 订阅事件 类里定义一个类!!!!!!!!!!!!!!!!!public class类public viod函数
public class wtuo_dyue : MonoBehaviour {
public Text text1;
private int counter;
private string disstr = "111111111111111111111111111";
private bool toggle1;
private int tt;
// Use this for initialization
void Start () {
counter = 0;
toggle1 = false;
tt = 100; } // Update is called once per frame
void Update () {
if (toggle1)
{
tt -= 5;
if (tt < 0)
{
timer_elapsed();
tt = 100;
}
}
}
public void start_out()
{
toggle1 = false;
}
//1 定义一个委托
public delegate void timearriveEventHandler(string str);
//时间到达类
public class Timer_arrived
{
//2 用委托定义事件 关键字event
public static event timearriveEventHandler timearrived;
public static void Start_time()
{
//触发事件
timearrived("oookkkk");
}
}
public void timer_elapsed()
{
if (counter < 1)
//3 订阅事件
Timer_arrived.timearrived += new timearriveEventHandler(WriteText);
Timer_arrived.Start_time(); }
//4 编写事件处理方法
public void WriteText(string s)
{
text1.text += disstr[counter++ % disstr.Length];
}
定义要发布的新闻
public class dingy_weit : MonoBehaviour {
public InputField InputField_title;
public InputField InputField_content;
//定义要发布的新闻类 参数
public class news_args
{
public string news_title = "news_title";
public string news_content = "news_content";
}
// 定义委托用于定义事件
public delegate void news_handler(object sender, news_args e);
//定义事件
public event news_handler News_build;
//定义触发事件的方法
public void build_news()
{
//生成触发事件参数
news_args news = new news_args();
news.news_title = InputField_title.text;
news.news_content = InputField_content.text;
if (News_build != null) ;//一定要检测 检测有人订阅
News_build(this, news); //this 当前脚本所在对象
}
}
接收或者取消订阅新闻
public class dingyue_wt : MonoBehaviour {
public GameObject s_news_center;
// Use this for initialization
public InputField InputField_title;
public InputField InputField_content;
public void listener_news_start()
{
s_news_center.GetComponent<dingy_weit>().News_build += Listener;
}
public void listener_news_stop()
{
s_news_center.GetComponent<dingy_weit>().News_build -= Listener;
}
public void Listener(object sender,dingy_weit.news_args e)
{
InputField_title.text = e.news_title;
InputField_content.text = e.news_content;
}
public void Start()
{
s_news_center.GetComponent<dingy_weit>().News_build += Listener;
}
17.UGUI界面案例,给载有动画组件的的物体添加脚本,可以给动画针添加事件脚本
using UnityEngine.SceneManagement; public class Game_manager : MonoBehaviour {
public Animator ani_text1;
public Animator ani_window;
public Animator ani_set;
public Animator ani_vudio;
void Awake()
{
ani_vudio = GameObject.Find("main_seting_audio").GetComponent<Animator>();
}
void Start()
{
ani_vudio.gameObject.SetActive(false);
}
public void text_in()
{
ani_text1.gameObject.SetActive(true);
ani_text1.SetBool("sp_in", true);
ani_window.SetBool("window_in", false);
StartCoroutine(WaitTime(10.0f));
//ani_window.gameObject.transform.parent.gameObject.SetActive(false)
}
public void main_window_in()
{
ani_window.SetBool("window_in", true);
}
IEnumerator WaitTime(float waittime)
{
yield return new WaitForSeconds(waittime);
this.main_window_in();
ani_text1.SetBool("sp_in", false);
ani_text1.gameObject.SetActive(false);
//在第一段动画没播完前改变Bool值,无法实现动画转换
}
public void Quit()
{
#if UNITY_EDITOR//预处理 写错 检测不出来
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
public void start_game()
{
//Application.LoadLevel("denglu");
SceneManager.LoadScene("denglu");
}
public void Set_in()
{
ani_window.SetBool("window_in", false);
ani_set.SetBool("set_in", true);
}
public void window_back()
{
ani_window.SetBool("window_in", true);
ani_set.SetBool("set_in", false);
}
public void vudio_in()
{
ani_vudio.gameObject.SetActive(true);
ani_vudio.SetBool("vudio_in", true); }
public void vudio_out()
{
ani_vudio.SetBool("vudio_in", false);
}