我一直在收到错误CS0029

时间:2016-07-29 13:23:44

标签: c#

我收到以下错误:

  

CS0029无法将类型UnityEngine.Renderer[]隐式转换为   System.Collections.Generic.List<UnityEngine.Renderer>

代码是:

using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;

public class AssignShadersToChildren : MonoBehaviour
{
    private new GameObject renderer;

    public Shader shader; // This should hold the Shader you want to use

    void Start()
    {
        // We create a list that will hold all the renderers(objects) 
        // so we can then assign the shader
        List<Renderer> renderers = new List<Renderer>();
        renderers = GetComponentsInChildren<Renderer>();

        // For every Renderer in the list assign the materials shader to the shader
        foreach (Renderer r in renderers)
        {
            r.material.shader = shader;
        }
    }
}

3 个答案:

答案 0 :(得分:2)

错误是描述性的。您需要将结果转换为List:

renderers = GetComponentsInChildren<Renderer>().ToList();

或者将局部变量更改为数组:

Renderer[] renderers = GetComponentsInChildren<Renderer>();

答案 1 :(得分:1)

为什么不只列举项目?

void Start()
{
    foreach (Renderer r in GetComponentsInChildren<Renderer>())
        r.material.shader = shader;
}

唯一重要的是GetComponentsInChildren<Renderer>()应该返回IEnumerable<Renderer>无论它是什么(数组,列表......)

答案 2 :(得分:1)

您可以简单地省略类型,让编译器完成工作!如果您正在将方法调用的结果分配给`renderers&#39;那么就不需要创建新列表。变量

void Start()
{
    var renderers = GetComponentsInChildren<Renderer>();
    foreach (Renderer r in renderers)
    {
        r.material.shader = shader;
    }
}