为什么我总是收到隐式转换错误
本文关键字:转换 错误 为什么 | 更新日期: 2023-09-27 17:56:43
我只是在Unity游戏引擎中使用c#进行编码,并且一直遇到此错误:
资产/背景/天管理器.cs(30,29):错误 CS0266:无法 隐式转换类型
float' to
int'。显式转换 存在(你缺少演员表吗?
这是我的代码:
using UnityEngine;
using System;
using System.Collections;
public class SkyManager : MonoBehaviour {
public int hours = DateTime.Now.TimeOfDay.Hours;
public int minutes = DateTime.Now.TimeOfDay.Minutes;
public int seconds = DateTime.Now.TimeOfDay.Seconds;
public Light lighting;
//public CameraClearFlags night;
public Camera night;
// Use this for initialization
void Start () {
print (DateTime.Now.TimeOfDay.TotalSeconds);
}
// Update is called once per frame
void Update () {
//what should the rotation of light be?
//15° every hour
if(hours != 1){
int sunRotation = 7.5f * hours;
print (sunRotation);
}
//end
var rot = transform.rotation;
lighting.transform.rotation = rot * Quaternion.Euler(180, 0, 0);
}
}
在行
int sunRotation = 7.5f * hours;
上,您正在使用浮点值7.5f
。您正在尝试将其放置在int
变量中。
您可以使用以下命令将数据转换为int
。
int sunRotation = (int)(7.5f * hours);
这里的代码是一个返回浮点数: int sunRotation = 7.5f * hours;
但是您正在尝试将其分配为整数。 您可以按照 Juken 的建议将该值转换为整数,但是您将丢失您可能希望它维护的任何十进制值。
您应该考虑使用 Math.Ceil 或 Math.Floor 根据您的意图向上或向下舍入您的值,或者将值分配给浮点数以保持准确性。