flex游戏引擎(PushButton)直接访问其它组件

直接访问其它组件,使用通用接口或直接访问

If all else fails, you can directly access another component, either using a common interface or directly.

There are three methods to directly access a component in an entity. Use owner for your own entity, or lookup and use another entity to get components from somewhere else. The methods:

  • lookupComponentByName which looks up a single named component and returns it.
  • lookupComponentByType which looks up a single component by type and returns it.
  • lookupComponentsByType which finds all components that match the specified type.

Here's a simple example of directly accessing another component:

01. // Interface implemented by another component. 其它组件也使用该接口IExampleInterface
02. interface IExampleInterface
03. {
04.    function getBigArray():Array;
05. }
06.   
07. class TestComponent extends EntityComponent
08. {
09.    public otherComponentName:String = "anotherComponent";
10.      
11.    public function AccessSomeData():void
12.    {
13.       var otherItem:IExampleInterface = owner.lookupComponentByName(otherComponentName, IExampleInterface) as IExampleInterface;
14.         
15.       for each(var i:* in otherItem.getBigArray())
16.          trace(i);
17.    }
18. }

These functions are cheap, and calling them once a tick won't slow anything down. However, if you do need to store a permanent reference to a component, make sure to clear and re-establish it when onReset() is called. Otherwise, you may access stale data(无效陈旧数据) or cause a memory leak(内存泄露).

01. // Just like the previous component, but it keeps the reference around longer.
02. class TestComponent extends EntityComponent
03. {
04.    public var anotherComponent:IExampleInterface;
05.   
06.    protected function onAdd():void
07.    {
08.       super.onAdd();
09.       anotherComponent = owner.LookupComponentByType(IExampleInterface) as IExampleInterface;
10.    }
11.      
12.    protected function onReset():void
13.    {
14.       super.onReset();
15.       anotherComponent = owner.LookupComponentByType(IExampleInterface) as IExampleInterface;
16.    }
17.      
18.    protected function onRemove():void
19.    {
20.       super.onRemove();
21.         
22.       // Don't forget to clear the reference to prevent memory leaks.
23.       anotherComponent = null;
24.    }
25.      
26.    public function DoSomething():void
27.    {
28.       for each(var i:* in anotherComponent.getBigArray())
29.          Logger.print(this, i);
30.    }
31. }

Linkage Issues

When you are using components that are only mentioned in level files, the Flex compiler won't know they are being used and may remove them. To prevent this, use the helper function PBE.registerType. For example:

1. PBE.registerType(com.pblabs.rendering2D.DisplayObjectRenderer);

你可能感兴趣的:(游戏,Flex,Access,UP)