首页 > 解决方案 > 更改精灵时无法将 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 与这两个文件交互。

标签: c#user-interfaceunity3d2d

解决方案


最简单的方法是演员

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实际更改时的事件->调用方法或将精灵设置移动到同一组件中。


推荐阅读