【问题标题】:C# Unity cannot implicity convert type float to int [closed]C# Unity 无法将浮点类型隐式转换为 int [关闭]
【发布时间】:2021-05-15 12:05:42
【问题描述】:

我正在尝试为数组中引用的游戏对象的颜色设置动画。像这样

public GameObject[] laneMat;
   
void Update()
{
    StartCoroutine(CountDownMat(laneMat, .3f));   
}
    IEnumerator CountDownMat(GameObject[] laneMat, float delay)
    {
        time += Time.deltaTime;
             for(float i = 0; i < laneMat.Length; i++)
            {
        
                if (duration > time)
                {
                    laneMat[i].GetComponent<Renderer>().material.color = Color.Lerp(startColor, endColor, time / duration);
                    yield return new WaitForSeconds(delay);
                }
                
            
            }
    }

我正在寻找的是,让游戏对象按顺序改变颜色,每个对象之间有 0.3 秒的延迟。

但是我不断收到错误:由于这条线laneMat[i].GetComponent&lt;Renderer&gt;().material.color = Color.Lerp(startColor, endColor, time / duration); 我很难理解错误,因为数组是游戏对象的类型,所以我不确定这里的浮点到 int 的转换是什么..

我尝试了另一种方法,即用 foreach 更改 for 循环,但没有按预期工作。

任何帮助将不胜感激

【问题讨论】:

  • Float i 是你需要看的
  • 嘿,您正在使用浮点数作为索引。在你的循环中你有 float i = 0; ...改为使用 int i = 0,这将解决您的问题

标签: c# unity3d colors gameobject lerp


【解决方案1】:

您将循环中的索引 (i) 声明为浮点数。 然后将它作为浮点数传递到数组的索引器中。这是导致错误的原因。

只需使用 int 即可,不再需要类型转换。

for(int i = 0; i < laneMat.Length; i++)
{

    if (duration > time)
    {
        laneMat[i].GetComponent<Renderer>().material.color = Color.Lerp(startColor, endColor, time / duration);
        yield return new WaitForSeconds(delay);
    }            
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多