Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

fix(cocos): a node's scripts load and enable as it joins an active parent or is switched, not a frame later; a converted script component's dropped fields are ignored quietly

yhhb4e23de81769
diff --git a/sdk/src/cocos/host.ts b/sdk/src/cocos/host.ts
index da2c5d25e..8f3c8e964 100644
--- a/sdk/src/cocos/host.ts
+++ b/sdk/src/cocos/host.ts
@@ -15,6 +15,7 @@
*/
import { defineComponent } from '../ecs/component';
import { Schedule, defineSystem, addSystemToSchedule, GetWorld } from '../ecs/system';
+import { Children } from '../ecs/component';
import { Query, Mut } from '../ecs/query';
import { Res, Time } from '../ecs/resource';
import type { World } from '../ecs/world';
@@ -23,7 +24,7 @@ import { log } from '../util/logger';
import { Color, Vec2, Vec3 } from './math';
import { Node, setCurrentWorld } from './node';
import {
- COMPONENT_PREFIX, classInfoOf, dropInstance, instancesOfClass, instancesOn, nodeOf, registerClassInfo, setInstantiator, storeInstance,
+ COMPONENT_PREFIX, classInfoNamed, classInfoOf, dropInstance, instancesOfClass, instancesOn, nodeOf, registerClassInfo, setActivitySync, setInstantiator, storeInstance,
type ClassInfo, type ComponentCtor, type PropertyKind, type PropertySpec,
} from './registry';
@@ -132,6 +133,45 @@ function instantiate(world: World, entity: Entity, ctor: ComponentCtor): Compone
}
setInstantiator(instantiate);
+/**
+ * Bring the scripts of a node and everything under it to the state its activity says, at once: the classes it carries are made (`onLoad`)
+ * while it is active, and `onEnable` / `onDisable` run as the switch changed. `start` and `update` stay with the frame.
+ */
+function syncSubtree(world: World, root: Entity): void {
+ const previous = setCurrentWorld(world);
+ try {
+ const stack: Entity[] = [root];
+ while (stack.length > 0) {
+ const entity = stack.pop()!;
+ if (!world.valid(entity)) continue;
+ const active = world.isEntityActive(entity);
+ const made: Component[] = [];
+ for (const type of world.getComponentTypes(entity)) {
+ if (!type.startsWith(COMPONENT_PREFIX)) continue;
+ const info = classInfoNamed(type.slice(COMPONENT_PREFIX.length));
+ if (!info) continue;
+ const inst = instancesOn(world, entity)?.get(info.ctor) ?? (active ? instantiate(world, entity, info.ctor) : null);
+ if (inst) made.push(inst);
+ }
+ for (const inst of made) {
+ const on = inst.enabled && active;
+ if (on && !inst._enabledApplied) {
+ inst._enabledApplied = true;
+ call(inst, 'onEnable');
+ } else if (!on && inst._enabledApplied) {
+ inst._enabledApplied = false;
+ call(inst, 'onDisable');
+ }
+ }
+ const children = world.tryGet(entity, Children)?.entities;
+ if (children) for (let i = children.length - 1; i >= 0; i--) stack.push(children[i]!);
+ }
+ } finally {
+ setCurrentWorld(previous);
+ }
+}
+setActivitySync(syncSubtree);
+
/** Run the per-frame part of one instance: enable/disable as its activity changes, then `start` once, then the timers and `update`. */
function drive(world: World, entity: Entity, inst: Component, dt: number): void {
const active = inst.enabled && world.isEntityActive(entity);
diff --git a/sdk/src/cocos/node.ts b/sdk/src/cocos/node.ts
index 5530bf1e4..443a6509f 100644
--- a/sdk/src/cocos/node.ts
+++ b/sdk/src/cocos/node.ts
@@ -17,7 +17,7 @@ import type { World } from '../ecs/world';
import { INVALID_ENTITY, type Entity } from '../types';
import { Quat, Vec3 } from './math';
import {
- classInfoNamed, classInfoOf, ensureInstance, instancesOn, nodeOf, setNodeFactory,
+ classInfoNamed, classInfoOf, ensureInstance, instancesOn, nodeOf, setNodeFactory, syncActivity,
type ComponentCtor,
} from './registry';
import type { Component } from './component';
@@ -144,6 +144,7 @@ export class Node {
set active(value: boolean) {
if (setDetachedActive(this._world, this._entity, value)) return;
setEntityActive(this._world, this._entity, value);
+ syncActivity(this._world, this._entity);
}
/** This node's switch and every ancestor's. */
@@ -168,6 +169,7 @@ export class Node {
if (parent) {
this._world.setParent(this._entity, parent._entity);
releaseDetached(this._world, this._entity);
+ syncActivity(this._world, this._entity);
} else this._world.removeParent(this._entity);
}
diff --git a/sdk/src/cocos/registry.ts b/sdk/src/cocos/registry.ts
index 696425de9..81d37b144 100644
--- a/sdk/src/cocos/registry.ts
+++ b/sdk/src/cocos/registry.ts
@@ -135,6 +135,18 @@ let instantiator: ((world: World, entity: Entity, ctor: ComponentCtor) => Compon
export function setInstantiator(fn: (world: World, entity: Entity, ctor: ComponentCtor) => Component | null): void {
instantiator = fn;
}
+let activitySync: ((world: World, entity: Entity) => void) | null = null;
+export function setActivitySync(fn: (world: World, entity: Entity) => void): void {
+ activitySync = fn;
+}
+/**
+ * A node joined an active parent, or was switched on or off: its scripts' `onLoad`, `onEnable` and `onDisable` run now, as they do in
+ * Cocos, and not on the next frame (a script that sets a value right after `addChild` would otherwise be undone by an `onEnable` that
+ * runs later).
+ */
+export function syncActivity(world: World, entity: Entity): void {
+ activitySync?.(world, entity);
+}
/** The instance of @p ctor on @p entity, made (and its `onLoad` run) if the entity has the component and it has none yet; null if the entity does not have it. */
export function ensureInstance(world: World, entity: Entity, ctor: ComponentCtor): Component | null {
const existing = instancesOn(world, entity)?.get(ctor);
diff --git a/sdk/src/scene/scene.ts b/sdk/src/scene/scene.ts
index 7b0b6e77a..dd5ca57f7 100644
--- a/sdk/src/scene/scene.ts
+++ b/sdk/src/scene/scene.ts
@@ -776,7 +776,12 @@ export function loadComponent(world: World, entity: Entity, compData: SceneCompo
const root = err.field in compData.data ? err.field : err.field.split('.')[0];
delete compData.data[root];
}
- log.warn(
+ // A converted Cocos script component carries what its scene serialized, including fields the class has since dropped; Cocos ignores
+ // those without a word, and so does this.
+ const stale = compData.type.startsWith('Cocos.') && errors.every((e) => e.actual === 'unknown field');
+ const report = stale ? log.debug : log.warn;
+ report.call(
+ log,
'scene',
`${formatValidationErrors(compData.type + context, errors)}\n → invalid fields dropped, their defaults apply (fix the scene file to silence this)`
);
diff --git a/sdk/tests/cocos/script-active-wasm.test.ts b/sdk/tests/cocos/script-active-wasm.test.ts
index 46ee8c8a9..d9ea9071f 100644
--- a/sdk/tests/cocos/script-active-wasm.test.ts
+++ b/sdk/tests/cocos/script-active-wasm.test.ts
@@ -73,4 +73,48 @@ describe.skipIf(!HAS_WASM)('a script that switches nodes on and off', () => {
expect(Node.for(app.world, map.get(1)!).active).toBe(true);
expect(started).toContain('bystander');
});
+
+ it('enables a script as soon as its node joins an active parent, so a value set right after addChild is not undone', async () => {
+ setDefaultContext(new AppContext());
+ ensureBuiltinComponentsRegistered();
+ resetClassRegistry();
+ declareBuiltinScripts();
+ const calls: string[] = [];
+
+ @_decorator.ccclass('Resetter')
+ class Resetter extends Component {
+ opacity = 0;
+ onEnable() { calls.push('enable'); this.opacity = 255; }
+ onDisable() { calls.push('disable'); }
+ }
+ void Resetter;
+
+ registry = new module.Registry();
+ app = App.new();
+ app.connectCpp(registry as never, module);
+ flushPendingRegistrations(app);
+ setCurrentWorld(app.world);
+ const map = loadSceneData(app.world, {
+ version: SCENE_FORMAT_VERSION, name: 'main',
+ entities: [
+ { id: 0, name: 'Parent', parent: null, children: [1], visible: true, components: [transform] },
+ { id: 1, name: 'Child', parent: 0, children: [], visible: true, components: [transform, { type: 'Cocos.Resetter', data: { enabled: true } }] },
+ ],
+ } as unknown as SceneData);
+ const child = Node.for(app.world, map.get(1)!);
+ child.setParent(null);
+ child.active = false;
+ calls.length = 0;
+ // an orphan that is switched on and given a parent: onEnable runs inside the call
+ child.active = true;
+ child.setParent(Node.for(app.world, map.get(0)!));
+ const resetter = child.getComponent(Resetter)!;
+ resetter.opacity = 120;
+ expect(calls).toContain('enable');
+ await app.tick(1 / 60);
+ expect(resetter.opacity).toBe(120);
+
+ child.active = false;
+ expect(calls).toContain('disable');
+ });
});