Adding RectTransform after other components returns null

Compare the following two code snippets:

var slot = new GameObject("Slot");
var rectTransform = slot.AddComponent<RectTransform>();
slot.AddComponent<CanvasRenderer>();
slot.AddComponent<Image>();

and

var slot = new GameObject("Slot");
slot.AddComponent<CanvasRenderer>();
slot.AddComponent<Image>();
var rectTransform = slot.AddComponent<RectTransform>();

In the first case rectTransform contains a RectTransform, as expected. In the second case, however, rectTransform is null. Why?

1 Like

Those other components probably add a RectTransform for you, so the AddComponent fails.

2 Likes

This.

You can just use:

        var rectTransform = slot.GetComponent<RectTransform>();

instead.

Though you may want to make sure you also include a canvas and canvas scaler.

You can also include components in the constructor of a game object. So you could do this:

        var slot = new GameObject("Slot", typeof(Canvas), typeof(CanvasRenderer), typeof(CanvasScaler),typeof(Image));
        var rectTransform = slot.GetComponent<RectTransform>();
1 Like

I see. Seems like adding a Text or Image component automatically adds a RectTransform. Guess it might go for other UI components as well. Not sure I agree with the silent “fail” however. Personally think that Unity should inform us we’re doing something “wrong” (trying to add something that already exists) by throwing an exception, or at least give a console warning.

Oh well. Thanks for your help.

It does?

2850501--208310--Screen Shot 2016-11-13 at 12.37.31 AM.png

–Eric

2 Likes

You’re right. It was on top of the error list, which was being spammed with other errors due to the variable containing null. Since all the errors looked the same I never got around to the top of the list. My bad.

1 Like