get_rect giving error. Game from scratch tutorial

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By mikethiem
:warning: Old Version Published before Godot 3 was released.

using tutorial from game from scratch Godot Engine Tutorial Part 2– 2D Scenes, Sprites, Coordinates and Viewports – GameFromScratch.com

the code that is given

var newPos = Vector2(self.get_parent().get_rect().size.width/2,self.get_parent().get_rect().size.height/2)

self.set_pos(newPos)

gives me the following error "Invalid call. Nonexistent function 'get_rect' in base 'Nil'." what do i use instead of get_rect

:bust_in_silhouette: Reply From: Warlaan

The problem isn’t the get_rect()-method, it’s the fact that you are calling a method on the result of “self.get_parent()” even though the object this code belongs to doesn’t have a parent.

When the error message talks about ‘Nil’ it is talking about “nothing”, so what it complains about is that the method 'get_rect' does not exist in ‘nothing’, which shouldn’t be surprising. So the real question is why ‘self.get_parent()’ returns nothing (a.k.a. ‘Nil’). Usually that can only be because there is no parent object.

:bust_in_silhouette: Reply From: vnen

Actually this is a bug that if you access a member that does not exist it shows the object as Nil but there’s actually an Object. I think this was fixed in master though.

So what is happening is likely that the parent is of a type that doesn’t have a get_rect() function.

Also, not that Rect2.size is a Vector2, so you need to use x and y not width and height. And you can divide a vector by a scalar, so you can do var newPos = size / 2.