- Home /
Accessing Specific Children to Change Color
What i am trying to accomplish is every-time my player touches a cube it changes the color of the cube that is touched.
In this case the color would be red.
The Problem i am having is when trying to use "gameObject.Find()"
when i use this it finds ONE game object and turns the color to red.
Here is the code: function OnCollisionEnter(theCollision : Collision) {
Debug.Log("Hit");
if(theCollision.gameObject.name == "Cube_Neut")
{
var theCube = gameObject.Find("Cube");
theCube.transform.renderer.material.color = Color.red;
Debug.Log("Changed Color");
}
}
The thing is that my "gameObject" was imported and has two children because there is a rim (if you want to call it that) around the corners of the cube and the regular cube itself.
So in the Hierarchy it looks like this:
Map_1 (Map_1 representing the level as a whole)
-Cube_Neut (Child of "Map_1")
-Cube (This is the part i want to turn Red. Child of "Cube_Neut")
-Cube_006 (This is the black rim of the cube that i want to keep<br>the same. Child of "Cube_Neut")
I am trying to find a better way of doing this so that is why i am here.
Any Help is Appreciated
Answer by aldonaletto · Dec 06, 2011 at 01:10 AM
You already has got a reference to the hit object in theCollision. You can find only the child transform you want using theCollision.transform.Find("ObjectName"):
function OnCollisionEnter(theCollision : Collision) { if (theCollision.gameObject.name == "Cube_Neut"){ var theCube = theCollision.transform.Find("Cube"); // theCube is a Transform theCube.renderer.material.color = Color.red; Debug.Log("Changed Color"); } }Only the hit object's child named "Cube" will change its color - the "Cube_006" will not be affected, nor other "Cube" childed to other "Cube_Neut" objects.
lol thanks a lot...i kind of had an ohhhhhh duhhhh moment... :D
Your answer
Follow this Question
Related Questions
Game works great, then i build and run, it no longer works. 1 Answer
Object reference not set to an instance of an object 1 Answer
How do I change the raycasthit material back? 1 Answer
How do I retrieve deep levels of nested child transforms with a generic snippet of code 2 Answers
Renderer.material.color not changing color of prefab 3 Answers