Home > Blockchain >  Adding mesh collider via script to game object and all its child game objects?
Adding mesh collider via script to game object and all its child game objects?

Time:11-01

looking for some help with adding mesh colliders in Unity via script. For example, I want to select GameObject and have script add mesh colliders to each other child gameobject, with exception of said gameobject of having Mesh Filter.

Any help would be appreciated. I'd like to be able to use the script in Editor mode, so I don't have to manually select gameobjects and set colliders to them.

I'm not really too sure how to go about that at the moment.

public GameObject object4col;

public void AddMeshColliders(){

    if (object4col.GetComponent<MeshFilter>() == null)
    {
        object4col.AddComponent<MeshCollider>();
    }
}

Thanks!

CodePudding user response:

Can be done this way: Import Linq

using System.Linq;

Select all the child objects of parentObj (say) that do not have a mesh collider

public Transform[] object4cols = parentObj.GetComponentsInChildren<Transform>().Where(x => x.GetComponent<MeshCollider>() == null).ToArray();

Iterate over the child objects and add a mesh collider to them

foreach(Transform object4col in object4cols) {
    object4col.AddComponent<MeshCollider>();
}

CodePudding user response:

You can iterate through recursively of child objects and add the component. You can add the method to the context menu, so when you right click on the script's header or click on the three dots on the header's right side, the option will be there.

[SerializeField] private Transform _target;

[ContextMenu("Add MeshColliders")]
private void AddMeshColliders()
{
    if (_target == null) _target = transform;
    AddRecursively(_target);
}

private void AddRecursively(Transform parent)
{
    for (int i = 0; i < parent.childCount; i  )
    {
        Transform child = parent.GetChild(i);
        if (child.GetComponent<MeshFilter>() != null) child.gameObject.AddComponent<MeshCollider>();

        AddRecursively(child);
    }
}

Instead of ContextMenu, you can write an Editor script, add a button for it and move the whole logic there.

  • Related