godotengine / godotengine/godot-docs

Document `get_script()` usage for exact comparison of classes (including nested)

Open
#3,791 3 comments 1 reaction 2 assignees Claimed by @vnen View on GitHub
area:class reference enhancement
Dominant language
reStructuredText
Stars
5.7k
Forks
3.8k
Avg merge
1d 20h
Merged PRs (30d)
25

Description

**Godot version:**
3.2.2

**OS/device including version:**
Fedora 32

**Issue description:**
I am unable to compare exact classes that are not script resources themselves

**Steps to reproduce:**
```gdscript
# First set up a class hierarchy
class Animal extends Spatial:
pass

class Primate extends Animal:
pass

class Human extends Primate:
pass

# Store a reference to the last animal we collided with
var last_animal : Animal = null

# We only want to update the "last_animal" reference if it's a new type
func on_body_entered(new_animal : Node):
if new_animal is Animal == false:
return

if !last_animal:
last_animal = new_animal
return

# Will always be true, since they are both "Spatial"
if last_animal.is_class(new_animal.get_class()):
return

last_animal = new_animal
```

**Proposed solution:**
A way to get the exact class of an object

```gdscript
if last_animal.get_constructor() == new_animal.get_constructor():
pass
```

This should ideally also work with the "is" logic, like so:

```gdscript
human is primate.get_constructor() # Should be true
human.get_constructor() == primate.get_constructor() # Should be false
```

...but I understand if we can only get class names as strings, i.e. `get_class()`, then `get_constructor()` could just return the exact class name.

**Workaround:**
A hacky way to solve this is to keep a "constructor" reference in the script itself:

```gdscript
class Animal:
var constructor : GDScript = null

class Primate extends Animal:
pass

var primate : Primate = Primate.new()
primate.constructor = Primate
```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.