https://docs.cocos.com/creator/3.8/manual/zh/engine/event/event-screen.html#事件使用示例
我使用时一个都没响应呀?
为啥是监听“change”
你这代码也不对呀,根本没按照文档来
https://docs.cocos.com/creator/3.8/manual/zh/engine/event/event-screen.html#事件使用示例
import { _decorator, Component, screen, macro } from 'cc';
const { ccclass } = _decorator;
@ccclass("Example")
export class Example extends Component {
onLoad() {
// Register event listeners with the screen object
screen.on('window-resize', this.onWindowResize, this);
screen.on('orientation-change', this.onOrientationChange, this);
screen.on('fullscreen-change', this.onFullScreenChange, this);
}
onDestroy() {
// Unregister event listeners when the component is destroyed
screen.off('window-resize', this.onWindowResize, this);
screen.off('orientation-change', this.onOrientationChange, this);
screen.off('fullscreen-change', this.onFullScreenChange, this);
}
onWindowResize(width: number, height: number) {
console.log("Window resized:", width, height);
}
onOrientationChange(orientation: number) {
if (orientation === macro.ORIENTATION_LANDSCAPE_LEFT || orientation === macro.ORIENTATION_LANDSCAPE_RIGHT) {
console.log("Orientation changed to landscape:", orientation);
} else {
console.log("Orientation changed to portrait:", orientation);
}
}
onFullScreenChange(width: number, height: number) {
console.log("Fullscreen change:", width, height);
}
}
效果如下,能正常监听:
另外,需要注意的是,在编写完组件脚本后,需要把脚本挂载到场景中已激活的节点上
参考文档:创建脚本 | Cocos Creator