类对象
类对象是类的一个实例。类对象也可以称为类实例、实例化对象或类对象。
#Player.gd
extends Node2D
class_name Player
# class variables and functions
#Scene.gd
extends Node2D
var playerInstanceObject = Player.new()
类构造函数
类构造函数是一个特定的函数,每次创建类对象时都会调用它。
_init()您使用以下方法定义类构造函数:
#Player.gd
extends Node2D
class_name Player
var playerHealth: int
# Class Constructor
_init():
playerHealth = 100
#Scene.gd
extends Node2D
var playerInstanceObject = Player.new()
print(playerInstanceObject.playerHealth) # 100
您还可以将参数传递给构造函数:
#Player.gd
extends Node2D
class_name Player
var playerHealth: int
# Class Constructor
_init(startingHealth:int = 100):
playerHealth = startingHealth
#Scene.gd
extends Node2D
var playerInstanceObject = Player.new(200)
print(playerInstanceObject.playerHealth) # 200