Get Class of Node to allow Class-specific Method

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Arecher

I was wondering if there is a way to confirm the class of a Node. I’m trying to make one script that can be used on any type of node, checks the Node’s class, and sets specific values based on that class.

Basically a more elaborate version of this:

Extends Node

if self.is_class("Control"):
		self.get_stylebox("panel").set_bg_color(Color(#ffffff))
elif self.is_class("Sprite"):
		self.modulate = Color(#ffffff)

Sadly doing this gives an error (error(): The Method "get_stylebox()" isn't declared in the current class), because it extends Node rather than Control. It gives this error even though there is no way the get_stylebox() method will ever call on a non-Control node.

I was hoping there was a way to confirm that self is a Control node, so get_stylebox() is a valid Method, or some other way to work around this.

By the way, making the script extend Control instead, has the issue that the script cannot be used on Sprites or any other non-Control node, so that won’t do the trick.

:bust_in_silhouette: Reply From: Wakatta

IMHO what you want to do feels very weird however Godot does not seem to have any restrictions on some_variable.calling_some_function() so just use a variable

extends Node

func _ready():
    var node = self
    if self.is_class("Control"):
        node.get_stylebox("panel").set_bg_color(Color("#ffffff"))
    elif self.is_class("Sprite"):
        node.modulate = Color("#ffffff")

Thank you! Making it a variable does indeed work.
Feels like I’m cheating the system, but results is all that matters :smiley:

Arecher | 2020-11-01 00:28