类对象

类对象是类的一个实例。类对象也可以称为类实例、实例化对象或类对象。

  1. #Player.gd
  2. extends Node2D
  3. class_name Player
  4. # class variables and functions
  1. #Scene.gd
  2. extends Node2D
  3. var playerInstanceObject = Player.new()

类构造函数

类构造函数是一个特定的函数,每次创建类对象时都会调用它。
_init()您使用以下方法定义类构造函数:

  1. #Player.gd
  2. extends Node2D
  3. class_name Player
  4. var playerHealth: int
  5. # Class Constructor
  6. _init():
  7. playerHealth = 100
  1. #Scene.gd
  2. extends Node2D
  3. var playerInstanceObject = Player.new()
  4. print(playerInstanceObject.playerHealth) # 100

您还可以将参数传递给构造函数:

  1. #Player.gd
  2. extends Node2D
  3. class_name Player
  4. var playerHealth: int
  5. # Class Constructor
  6. _init(startingHealth:int = 100):
  7. playerHealth = startingHealth
  1. #Scene.gd
  2. extends Node2D
  3. var playerInstanceObject = Player.new(200)
  4. print(playerInstanceObject.playerHealth) # 200