Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

オブジェクト指向の原則をGodotに適用する

エンジンは、再利用可能なオブジェクトを作成するための2つの主な方法を提供します: スクリプトとシーンです。これらのどちらも、内部でクラスを技術的に定義していません。

それでも、Godot を使用する多くのベスト プラクティスでは、ゲームを構成するスクリプトやシーンにオブジェクト指向プログラミングの原則を適用します。そのため、それらをクラスとしてどのように考えることができるかを理解することが有用です。

このガイドでは、スクリプトとシーンがエンジンのコアでどのように機能するかを説明します。Godotが内部でどのように機能するかを理解するのに役立ちます。

エンジン内のスクリプトの働き

エンジンは :ref:`Node <class_Node>`のような組み込みクラスを提供します。スクリプトを使用して、それらを拡張して派生型を作成できます。

これらのスクリプトは技術的にはクラスではありません。しかし代わりに、エンジンの組み込みクラスで実行される初期化シーケンスをエンジンに伝えるリソースです。

Godotの内部クラスには、クラスのデータを ClassDB に登録するメソッドがあります。このデータベースは、クラス情報へのランタイムアクセスを提供します。ClassDB には、次のようなクラスに関する情報が含まれています。

  • プロパティ。

  • メソッド。

  • 定数。

  • シグナル。

この ClassDB は、プロパティへのアクセスやメソッドの呼び出しなどの操作を実行するときにオブジェクトがチェックするものです。ClassDB では、データベースのレコードとオブジェクトの基底型のレコードをチェックして、オブジェクトが操作をサポートしているかどうかを確認します。

オブジェクトに Script <class_Script>`をアタッチすると、``ClassDB` から利用できるメソッド、プロパティ、およびシグナルが拡張されます。

注釈

Even scripts that don't use the extends keyword implicitly inherit from the engine's base RefCounted class. As a result, you can instantiate scripts without the extends keyword from code. Since they extend RefCounted though, you cannot attach them to a Node.

シーン

シーンの動作はクラスと似ているため、シーンをクラスと考えるのも理にかなっています。シーンは、再利用可能で、インスタンス化可能で、継承可能なノードのグループです。シーンを作ることは、ノードを作り``add_child()``を使ってノードを子として追加するようなスクリプトを持つことに似ています。

We often pair a scene with a scripted root node that makes use of the scene's nodes. As such, the script extends the scene by adding behavior through imperative code.

シーンのコンテンツは、以下を定義するのに役立ちます:

  • What nodes are available to the script.

  • How they are organized.

  • How they are initialized.

  • What signal connections they have with each other.

Why is any of this important to scene organization? Because instances of scenes are objects. As a result, many object-oriented principles that apply to written code also apply to scenes: single responsibility, encapsulation, and others.

The scene is always an extension of the script attached to its root node, so you can interpret it as part of a class.

Most of the techniques explained in this best practices series build on this point.