Home > Blockchain >  Unity editor script check if AddComponent would succeed or fail for specified component type
Unity editor script check if AddComponent would succeed or fail for specified component type

Time:09-23

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.

CodePudding user response:

I've found a 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:

Until a better answer is posted, I'll accept this answer.

CodePudding user response:

A handy function from Component class is TryGetComponent, it could be used as following:

using UnityEngine;

public class Q69283330 : MonoBehaviour
{
    private Rigidbody _rigidbody;

    private void Awake()
    {
        // if rigidbody component exists, add the result to _rigidbody
        if(TryGetComponent<Rigidbody>(out _rigidbody))
        {
            // do something with it
        }
        else
        {
            _rigidbody = this.gameObject.AddComponent<Rigidbody>();
        }
    }
}
  • Related