'Unity3d - Is there any whay to add a script to all colliders automatically

I'm making a library where it would be beneficial to add a script to all objects with a collider automatically. Is there any way to do it?



Solution 1:[1]

I think one can do something like this:

foreach(var go in GameObject.FindObjectsOfType(typeof(GameObject)))
{
    if (!go.TryGetComponent<ScriptName>() && go.TryGetComponent<Collider>())
    {
        go.AddComponent<ScriptName>();
    }
}

You can make it look better with LINQ of course, but I left it as is for the sake of clarity.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Oleksandr Novik