本文是关于怪物血量的教程,其中包含了血条设置,血条代码一系列指导。
示意图
一:血条设置
首先要创建一个空画布:
1.在层级栏鼠标右键选择UI一栏,再点击画布。
2.把渲染模式改为世界空间
3.创建一个空代码,这样可以一直让血条朝向摄像头(如果需要其他的需求可以再另该代码)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GuaiGu : MonoBehaviour
{
public Camera cam;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (cam == null)
cam = Camera.main;
transform.LookAt(transform.position + cam.transform.rotation * Vector3.forward, cam.transform.rotation * Vector3.up);//怪物血条一直朝向摄像头
}
}
4.接下来可以把画布拖到你所需要的怪物头上或者其他地方(这边就随便找了一个怪物模型)
记得把画布拖到怪物一栏里,这样子可以怪物带着血条一起跑动。(如果你需要的话)
(这边把画布名改为了GuaiWu(XueTiao))
5.创建一个空对象放在GuaiWu(XueTiao),在这个空对象本身也要开始挂载一个脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GuaiWuXueTao : MonoBehaviour
{
public Slider silder;//定义一个Slider组件的变量名字叫做silder
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void SetMaxHealth(int health)
{
silder.maxValue = health;
silder.value = health;
}
public void SwtCurrentHealth(int health)
{
silder.value = health;
}
}
(脚本上的挂载暂且不管,后面再挂载上去)
6.接下来创建2个原始图像,2个的颜色为不一样的颜色,2个图像是叠加再一起的,并把图像拖到合适的位置,如图所示。(这边就把第二个图像改为红色)
7.接下来回到第5步创建的空对象,(可以把上一步创建的两个原始图像拖进来)再把他本身拖到这里面来。
这样怪物的血条就设置好了。
下面则是怪物血条相对应的简单代码。(直接拿去用会报错,需要关于"ZiDan"标签的相对应的物体)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.AI;
public class DiRen : MonoBehaviour
{
private int hp = 100;
public Text xuelang;//怪物血量UI显示
public GuaiWuXueTao a;
// Start is called before the first frame update
void Start()
{
a.SetMaxHealth(hp);
a.SwtCurrentHealth(hp);
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter(Collider other)
{
if (other.tag=="ZiDan")
{
hp=hp-30;
a.SwtCurrentHealth(hp);
xuelang.text = "怪物血量:" + hp;
if (hp==0 || hp <= 0)
{
Destroy(gameObject);
}
}
}