Proper way to auto-scale a sub-viewport

Godot Version

4.2

Question

Hi, I’m working on an editor plugin and my intent is to display a 3d sub-viewport to work in. I created a SubViewportContainer under the Control scene root and a Subviewport under that.

The viewport container is set to scale to the full rect to match the full rect of the root node. My problem is that the sub-viewport does not seem to scale to fit the container it’s in.

The sub viewport node only has fixed dimensions, and the shrink toggle in the container doesn’t have any effect on it.
image

I’ve written a small script I’ve attached to the container to get the child, subscribe to the Resized event, and set the subviewport Size property to match the (Vector2I)GetViewportRect().Size;

 public partial class ViewportAutoScalar : SubViewportContainer
 {
     private SubViewport _subViewport;
 
     public override void _Ready()
     {
         _subViewport = GetNode<SubViewport>("SubViewport");
         this.Resized += OnContainerResized;
         OnContainerResized();
     }
 
     private void OnContainerResized()
     {
         if (_subViewport != null)
             _subViewport.Size = (Vector2I)GetViewportRect().Size;
     }
 }

While this works, it feels like there must be a simpler non code way to structure the UI nodes to allow a sub-viewport to auto-fit to its container? What am I missing?

Any help would be appreciated thank you.

P.S. I tried to make the variable for the subviewport [Export] so I could drag and drop the sub-viewport reference in the Inspector without having to use strings (for less fragility) but for some reason the field did not appear in the inspector. Is SubViewport not a type that you can expose?

Enabling SubViewportContainer.stretch should do just that without any need for code.

Did you build the project after that? In C# exported properties won’t show up until you build the project. More info here C# exported properties — Godot Engine (stable) documentation in English

1 Like

Yes thank you I did rebuild (Rider does a build before running the editor). I’ll try it again but it didn’t seem to appear. I’ll check the stretch thank you.

Update: It appears Stretch does work, though I am confident I tried it before and it did not function the same way. I must have had something else on at the time conflicting with it. Thank you for the tip