Unity怪物的血量教程(宝宝教程)

本文是关于怪物血量的教程,其中包含了血条设置血条代码一系列指导。

示意图

一:血条设置

首先要创建一个空画布:

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);
                }
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值