RequiringComponent on Child Objects

Hello, I have a script that contains a [RequireComponent] line to attach a BoxCollider to a parent object prefab. Any prefab in the project folder that contains the script will have the BoxCollider attached immediately. The script works perfectly for the parent object, but as far as I know, to attach any component to any child object requires code that doesn’t get executed until run time. I want to achieve similar functionality as [RequireComponent] for child objects without using other scripts. The parent object should be all that is needed to generate required components to the prefab object before the scene starts. What are some possible solutions to achieving that goal?

If you really want to have these box colliders while not playing then you can make and editor script for whatever script you have and it can add the box colliders for you. You could also do a similar thing with ExecuteInEditMode on the script but you’d have to have if statements on all the built in unity functions that would check Application.isPlaying. If that seems confusing to you let me know and I can probably make an example.

What about this script? You don’T have to attach it to any gameObject, it can just sit there in your script folder.

using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
using System.Collections;

[CustomEditor(typeof(YourScriptName))]
public class YourScriptNameEditorExtension : Editor {

	#if UNITY_EDITOR
	override public void  OnInspectorGUI () {
		YourScriptName yourScript = (YourScriptName)target;

		if(GUILayout.Button("Check children for box colliders")) {
			
			Transform[] children = yourScript.gameObject.GetcomponentsInChildren<Transform>();
                        foreach(Transform child in children) {
                             if(!child.gameObject.GetComponent<BoxCollider>()) {
                                  child.gameObject.AddComponent("BoxCollider") as BoxCollider;
                             }
                        }
		}

		DrawDefaultInspector();

                if (GUI.changed) {
			EditorUtility.SetDirty(target);
		}
	}
	#endif
}

This will make a button appear that when clicked, attaches a boxcollider to all children that don’t have one. Not perfect, but then again it’s just one button click :slight_smile: