Unity C# 脚本常用代码
坐标位置相关
加载相关
UI操作相关
编辑器相关
坐标相关
世界坐标转屏幕坐标
// target 为物体对象(GameObject).
Camera.main.WorldToScreenPoint(target.gameObject.transform.position);
使用射线检测点击模型
private RaycastHit hit;
void Update() {
if (Input.GetMouseButtonDown(0)) {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
// 使用 Physics.Raycast 时请确保模型包含碰撞体( collider ) 不然无法被检测.
if (Physics.Raycast(ray, out hit)) {
GameObject obj = hit.collider.gameObject;
if (obj.tag.Equals("Player")) {
//判断 obj 的 Tag 是否为玩家.
}
}
}
}
加载相关
加载预制体
GameObject obj_1 = (GameObject)Resources.Load("Prefab/O_obj_1");
GameObject obj_2 = (GameObject)Resources.Load("Prefab/O_obj_2");
// 加载血条蓝条UI.
GameObject hpMpPanel = (GameObject)Resources.Load("Prefab/Hp_Mp_Panel");
// 实例化预制体.
GameObject hpMpPanelObj = GameObject.Instantiate(hpMpPanel);
UI操作相关
修改UI大小、位置等
// btn 为UI对象 (GameObject)
RectTransform rect = btn.GetComponent<RectTransform>();
// 设置位置
rect.anchoredPosition = new Vector3(100, 100, 0);
// 设置大小
rect.sizeDelta = new Vector2(145, 200);
编辑器相关
禁用动画位移
Animator 组件上 去掉 Apply Root Motion 选项