I have a Monobehavior with or without a Rigidbody2D component. I want to get it or create it if needed.
The AddComponent, returns null on my game. Often, not every time, the log appeared.
Using:
void Start()
{
Rigidbody2D rb = gameObject.GetComponent<Rigidbody2D>() ??
gameObject.AddComponent<Rigidbody2D>();
if (rb == null)
{
Debug.LogError("No way to be here!");
}
}
I can remove the ?? and do this in multiple lines, it doesn't change the error.
Do you have a solution to get the Rigidbody2D component?
I found the solution. The coalescing operator doesn't works with MonoBehavior and I need to get the Component a third time to make it work. It seems that the AddComponent does not work with Rigidbody2D.
This code works:
Rigidbody2D rb = gameObject.GetComponent<Rigidbody2D>();
if (rb == null)
{
rb = gameObject.AddComponent<Rigidbody2D>();
}
if (rb == null)
{
rb = gameObject.GetComponent<Rigidbody2D>();
}