0

I've made a class script that looks like this:

extends Node

class_name Class

func method():
    pass

Then I've added a child node using that script in my main scene.

Next, in my main scene gdscript, I've added this bunch of code:

extends Node2D

var class = $Class # That's the child node using my previous script

func _ready():
    print(class.method())

And no matter what I put in the method() function, the main script will always print "Null" in my output. I've tried putting stuff to print and it behaves exactly like it should except that it still prints "Null" at the end of my output.

Does anyone know how to fix this?

2 Answers2

3

print(class.method()) is the equivalent of:

var result_of_method = class.method() # `class.method()` will return Null
print(result_of_method) # will print "Null"

As @JarWarren suggested you need to change your method to return something

mikatuo
  • 758
  • 6
  • 10
2

It doesn't look like class.method() returns anything.

Currently you're asking GDScript to print the result of class.method(). It will run the method, but if nothing ever gets returned out of it, it just defaults to Null.

func method():
    return  "Hello World"

If you were to call print on the above, it would print "Hello World" because that's what's being returned.

JarWarren
  • 1,343
  • 2
  • 13
  • 18
  • That's what you would think, but if I were to print "Hello World", the result would be the following: `Hello World Null` I'm not returning anything in my method() at all. The code for printing would be print("Hello World") (in my method()) PS: Hello World and Null are on two different lines – helpidontknowwhatimdoing Oct 10 '20 at 07:52
  • 1
    `print(class.method())` is basically saying to run the code inside of `method()` and afterward, print whatever `returns` out of it. The way you have it written, it will always run `method()` but it will always print `Null` afterward because that's what returns out of it. – JarWarren Oct 10 '20 at 17:03
  • I can guarantee you, printing my version of the code will not print `Null`. It will only print the string that `method` returns. – JarWarren Oct 10 '20 at 17:05
  • 1
    yup thanks, the other answer made me understand what you meant. I was basically using an unneeded print(). – helpidontknowwhatimdoing Oct 11 '20 at 13:13