006-unity3d GUI初识、贴图、自定义鼠标指针

时间:2023-03-09 20:52:48
006-unity3d GUI初识、贴图、自定义鼠标指针

一、gui概念

无论摄像机拍摄到的图像怎么变换,GUI永远显示在屏幕上,不受变形、碰撞、光照的影响。
对话框、战斗值、能量等。
示例:用手机录像,摄像的参数不会随着拍摄场景变换。
GUI基础
GUI部分是每帧擦除重绘的,只应该在OnGUI中绘制GUI,按钮:GUILayout.Button(“Hello”);只读标签GUILayout.label()[注意脚本要实例化到GameObject上]
(引申)GUI有很对细节问题,比如GUI的绘制机制、如何响应鼠标点击、布局、如何获取设置控件。窗口等都和普通的窗口程序不一样()。其中还有NGUI、2DToolKit等

示例

在脚本中

    void OnGUI()
{
GUILayout.Button("hello");
}

Material 是3D贴图;Texture是2D贴图,也就是GUI。

二、贴图材质Material画皮

  给GUI贴图:给脚本增加一个Texture类型的public字段,GUI.DrawTexture(new Rect(100,100,100,100),MyTexture);把Texture画到界面上指定区域。直接把图片从project拖到脚本的MyTexture属性上即可。
  做项目推荐定义public Texture的做法,这样可以方便美工修改贴图便于分工。
  建项目时候应该不同类别不同文件夹Images、Scripts、Audios、Vedios

开发步骤

  1、在Assets中添加Images文件夹,增加需要的贴图图片

  2、在Assets中添加Materials文件夹,在文件夹中右键添加Material,命名为BoxMaterial,在Inspecttor中设置纹理等,纹理选用图片,Albedo前小圆点。

  3、静态资源绑定

    3.1、如果是静态资源,可以直接在Materials设置此项即可

    3.2、如果是动态加入

    1、先在脚本中增加属性,public Texture BoxMaterial;应该是简化的:public Texture BoxMaterial{get;set;}

    2、使用处增加:go.GetComponent<Renderer>().material = BoxMaterial;

    private GameObject goPlane;
public Material BoxMaterial; // Use this for initialization
void Start()
{
goPlane = GameObject.Find("Plane");
for (int i = ; i < ; i++)
{
for (int j = ; j < ; j++)
{
GameObject go = GameObject.CreatePrimitive(PrimitiveType.Cube);
go.transform.position = new Vector3(i, j, -);
//if (j % 2 == 0)
//{
// go.GetComponent<Renderer>().material.color = Color.red;
//}
go.AddComponent<Rigidbody>();
go.GetComponent<Renderer>().material = BoxMaterial;
go.AddComponent<AutoDestory>();
}
} }

    3、然后在组件对应的脚本上找到此属性

      006-unity3d GUI初识、贴图、自定义鼠标指针

    找到相应属性,进行可视化赋值即可,赋值第二部命名的BoxMaterial即可。

三、自定义鼠标指针

  屏幕坐标系(ScreenPoint)是以 屏幕 左下角(0,0)右上角(Screen.Width,Screen.Height),向上向右正方向,鼠标的位置Input.mousePosition是屏幕坐标系;GUI则是常规的以左上角为(0,0),向下向右为正方向。Screen.Width,Screen.Width是游戏屏幕的大小,不是电脑屏幕的大小;Screen.showCursor读写是否显示鼠标光标状态。自定义游侠光标:隐藏光标:5.0以前:在Start中,Screen.showCursor=false;5.0以后:在OnGUI中,Cursor.visible = false;声明属性public Texture CursorTexture找一个png格式鼠标图片放到Project中,拖后CursorTexture属性上;OnGUI中:

  1.增加ScreenCursor脚本,并将脚本拖拽至主摄像机,在脚本中增加Texture属性    

    public Texture CursorTexture;

  2、在unity3D中选择具体图片,赋值给上述属性

  3、在脚本中增加以下代码【基本代码】

    void OnGUI()
{
GUI.DrawTexture(new Rect(, , CursorTexture.width, CursorTexture.height), CursorTexture);
}

  4、动态跟随鼠标

    void OnGUI()
{
float x = Input.mousePosition.x - CursorTexture.width / ;
float y = Screen.height - Input.mousePosition.y - CursorTexture.height / ;
GUI.DrawTexture(new Rect(x, y, CursorTexture.width, CursorTexture.height), CursorTexture);
}

  5、隐藏光标:5.0以前:在Start中,Screen.showCursor=false;5.0以后:在OnGUI中,Cursor.visible = false;