I have a prefab object “an Aircraft” and this aircraft got 3 meshes in it.
I Instantiate on the scene in a loop 3 of this aircraft.
and in the same loop, i try to set the opacity of the mesh “Canopy” to 0.5.
then, when i run the project, only the first object get the correct opacity. the 2 others are ignored.
GameObject.Find will find the same Canopy in every iteration of the loop. You’re trying object.Find, but that doesn’t do what you think it does. It’s a static function; you’re not actually searching within the hierarchy of object. To help clear this up for yourself, always code it as GameObject.Find, like they have it in the docs.
GameObject.Find is slow, and using it like that isn’t good practice. Here’s one way alternative way to do this, which should become much faster than GameObject.Find, as you get more Game Objects in your scene. I’ve changed the names of your variables based on what I feel are good scripting habits.
You’ll need import System.Collections.Generic; at the top of the script, so you can use List.
for (var i = 0; i < 3; i++) {
var aircraft = Instantiate(prefabAircraft, Vector3(i * 20, 0, 0), Quaternion.identity);
// Create a generic List made of all renderers that have the new aircraft as a parent...
List.<Renderer>(aircraft.GetComponentsInChildren.<Renderer>()).
// ...so we can use List.Find
Find(function(renderer) renderer.name == "Canopy").
material.color.a = 0.5;
}
With GetComponentsInChildren function i get access to Renderer, Transform etc… That is very nice but, how can i access to the childrens as GameObject ?
I need to use one more time to access to “Canopy” object inside my Aircraft prefab in order to tween it.
I use itween, and itween only accept GameObjects.
You can loop through the children using the code snippet at the top of the Transform reference page. I don’t know if that’s going to be enough information for you, but give some code a shot, and I’ll help you if you still need it after you get started.