Cocos Creator兩個類相互引用(調用)


如果兩個類相互引用,腳本加載階段就會出現循環引用,循環引用將導致腳本加載出錯:
///////////Game.js
var Item = require("Item");
var Game = cc.Class({
properties: {
item: {
default: null,
type: Item //用 Item 對象
}
}
});
module.exports = Game;

//////////Item.js
var Game = require("Game");
var Item = cc.Class({
properties: {
game: {
default: null,
type: Game //用 Game 對象
}
}
});
module.exports = Item;

上面兩個腳本加載時,由於它們在 require 的過程中形成了閉環,因此加載會出現循環引用的錯誤,循環引用時 type 就會變為 undefined。
因此我們提倡使用以下的屬性定義方式:

/////////Game.js
var Game = cc.Class({
properties: () => ({ //箭頭函數在腳本加載中不會同步執行,而是在所有腳本加載成功后才調用。
item: {
default: null,
type: require("Item")
}
})
});
module.exports = Game;

////////Item.js
var Item = cc.Class({
properties: () => ({
game: {
default: null,
type: require("Game")
}
})
});
module.exports = Item;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM