本帖最后由 犯困嫌疑人 于 2023-5-12 10:53 编辑
1.首先先随手搭建一个UI,这个UI包含了一个滑动条和一个文本
我们将它起名为UIHP。并导出UI。
2.新建一个脚本~叫做HPBar
import UIHP_Generate from "./ui-generate/UIHP_generate";
@Core.Class
export default class HPBar extends Core.Script {
@Core.Property({ replicated: true, onChanged: "onHpChange" })
public maxHp: number = 0;
@Core.Property({ replicated: true, onChanged: "onHpChange" })
public hp: number = 0;
private _hpBarUI: UIHP_Generate;
private _hpBarWidget: Gameplay.UIWidget;
private _isInit = false;
/** 当脚本被实例后,会在第一帧更新前调用此函数 */
protected onStart(): void {
if (SystemUtil.isClient()) {
console.log("qwq")
this.init();
}
}
private async init() {
this._hpBarUI = UI.UIManager.instance.create(UIHP_Generate);
this._hpBarWidget = await Gameplay.GameObject.asyncSpawn<Gameplay.UIWidget>({ guid: "UIWidget", replicates: false });
this._hpBarWidget.setTargetUIWidget(this._hpBarUI.uiWidgetBase);
this._hpBarWidget.widgetSpace = Gameplay.WidgetSpaceMode.OverheadUI;
let character = this.gameObject as Gameplay.CharacterBase;
this._hpBarWidget.attachToGameObject(character.getHeadUIWidget())
this._hpBarWidget.relativeLocation = Vector.up.multiply(-10);
this._isInit = true;
this.onHpChange();
}
private onHpChange() {
if (!this._isInit) {
return;
}
this._hpBarUI.mScollHP.percent = this.hp / this.maxHp;
this._hpBarUI.mTextHPNum.text = `${this.hp}/${this.maxHp}`;
}
protected onDestroy(): void {
this._hpBarUI?.destroy();
this._hpBarWidget?.destroy();
}
}
再新建一个脚本,叫做GameLauncher来测试这个脚本
import HPBar from "./HPBar"
@Core.Class
export default class GameLauncher extends Core.Script {
private _hpbarMap: Map<number, HPBar> = new Map();
/** 当脚本被实例后,会在第一帧更新前调用此函数 */
protected onStart(): void {
if (SystemUtil.isServer()) {
Events.addPlayerJoinedListener(async (player: Gameplay.Player) => {
let hpbar = await Gameplay.Script.spawnScript(HPBar, true, player.character);
hpbar.maxHp = 100;
hpbar.hp = 80;
this._hpbarMap.set(player.getPlayerID(), hpbar);
})
Events.addPlayerLeftListener((player: Gameplay.Player) => {
if (this._hpbarMap.has(player.getPlayerID())) {
this._hpbarMap.get(player.getPlayerID()).destroy();
this._hpbarMap.delete(player.getPlayerID());
}
})
}
}
}
把GameLauncher拖入到场景中,我们就可以看到效果了。在实战中去服务器修改对应scripts的hp值和mhp就可以达到效果了。
|