c# - 更改精灵时无法将 FLOAT 类型转换为 INT
问题描述
我正在制作一个精灵表,它会根据我角色的 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 与这两个文件交互。
解决方案
最简单的方法是演员
int intValue = (int) floatValue;
然而,这只是切断了小数点。
阿里巴巴的答案很接近,但你仍然必须将结果转换为,int
因为他提到的所有方法仍然返回 a float
。例如
int intValue = (int)Mathf.Floor(floatValue);
更好的是直接使用int
返回的版本,如Mathf.RoundToInt
int intValue = Mathf.RoundToInt(floatValue);
1.5
-> 2
1.3
->1
或者可能Mathf.FloorToInt
取决于您的需求。
1.9
-> 1
1.2
->1
但是,您实际上永远不会更改curHealth
任何地方的值(在 .. 中除外,Start
您应该将其实现为只读属性,返回int
基于以下值的值health
:
public int CurrentHealth
{
get { return Mathf.RoundToInt(health); }
}
所以你只需要health
使用float
操作更新并自动CurrentHealth
返回相应的int
值。
然后使用
HeartUI.sprite = HeartSprites[player.CurrentHealth];
不过,我不会这样做,Update
而是基于health
实际更改时的事件->调用方法或将精灵设置移动到同一组件中。
推荐阅读
- java - Java 11 谓词 lambda 表达式泛型类型 ClassCastException
- php - 使用 Laravel Eloquent 的 with() 函数和内部连接
- reactjs - React - API 函数无权访问上下文 API
- python - 如何将当前行值加到熊猫中后续值的总和(相对于该行对应的日期)?
- mql5 - 我该如何解决这个问题:'Martingale' - 缺少函数调用,需要打开括号?
- c++ - Protobuf 中重复字段的问题。使用重复字段进行序列化/反序列化的更好方法是什么?
- python - 用 cssutils 替换 @font-face CSS 规则中的 URI 值
- python - 如何将csv写入“变量”而不是文件?
- regex - regex - Notepad++ 搜索和替换丢失的行
- php - PHP重命名关联数组中的键