Reputation: 29
I am getting the following error:
CS0029 Cannot implicitly convert type
UnityEngine.Renderer[]
toSystem.Collections.Generic.List<UnityEngine.Renderer>
The code is:
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;
}
}
}
Upvotes: 0
Views: 270
Reputation: 186688
Why not just enumerate the items?
void Start()
{
foreach (Renderer r in GetComponentsInChildren<Renderer>())
r.material.shader = shader;
}
the only thing that's matter is that GetComponentsInChildren<Renderer>()
should return IEnumerable<Renderer>
whatever it is (array, list...)
Upvotes: 1
Reputation: 176169
You can simply omit the type and let the compiler do the work! There is no need to create a new list if you are then assigning the result of a method call to the `renderers' variable.
void Start()
{
var renderers = GetComponentsInChildren<Renderer>();
foreach (Renderer r in renderers)
{
r.material.shader = shader;
}
}
Upvotes: 1
Reputation: 30022
The error is descriptive. You need to convert the results to a List:
renderers = GetComponentsInChildren<Renderer>().ToList();
Or change the local variable to be an array:
Renderer[] renderers = GetComponentsInChildren<Renderer>();
Upvotes: 2