Editor script check if AddComponent would succeed or fail for specified component type

Hi!

When an object has a Rigidbody, calling AddComponent<Rigidbody>() will return null and it will also log a warning message in Console: “The component Rigidbody can’t be added because GameObject already contains the same component.” Same thing happens when the object has an Image and we call AddComponent<Text>().

In my editor script, I don’t want the warning message to appear in the console if AddComponent fails, so I need to find a way to check if AddComponent will fail for the given component type. In which case, I’ll simply not call AddComponent at all. I couldn’t find an Editor API for this query but it’s possible that I’ve missed some internal APIs.

Any help is appreciated :slight_smile:

Why don’t you use GetComponent<> to see if it’s attached or not?

This isn’t quite enough. For instance if you have a Collider2D on something and attempt to add a Collider (3D) or a Rigidbody (3D) it will also tilt and complain.

To OP, I’m not sure there is a public way… can you try/catch the attempted AddComponent(), or does the log message still spew?

@Dextozz GetComponent won’t work for me because it is possible to add multiple BoxColliders to an object, so AddComponent won’t fail for BoxCollider even if GetComponent returns true. The solution I’m seeking must work for all component types correctly.

@Kurt-Dekker The message is always logged, unfortunately. The message is a log rather than an error or exception and I’ve tried assigning a dummy logger to Debug.unityLogger so that I would maybe skip the logs but even that didn’t work. I couldn’t find a public/internal API for my problem yet.

1 Like

I think I’ve found a possible workaround. Unlike gameObject.AddComponent, ObjectFactory.AddComponent function actually throws an exception when the component can’t be added! If I catch the exception and not log it, then it solves my problem. Downsides of this approach are:

  • I was actually using Undo.AddComponent, so I’ll have to destroy the component returned by ObjectFactory (if it doesn’t fail) and call Undo.AddComponent afterwards
  • ObjectFactory.AddComponent won’t work for a small list of deprecated components: Repository search results · GitHub
1 Like