|
|
|
 |
Reply From: |
SIsilicon |
Since you’re a beginner I assume you are working with gdscript.
Every script can be a class by itself, and can even have inner classes inside these scripts. Whenever you use the keyword extends
in a script (which is a necessity anyway), you are extending from either a built-in class, node or another script. To extend from another script, you would do something like this.
extends "script file path"
To easily get the (absolute)path of the script you want to extend from you can find it in the file explorer on the left, right click it and press Copy Path
. Then just paste it in quotations after the extends
keyword. Note that you can only extend from one thing in one script at a time.
So In your example, if the path to the mob script/class is res://mob.gd
, then in your fish script you’d type this at the top of the script.
extends "res://mob.gd"
You can learn more about the fabulous gdscript language here in the Godot docs.
First of all, thank you for answering my question.
Of course I could follow your answer, but in my case, I want to do everything with just one class (which is “mob.gd”). Here is the code:
extends Node2D
var _type = ""
var _size = Vector2(1,1)
func _ready():
pass
class fish extends Node2D:
func _init():
_randomize()
func _randomize():
randomize()
_size = rand_range(0.75,2.0)
I just wanted to replace, for example, “extends Node2D” with “extends mob”. That way besides fish, I could then add other mobs like cow. And all in the same script.
JulioYagami | 2018-11-20 08:40
Firstly you can’t extend from something that doesn’t exist.
And secondly, It would be best to have each class in separate scripts. If you want one class to inherit from the other, it will need to be a separate script. It would start to get cumbersome having different classes on the same script anyway (unless it’s some sort of helper class). So in your case:
# your mob class (res://mob.gd)
extends Node2D
var _type = "generic"
var _size = Vector2()
# your fish class (res://fish.gd)
extends "res://mob.gd"
func _init():
_type = "fish"
_randomize()
func _randomize():
randomize()
_size = Vector2() * rand_range(0.75, 2.0) # _size is a Vector2 remember?
# your cow class maybe (res://cow.gd)
extends "res://mob.gd"
# And some code that you would put in.
SIsilicon | 2018-11-20 13:50
Yes, I did exactly that way and it worked. I have to admit that this way is more organized than it would be if I put all the classes inside the same script. As for _size, I use it as a scale for both width and height, so you do not need to write something like “Vector2(2,2)”, for example. I want it to be proportional. Thanks again for the reply
JulioYagami | 2018-11-20 14:51