Nanfeng

Notes on software development, code, and curious ideas

Loading CSB Files and Binding Controls in Cocos2d-x 3.17 Lua

Cocos Studio exports a scene or UI layout as a CSB file. Cocos2d-x 3.17 Lua can load the node tree through cc.CSLoader, after which named controls can be found and bound to callbacks.

Load a layout directly

1
2
3
4
5
6
7
8
9
10
local root = cc.CSLoader:createNode("ui/MenuScene.csb")
assert(root, "failed to load MenuScene.csb")
self:addChild(root)

local startButton = root:getChildByName("Button_Start")
assert(startButton, "Button_Start is missing")

startButton:addClickEventListener(function(sender)
print("start clicked", sender:getName())
end)

For nested controls, either follow the hierarchy with repeated getChildByName calls or use a deliberate recursive lookup helper. Duplicate names make recursive lookup ambiguous, so use unique names for controls that code accesses.

Touch listeners can inspect the event type:

1
2
3
4
5
startButton:addTouchEventListener(function(sender, eventType)
if eventType == ccui.TouchEventType.ended then
print("touch ended")
end
end)

Load a timeline

1
2
3
local timeline = cc.CSLoader:createTimeline("ui/MenuScene.csb")
root:runAction(timeline)
timeline:play("show", false)

The animation name must match the Cocos Studio export.

A reusable view base

A project-level ViewBase can define RESOURCE_FILENAME, create the CSB root, expose a binding phase, and centralize lifecycle cleanup. Derived views should declare their resource and bind only the controls they own. Fail early when a required node is missing instead of storing nil and crashing much later.

Keep CSB names and code changes in the same review, avoid business logic inside the loader, and remove event listeners or scheduled callbacks when the view exits.

+