2
\$\begingroup\$

I built a simple scene that I instanciate at will. Simply a KinematicBody2D as root, containing a Sprite and a CollisionShape2D. There is a script linked to the root node that basically expose a few properties to describe an orbit and make it move in orbit around its parent. The point being to make a very basic solar system simulation or anything that requires a node to move around another in a circular fashion.

Instanciated scene tree

The movement work fine and I’ve been playing around my scene tree, instancing a bunch and watching them move around as moons of planets, etc. But the texture is all the same. If I make children editable, I can go change the texture of the sprite, but I’d like to expose that property from the root node so I can access it directly from the editor.

I tried adding an exposed property with a setter and a getter to assign and retrieve the texture, but it seems to crash Godot completely with this code:

export(Texture) onready var texture setget texture_set, texture_get

func texture_set(newtexture):
    $"Sprite".texture = newtexture

func texture_get():
    return $"Sprite".texture

Is there a solution for that? Or simply another way?

\$\endgroup\$
  • \$\begingroup\$ I've been using that, what you need to make it work is to add a conditional (if) check to the methods to make sure that the $"Sprite" node exists when you try to retrieve or set that information. If it doesn't, you have a couple of options: completely ignore the get/set call, or return a default value for get and cache the value for set, then set that value to the actual parent property in _ready. The reason $Sprite wouldn't exist is if the get/set method gets called before _ready (or in case you forgot to add the Sprite child node) \$\endgroup\$ – Bruno Ely Jun 13 at 20:54
1
\$\begingroup\$

I would export the texture variable from the root node and simply set the child texture in _ready(), rather than mess around with getters and setters.

export(Texture) var my_texture 

func _ready():
    get_node("Sprite").texture = my_texture
\$\endgroup\$
  • 1
    \$\begingroup\$ Always the simple solution that works ;) \$\endgroup\$ – BadgerBadger Apr 25 '18 at 22:15
  • \$\begingroup\$ Reviving this because I've been giving this issue some thought recently. What happens when some external actor decides to set my_texture on the parent? Is there a way to make it read-only? \$\endgroup\$ – Bruno Ely Jun 13 at 20:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.