I have a small Centercontainer. I instance a scene to it that has a TextureRect.


MyScene = Scene.instance()
add.child(MyScene)

But the image is not scaled to the Centercontainer. How do I scale the image to fit the Centercontainer? Preferably with an intact aspect ratio.

I could probably just write.

Myscene.rect_scale = Vector2(10,10)

Or something like that. But in case I change my Centercontainer size (which I will) the image scale will be all wrong again.

I'd like to get the scale of the CenterContainer and then scale the image based on that. I tried various configs of

var new_width = $Centercontainer.get_viewport().rect_size.x
var new_height = $Centercontainer.get_viewport().rect_size.y

But these kept giving the null instance error so I kinda gave up.

Took me a few hours but I solved it. Leaving a small explanation for anyone else with similar problems. Firstly, on the instanced scene, tick the "Expand" box on. Stretch mode is default "Scale on Expand" .

Secondly below is the relevant parts of the script. My instanced scene is named Texture.scn, it's a Node2D with a TextureRect. The script below should be attached to the Centercontainer you wish to instance a scene to.

Here's the code

onready var Specs = get_node("/root/Node2D/Centercontainer")
onready var viewportWidth = Specs .rect_size.x
onready var viewportHeight = Specs .rect_size.y

func _ready():
    	var Tex= Texture.instance()
    	Tex.get_child(0).rect_size.x = viewportWidth     
    	Tex.get_child(0).rect_size.y = viewportHeight
    	add_child(Tex)

And the same with explanations

! ! onready var Specs = get_node("/root/Node2D/Centercontainer") ! # Get the node we will be instancing to !
! onready var viewportWidth = Specs .rect_size.x # get that node's width ! onready var viewportHeight = Specs .rect_size.y #get that node's height !
! func _ready(): ! var Tex= Texture.instance() # make an instance of the scene ! Tex.get_child(0).rect_size.x = viewportWidth
! # get instanced scene's first child node, which is TextureRect, then make it's width viewPortWidth
! ! Tex.get_child(0).rect_size.y = viewportHeight ! # Same for height !
! add_child(Tex) # Finally, add the instance

Hopefully it helps someone else too.

2 years later