2016-07-29 113 views
0

我收到以下錯誤:我不斷收到錯誤CS0029

CS0029 Cannot implicitly convert type UnityEngine.Renderer[] to 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; 
     } 
    } 
} 
+1

的方法'GetComponentsInChildren'可能是返回的'渲染[]''而不是名單' –

+1

什麼是與錯誤的問題?你有錯誤的類型。你也創建一個扔掉的列表。將'renderers'的類型更改爲正確的類型並刪除創建的列表。 –

回答

2

的錯誤是描述性的。您需要將結果轉換到一個列表:

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

或更改局部變量是一個數組:

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

爲什麼不只是列舉的項目?

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

這件事是GetComponentsInChildren<Renderer>()應該返回IEnumerable<Renderer>不管它是唯一的事情(數組列表...)

1

您可以簡單地忽略類型,讓編譯器做的工作!如果您隨後將方法調用的結果分配給`renderer'變量,則不需要創建新列表。

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