ステップ3 - プレハブをインスタンス化する

このステップでは、Luaスクリプトからプレハブをインスタンス化する方法を学びます。

プレハブをノードツリーにインスタンス化するには:

  1. tryAcquireResource を持つプレハブを見つける。

  2. instantiate でプレハブからノードを作成します。

  3. addChild を使用してノードをノードツリーに追加します。

-- Find the node with the alias "Grid".
local grid = contextNode:lookupNode("#Grid")
assert(grid)

-- Find the "Piece" prefab.
local piecePrefab = contextNode:tryAcquireResource("kzb://fifteen_puzzle/Prefabs/Piece")

-- Use the piecePrefab to create a node named "New piece".
local node = piecePrefab:instantiate("New piece")

-- Add the node to the grid.
grid:addChild(node)

パズルグリッドにピースを追加する

ピース プレハブをインスタンス化して、パズルグリッドを1から15までの順番で15個のピースで埋めます。ゲームをプレイできるように、最後のグリッドスロットは空のままにしておきます。

パズルグリッドにピースを追加するには、スクリプトエディタ (Script Editor) で、new_game.lua スクリプトの内容を次のように置き換えます。

print("Entering new_game.lua")

-- Find the "Grid" node using its alias.
local grid = contextNode:lookupNode("#Grid")
assert(grid)

-- Find the "fifteen_puzzle.PieceIndex" custom property type.
local PieceIndexProperty = PropertyType:find("fifteen_puzzle.PieceIndex")

-- Find the "Piece" prefab.
local piecePrefab = contextNode:tryAcquireResource("kzb://fifteen_puzzle/Prefabs/Piece")

-- Declare the constants for the grid size and number of pieces.
-- The number of pieces is one less than the number of grid slots
-- because you need an empty slot to play the game.
local RowCount = 4
local ColumnCount = 4
local PieceCount = RowCount * ColumnCount - 1

-- Remove all grid items that were created in the project or by the earlier
-- executions of the script.
grid:removeAllChildren()

-- Create the grid child nodes.
for i = 1,PieceCount do
    -- Create a grid item.
    local piece = piecePrefab:instantiate("piece_" .. i)

    -- Assign the number to the piece.
    piece:setProperty(PieceIndexProperty, i)

    -- Set the grid coordinates of the node.
    -- Use integer division to get the row index and modulo to get the column index.
    local row = (i-1) // ColumnCount
    local column = (i-1) % ColumnCount
    piece:setProperty(GridLayout2D.RowProperty, row)
    piece:setProperty(GridLayout2D.ColumnProperty, column)

    -- Add the node to the grid.
    grid:addChild(piece)
end

print("Exiting new_game.lua")

スクリプトを保存し、プレビュー で リスタート (Restart) をクリックすると、スクリプトはグリッドに1から15までの順に15個のピースを配置し、グリッドの最後のスロットを空のままにします。

../../_images/step3-result.png

関連項目

ノードプレハブの使用

プロパティシステム