- Home /
Children of Instantiated Prefabs are not seperate
I have a child called "hairMesh" in two Instantiated prefabs and I refer to these children using Find function.
I'm trying to change the material on both the "hairMesh" children but it only changes the first one. I also noticed that when trying to add the MeshRenderer component on the two children, it only is added to the first one.
I also ran a condition testing if the children are the same and it returns true. No idea why they're the same as the prefabs are spawned separately.
Here's my code:
var headObj = transform.Find("gut").Find("stomach").Find("chest").Find("neck").Find("headtip").Find("head").Find("headItem");
var headPrefab = IVendor.items[IVendor.FindItemID(head)];
if(headPrefab) {
var headSpawn = Instantiate(headPrefab, headObj.transform.position, headObj.transform.rotation);
if(headSpawn) {
if(headSpawn.Find("hairMesh")) {
headSpawn.Find("hairMesh").AddComponent(MeshRenderer);
}
headSpawn.transform.parent = headObj;
headSpawn.name = head;
setHeadItem = head;
if(selfPlayer) {
var headItem = skullObj.Find("HeadItem");
var headSpawn2 = Instantiate(headPrefab, headItem.transform.position, headItem.transform.rotation);
headSpawn2.transform.parent = headItem.transform;
headSpawn2.layer = LayerMask.NameToLayer("UI");
headSpawn2.name = head+"_skull";
headSpawn2.transform.localScale = headItem.transform.localScale;
SetLayerRecursively(headSpawn2, LayerMask.NameToLayer("UI"));
if(headSpawn2.Find("hairMesh") == headSpawn.Find("hairMesh")) {
Debug.Log("Children match???");
}
if(headSpawn2.Find("hairMesh")) {
headSpawn2.Find("hairMesh").AddComponent(MeshRenderer);
}
}
}
Answer by NoseKills · Apr 10, 2015 at 11:24 PM
I'm on mobile and can't check this and also my javascrip is a bit shaky compared to c#, but I believe what is happening is:
You don't assign strict types for variables in your code so you can't be sure exactly which methods you are calling.
There is non-static transform.Find() that searches for child objects and there is static GameObject.Find() that searches the whole scene.
You just Instantiate the "headspawn" objects withou caring about their type and apparently end up calling the static GameObject.Find() through the created instances (in c# that's not even possible) instead of the transform.Find(), and so you end up finding the first object called "hairMesh" in the scene both times.
Try changing the xxx.Find("hairMesh")
calls to xxx.transform.Find("hairMesh")
And regardless of whether that worked or not, switch to C# ;)
Cheers Nose$$anonymous$$ills, this solved the issue. I'll keep this advice in $$anonymous$$d for the future, apart from that last bit ;)