- Home /
Get MeshRenderer Component of Gameobjects in an Array
I'm trying to write a script in which the Mesh Renderer component is accessed from all of the game objects in an array. Here's what I've written so far:
#pragma strict
var limbs : GameObject[];
function Start(){
limbs = gameObject.GetComponents.<MeshRenderer>();
}
I feel like I'm on the right track but I'm getting the error:
Assets/Scripts/LevelComplete.js(5,56): BCE0022: Cannot convert 'UnityEngine.MeshRenderer[]' to 'UnityEngine.GameObject[]'.
If anybody could point me in the right direction that would be great. Thanks for your help!
Answer by Cherno · May 03, 2015 at 04:25 PM
Ok, here is what you are doing wrong:
You declare that limbs is an array with elements that are of type GameObject. However, then you try to populate this array by calling
GetComponents<MeshRenderer>()
, which returns an array with elements of type MeshRenderer. I think you see where the error is here. If you want to access the MeshRenderers of each GameObject in an array, populate the array with elements of the appropriate type, i.e. GameObjects. You can then use a simple foreach loop to cycle through the GameObjects in the array and use
go.GetComponent<MeshRenderer>()
on each element to access their MRs. However, if you want an array all the MeshRenderer components that are in the scene, you need to change the limbs array's element type to MeshRenderer, and then you can populate it with
var limbs : MeshRenderer[];
limbs = FindObjectsOfType(typeof(MeshRenderer)) as MeshRenderer[];
You can then cycle to that array to access the MeshRenderers directly, and access the gameObjects they are attached to with
foreach(MeshRenderer mr in limbs) {
GameObject go = mr.GameObject;
}