赞
踩
新建项目,将Assets文件替换为我项目中的Assets文件,Assets/Scenes/UGUIScenes和Assets/Scenes/IMGUIScenes,分别是两种方式实现的场景,拖入Hierarchy即可用
using System.Collections; using System.Collections.Generic; using UnityEngine; public class IMGUIbloodBar : MonoBehaviour { public float curBlood = 5f; private float targetBlood = 5f; private Rect bloodBarArea; private Rect addButton; private Rect subButton; private int status = 0;//1:add -1:sub 0:不变 void Start () { bloodBarArea = new Rect(Screen.width/2 - 80, Screen.height/2, 200, 50); addButton = new Rect(Screen.width/2 - 80,Screen.height/2 + 30, 40, 20); subButton = new Rect(Screen.width/2 + 80,Screen.height/2 + 30, 40, 20); } public void addBlood() { targetBlood = targetBlood + 1 > 10f? 10f : targetBlood + 1; } public void subBlood() { targetBlood = targetBlood - 1 < 0f? 0f : targetBlood - 1; } private void OnGUI() { if (GUI.Button(addButton, " + ")) status = 1; if (GUI.Button(subButton, " - ")) status = -1; if (status==1) { addBlood(); status = 0; } else if (status==-1){ subBlood(); status = 0; } curBlood = Mathf.Lerp(curBlood, targetBlood, 0.1f); GUI.HorizontalScrollbar(bloodBarArea, 0f, curBlood, 0f, 10f); } }
菜单 GameObject -> 3D Object -> Plane,在游戏场景中创建一个plane,修改属性如下:
父对象人物预制使用的是Assets/Standard Assets/Charactors/ThirdPersonCharater/Prefabs/ThirdPersonController,为寻找方便,将其复制到Assets/Prefabs并重命名为Person。将人物预制(Assets/Prefabs/Person)拖入场景,将名称改为bloodBar_UGUI,修改属性如下:
修改Main Camera属性如下:
选择 bloodBar_UGUI 用上下文菜单(鼠标右键) -> UI -> Canvas,添加画布子对象
选择 bloodBar_UGUI 的 Canvas,用上下文菜单 -> UI -> Slider,添加滑条作为血条子对象
选择 bloodBar_UGUI 的 Canvas,在 Inspector 视图做如下设置:
展开 Slider
选择Slider,在 Inspector 视图
给 Canvas 添加以下脚本 LookAtCamera.cs,使血条任何时候面朝一个方向,从而达到面对摄像头的目的
using UnityEngine;
public class LookAtCamera : MonoBehaviour {
void Update () {
this.transform.rotation = Quaternion.LookRotation(new Vector3(0, 0, 1));
}
}
IMGUI实现血条
UGUI实现血条
菜单 GameObject -> 3D Object -> Plane,在游戏场景中创建一个plane,修改属性如下:
将血条预制bloodBar_UGUI拖入场景,修改属性如下:
修改Main Camera属性如下:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。