XDracam / unity-corelibrary

Collection of classes and extension methods that make life with Unity3D more comfortable
MIT License
15 stars 3 forks source link

GetOrAddComponent<T> #7

Closed XDracam closed 5 years ago

XDracam commented 5 years ago

Might be useful to add a component if GetComponent fails.

T GetOrAddComponent<T>(this GameObject go, Search where = Search.InObjectOnly) where T : Component 
{
    var found = go.As<T>(where);
    if (found == null) return go.AddComponent<T>();
}
XDracam commented 5 years ago

Considering the style and naming of other existing methods in the CoreLibrary, this seems like a bad idea. It is basically an .As<T> call with a different name and a potential side effect.

So, when would this be used? When querying a component while assigning it. And to make sure that that component always exists. Implementing the above version could cause weird bugs due to the side effect. Bugs I do not even want to imagine, where people keep removing and adding components in a loop *shudder*.

As a result, I have implemented AssignComponentOrAdd<T>(this GameObject go, out T variable, Search where = Search.InObjectOnly) where T : Component as well as an analoguous AssignIfAbsentOrAdd<T> instead. Assignment of a field is the only case for which I would want have this behaviour in my codebase.