Gizmos用于场景中给出一个可视化的调试或辅助设置
游戏Scene场景中的灰色线条,绿色的碰撞体条纹等都是由Gizmos绘制的
如何开启Gizmos呢,在Scene和Game界面的右上角有一个Gizmos按钮(右边有小箭头能展开)
如何根据需求自定义Gizmos呢?
我们先创建一个脚本GizmosDemo.cs,在这个类中添加OnDrawGizmos(),并将该脚本挂载到游戏场景中的某个GameObject上去。
脚本如下:
using UnityEngine;
using System.Collections;
using UnityEngine;
using System.Collections;
public class GizmosDemo : MonoBehaviour {
#region Public Variables
public Color gizmosColor;
public float gizmosSize = 1;
public Vector3 posA;
public Vector3 posB;
#endregion
void OnDrawGizmos()
{
}
}
在添加了OnDrawGizmos方法后,我们可以再视图的右上角Gizmos中为挂在了我们GizmosDemos.cs的游戏体设置Unity自带的几个Gizmos的icon或自定义其Gizmos的icon
那么如何绘制我们自己想要的形状呢,首先我们在OnDrawGizmos中添加如下语句
//设置Gizmos颜色
Gizmos.color = gizmosColor;
//以当前物体位置为中心,1为半径画球
Gizmos.DrawSphere(transform.position, gizmosSize);
通过改变gizmosColor的值,可以改变Gizmos的颜色,而通过改变gizmosSize的值能改变Gizmos的大小:
Gizmos还有很多方法,都比较类似,查一下文档就知道怎么用了。
另外,之前我们绘制Gizmos都是在世界坐标系下绘制的,那怎么在物体坐标系下绘制呢?
——只要把Gizmos.matrix设置为transform.localToWorldMatrix即可
下面是以上知识点示例代码:
using UnityEngine;
using System.Collections;
public class GizmosDemo : MonoBehaviour {
public Color gizmosColor;
public Color gizmosLineColor;
public float gizmosSize;
public Vector3 posA;
public Vector3 posB;
public bool onOffSwitch = false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnDrawGizmos()
{
Matrix4x4 oldGizmos = Gizmos.matrix;
//The basics
Gizmos.color = gizmosColor;
//Gizmos.DrawSphere (transform.position, gizmosSize);
Gizmos.DrawCube(transform.position, new Vector3(gizmosSize, gizmosSize, gizmosSize));
Gizmos.color = gizmosLineColor;
//Gizmos.DrawWireCube (transform.position, gizmosSize);
Gizmos.DrawWireCube(transform.position, new Vector3(gizmosSize, gizmosSize, gizmosSize));
//Look into rays
Gizmos.color = Color.blue;
Gizmos.DrawRay (transform.position, transform.TransformDirection (Vector3.forward));
Gizmos.color = Color.red;
Gizmos.DrawRay (transform.position, transform.TransformDirection (Vector3.right));
Gizmos.color = Color.green;
Gizmos.DrawRay (transform.position, transform.TransformDirection (Vector3.up));
//Look into lines
//为了把sphere绘制在物体坐标系
Gizmos.matrix = transform.localToWorldMatrix;
Gizmos.color = Color.yellow;
Gizmos.DrawSphere (posA, gizmosSize * 0.5f);
Gizmos.DrawSphere (posB, gizmosSize * 0.5f);
Gizmos.color = gizmosLineColor;
Gizmos.DrawLine (posA, posB);
Gizmos.matrix = oldGizmos;
//Multi Icons
if (onOffSwitch)
{
//Assets目录下需要有一个Gizmos文件夹,存放下面用到的两张图片
Gizmos.DrawIcon (transform.position, "onSwitch_icon.png");
} else {
Gizmos.DrawIcon (transform.position, "offSwitch_icon.png");
}
}
}
效果如下:
最后推荐一篇相关文章http://blog.csdn.net/u010019717/article/details/46039081