【发布时间】:2019-12-06 01:25:12
【问题描述】:
我正在制作一个精灵表,它会根据我的角色的 HP 而变化。为了创建它,我有一个 Heart 文件,它从玩家那里获取 Health 对象并根据 Current Health 更改精灵。
当我试图将当前健康状况放入 PlayerStats 时。我有一个生命值和最大生命值的浮点数,但显然,要显示精灵,curHealth 必须是一个 INT。
但每当我尝试与 curHealth 值交互时,我都会收到错误消息“无法将类型 'float' 隐式转换为 'int'。
我的心档案
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Hearts : MonoBehaviour
{
public Sprite[] HeartSprites;
public Image HeartUI;
private PlayerStats player;
void Start (){
player = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerStats>();
}
void Update (){
HeartUI.sprite = HeartSprites[player.curHealth];
}
}
playerStats 文件
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerStats : MonoBehaviour
{
public static PlayerStats playerStats;
public int curHealth;
public GameObject player;
public float health;
public float maxHealth;
void Awake()
{
if(playerStats != null)
{
Destroy(playerStats);
}
else
{
playerStats = this;
}
DontDestroyOnLoad(this);
}
void Start()
{
health = maxHealth;
curHealth = maxHealth;
}
public void DealDamage(float damage)
{
health -= damage;
CheckDeath();
}
public void HealCharacter(float heal)
{
health += heal;
CheckOverheal();
}
private void CheckOverheal()
{
if(health > maxHealth)
{
health = maxHealth;
}
}
private void CheckDeath()
{
if(health <= 0)
{
Destroy(player);
}
}
}
虽然将它与“浮动健康”组件连接起来会更容易。因为它必须是一个 int 这似乎不起作用。 到目前为止,我不知道如何使 curHealth 与这两个文件交互。
【问题讨论】:
-
当我尝试玩游戏并被敌人击中时。我得到“对象引用未设置为对象的实例”,它指的是 HeartUI.sprite = HeartSprites[Mathf.RoundToInt(player.curHealth)];
标签: c# user-interface unity3d 2d