概要
実行中に特定の属性を持つ、もしくは与える為に後からスクリプトを追加したい場合の方法と、既に処理が完了し、残しておく必要が無いスクリプトを削除したい場合の方法。
実装例
追加
addSample.js
var AddSample = pc.createScript('addSample');
AddSample.attributes.add('name', {type: string, default: 'None'});
AddSample.prototype.initialize = function(){
console.log('Hello, ' + this.name);
};
main.js
var Main = pc.createScript('main');
Main.prototype.initialize = function(){
// Scriptコンポーネントがあるかをチェックする ※今回の場合は本来不要
if( this.entity.script ){
// create()で追加する
// 第2引数でアトリビュートの初期化も可能
this.entity.script.create('addSample', {
attributes: {
name: 'John'
}
});
}
};
一度だけコンソールに挨拶を表示するスクリプト addSample を初期化時に追加しています。
create()できるのはレジストリに登録されたスクリプトだけなので、PlayCanvas上のScriptの設定でPreloadの項目にチェックが入っているスクリプトでのみ可能な方法です。
create()できない場合はコンソールに下記のような警告が表示されます。
script '指定したスクリプト名' is not found, awaiting it to be added to registr
削除
main.js
var Main = pc.createScript('main');
Main.prototype.destroyUsedScript = function(){
// Scriptコンポーネントに削除したいスクリプトがあるかをチェックする
if( this.entity.script && this.entity.script.has('addSample') ){
// destroy()で削除する
this.entity.script.destroy('addSample');
}
};
指定したentityから指定したスクリプト名のスクリプトを削除するというシンプルな処理です。
今回はスクリプトを持っているかを判定していますが、なくても警告は出ません。(2020/11/05現在)