目前有两个办法加载预制体,一个是动态加载,一个是放到scene上
动态加载
showTip(str){
//我們先動態取得Canvas
var CanvasNode = cc.find( 'Canvas' );
if( !CanvasNode ) { cc.log( 'find Canvas error' ); return; }
var onResourceLoaded = function(errorMessage, loadedResource )
{
if( errorMessage ) { cc.log( 'Prefab error:' + errorMessage ); return; }
if( !( loadedResource instanceof cc.Prefab ) ) { cc.log( 'Prefab error' ); return; }
var newMyPrefab = cc.instantiate( loadedResource );
CanvasNode.addChild( newMyPrefab );
newMyPrefab.setPosition( 0, 0 );
var newMyPrefabScript = newMyPrefab.getComponent( 'showTips' );
newMyPrefabScript.setLabelString(str );
};
cc.loader.loadRes('prefabs/tips', onResourceLoaded );
}
静态加载
将预制体拖入scene中,在预制体的onload中,将自己加入window
onLoad:function () {
cc.log("showTips.onLoad")
window.showtips = this;
// 初始化计时器
this.timer = 0;
this.node.active = this._isShow;
},
接下来使用就很方便了
window.showtips.run("aaa")
预制体代码如下:
// Learn cc.Class:
// - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/class.html
// - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/class.html
// Learn Attribute:
// - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
// - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
// - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
// - [English] https://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html
cc.Class({
extends: cc.Component,
properties: {
Text: { default: null, type: cc.Label },
showTimes: 1, //隐藏时间
jumpHeight: 100, //跳跃高度
_isShow:false,
},
// LIFE-CYCLE CALLBACKS:
setLabelString: function( str )
{
//這邊直接將我們的Label字串設定為 No.#
this.Text.string = ( str );
},
onLoad:function () {
cc.log("showTips.onLoad")
window.showtips = this;
// 初始化计时器
this.timer = 0;
this.node.active = this._isShow;
},
setJumpAction: function () {
this.timer = 0;
// 跳跃
var jumpDown = cc.moveBy(this.showTimes, cc.v2(0, this.jumpHeight)).easing(cc.easeCubicActionIn());
var callback = cc.callFunc(this.finish, this);
return cc.repeat(cc.sequence(jumpDown,callback),1);
},
finish:function(){
this._isShow = false;
if(this.node){
this.node.active = this._isShow;
}
this.node.stopAllActions();
this.node.destroy();
},
start:function () {
cc.log("showTips.start")
},
run:function (str) {
this._isShow = true;
if(this.node){
this.node.active = this._isShow;
}
this.setLabelString(str)
this.jumpAction = this.setJumpAction();
this.node.runAction(this.jumpAction);
},
update:function (dt) {
var opacityRatio = 1 - this.timer/this.showTimes;
var minOpacity = 50;
this.node.opacity = minOpacity + Math.floor(opacityRatio * (255 - minOpacity));
if (this.timer > this.showTimes) {
this.finish();
return;
}
this.timer += dt;
},
});