disabling grandchild C#

I want to disable the entire grand child and I dont really know how to find it by scripting, example:

using UnityEngine;
using System.Collections;

public class jointbreakwhatever : MonoBehaviour 
{
	
	void OnJointBreak(float breakForce)
	{
		findTheGrandChild.enabled = false;
	}
}

2 Answers

2

@Kiloblargh answer is totally fine. But at a later point in your game, you might add other things, other objects (children/grandchildren) and doing a GetChild(index) (or even writing an extension GetChild(name)) isn’t going to be efficient and could prove buggy. Changing the objects’ order (if you’re using the index version of GetChild), or name (if you wrote a GetChild(name)) won’t get you the results you want.

Instead, why not just reference the grandchild you want from your gameObject?

using UnityEngine;
using System.Collections;
 
public class jointbreakwhatever : MonoBehaviour 
{
    public GameObject grandChild; // assign via inspector
    void OnJointBreak(float breakForce)
    {
       grandChild.SetActive(false);
    }
}

Since we’re at it, here’s a GetChild(name) Transform extension:

public static Transform GetChild(this Transform inside, string wanted, bool recursive = false)
{
	foreach (Transform child in inside) {
		if (child.name == wanted)
			return child;
		if (recursive)
		{
			var within = GetChild(child, wanted, true);
			if (within) return within;
		}
	}
	return null;
}	

Usage:

GameObject grandChild = transform.GetChild("grandChildName", true).gameObject;

Again, I wouldn’t recommend this - I don’t like string literals and hard-coding stuff. This would easily fail if you change the name of the grandchild. I would stick with assigning it via the inspector.

thanks for the answers but I wont have my computer till next month, then I will try and rate the answers.

transform.GetChild (0).GetChild (0).enabled = false.

( Will only work if there is exactly one child and exactly one grandchild.)

will not work at all. See comment below.

enabled will enable/disable a certain component. The GetChild returns a Transform component which can't be enabled/disabled. So instead, use: transform.GetChild(0).GetChild(0).gameObject.SetActive(false);