在Puerts中使用
准备工作
- 在Unity编辑器的Scripting Define Symbols里增加
FAIRYGUI_PUERTS。 - 可以参考以下代码生成FairyGUI的声明文件和胶水代码文件(仅供参考,可以自行根据Puerts要求实现)。
[Binding]
static IEnumerable<Type> Bindings
{
get
{
List<Type> result = new List<Type> {
List<string> namespaces = new List<string>()
{
"FairyGUI",
"FairyGUI.Utils",
};
Assembly[] ass = AppDomain.CurrentDomain.GetAssemblies();
result.AddRange((from assembly in ass
where !(assembly.ManifestModule is System.Reflection.Emit.ModuleBuilder)
from type in assembly.GetExportedTypes()
where type.Namespace != null && namespaces.Contains(type.Namespace) && !isExcluded(type)
&& type.BaseType != typeof(MulticastDelegate) && !type.IsEnum
select type));
return result;
}
}
监听事件
function onClick() {
console.log('you click');
}
//也可以带上事件参数
function onClick(context:EventContext) {
console.log('you click', context.sender);
}
FairyGUI.UIPackage.AddPackage('Demo');
let view = FairyGUI.UIPackage.CreateObject('Demo', 'DemoMain');
FairyGUI.GRoot.inst.AddChild(view);
view.onClick.Add(onClick);
//view.onClick.Remove(onClick);
//view.onClick.Set(onClick);
使用Window类
FairyGUI提供的Window类,一般需要开发者自己扩展,例如覆盖OnShown,OnHide等。在Puerts里,编写Window扩展的方法是:
class DemoWindow extends FairyGUI.Window {
public constructor() {
super();
this.__onInit = ()=> { this.onInit(); };
this.__onShown = ()=> { this.onShown(); };
this.__onHide = ()=> { this.onHide(); };
// this.__doShowAnimation = ()=> { this.doShowAnimation(); };
// this.__doHideAnimation = ()=> { this.doHideAnimation(); };
}
private onInit(): void {
this.contentPane = FairyGUI.UIPackage.CreateObject("Basics", "WindowA").asCom;
}
private onShown():void {
}
private onHide():void {
}
}
//创建并显示窗口
let win = new DemoWindow();
win.Show();
自定义扩展
FairyGUI在C#里可以使用UIObjectFactory.SetPackageItemExtension进行自定义扩展。在Puerts里,同样可以这样做。方法如下:
- 定义扩展类。注意基础类型,不要搞错。例如按钮是GButton,一般的组件则是GComponent。
class MyButton extends FairyGUI.GButton {
public myProp:string;
public constructor() {
super();
this.__onConstruct = () => { this.onConstruct(); };
}
public onConstruct(): void {
}
public test() {
}
}
- 注册扩展类。要在创建任何对象前注册好。
FairyGUI.UIObjectFactory.SetPackageItemExtension("ui://包名/我的按钮", () => { return new MyButton();});
- 完成以上两步后,任何“我的按钮”这个资源创建出来的对象都可以使用MyButton访问了。例如:
let myButton = <MyButton>someComponent.GetChild("myButton"); //这个myButton的资源是“我的按钮”
myButton.test();
myButton.myProp = 'hello';