Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

UnityShared.swc; Communicating between Unity Flash Content and AS3.

Discussion in 'Flash' started by RalphH, Dec 23, 2011.

  1. RalphH

    RalphH

    Administrator

    Joined:
    Dec 22, 2011
    Posts:
    592
    [Edit by Cat: Please note that the below example does not work in Unity 3.5.2. The updated project can be found here.]

    By popular demand, here's an example of how one can use UnityShared.swc to create a custom preloader and communicate between Unity and Flash.

    The ActionScript source of this project can be used with ActionScript tools like FlashBuilder, FDT and FlashDevelop. The project needs to be setup so that the provided UnityShared.swc is used as a library.

    View attachment $AS3Communication_unity_project.zip
    View attachment $AS3Communication_as3_src.zip

    In UnityShared an AS3 class named UnityContentLoader is provided, which is the base for loading and communicating with UnityContent.

    When publishing to Flash Application.ExternalCall is routed to what is set as the UnityContentHost, when constructing the UnityContentLoader. These messages (unfortunately there is no way to send arguments at this point in time using Application.ExternalCall), then are directly called on IUnityContentHost.

    The unityInitStart and unityInitComplete have to be implemented by the class set as IUnityContentHost and signify when the UnityContent is done loading and starting to initialize, and when it's done initializing, and ready for communication from AS3.

    To communicate from AS3 to Unity, one calls sendMessage on the unityContent property of unityContentLoader. The sendMessage functionality is similar to the sendMessage functionality of the Unity webplayer.

    sendMessage accepts arguments in the following order; first a string path to the gameobject, then the method to be called on that gameobject, and then an anonymous object to contain the arguments. This way, one can marshall direct references to objects between AS3 and Unity, cache them and call them directly.

    This api is by no means in it's final state and are subject to change in later drops(we are thinking about a full api inside unity towards AS3, similar to custom platform api's for other platforms), but it should help implementing things like networking.

    I'll post more examples in this thread.

    Regards,
    Ralph.
     
    Last edited by a moderator: May 28, 2012
  2. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    3,752
    Wow thanks for this. Unfortunately I'm getting a little red box with "Fatal Error : null" when I try compile this or just run the swf provided. Any idea where I may have gone wrong?
     
    Last edited: Dec 23, 2011
  3. RalphH

    RalphH

    Administrator

    Joined:
    Dec 22, 2011
    Posts:
    592
    You need a content debugger of the flashplayer; please check out the faq here; http://unity3d.com/unity/preview/faq

    Without a proper error message I can't tell you what's going on, but most likely your swf isn't published with version=13 or your wmode isn't set to direct on the flash embed, or your flashplayer is lower then 11.
     
  4. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    3,752
    Silly me. Forgot I had 11.2 beta build installed. Cheers.

    -edit- hmm actually runs fine in 11.2 content debugger. just null errors in browser.
     
    Last edited: Dec 23, 2011
  5. laurent-clave

    laurent-clave

    Joined:
    Jul 18, 2011
    Posts:
    280
    Thank Ralph,

    You can send and receive an arguments with this method (Replace WWW WWWForm) ?
     
  6. RalphH

    RalphH

    Administrator

    Joined:
    Dec 22, 2011
    Posts:
    592
    darkloy, yes, check out the provided example; it show sending arguments both ways.
     
  7. laurent-clave

    laurent-clave

    Joined:
    Jul 18, 2011
    Posts:
    280
    Ok Sorry Ralph !! ;)
     
  8. vtornik23

    vtornik23

    Joined:
    Jul 1, 2010
    Posts:
    27
    Hi Ralph! Thank you for your post.
    Can you tell us, is it possible now to integrate compiled stage3d layer (that unity builds) with native flash GUI?
    I mean in FlashDevelop or FlashBuilder
     
  9. RalphH

    RalphH

    Administrator

    Joined:
    Dec 22, 2011
    Posts:
    592
    @darkloy : glad I could help, let us know how it works out for you.
     
  10. RalphH

    RalphH

    Administrator

    Joined:
    Dec 22, 2011
    Posts:
    592
    Hi vtornik, in the example I remove the entire opaque preloaded from the stage; however, you can keep an overlay sprite / movie clip over the stage3d content. Keep in mind that this on some configurations/platforms might cost you some performance. However, it's entirely possible do your overlaying gui in flash and the game and the 3d in unity!

    We'd love to see an example of someone using that functionality; let us know what you manage to do with it !
     
    Last edited: Dec 23, 2011
  11. vtornik23

    vtornik23

    Joined:
    Jul 1, 2010
    Posts:
    27
    Thank you a lot, Ralph!
     
  12. laurent-clave

    laurent-clave

    Joined:
    Jul 18, 2011
    Posts:
    280
    @UnityRalph : Ok, no problem ;)
     
  13. laurent-clave

    laurent-clave

    Joined:
    Jul 18, 2011
    Posts:
    280
    If you provide other examples I would be very happy: D ...
     
  14. Nevers

    Nevers

    Joined:
    May 6, 2008
    Posts:
    39
    i'm trying to run the example in ie8 with the flash debugger and running vizzy flash tracer but when i click the button, nothing seems to happen.
    any ideas on what i'm doing wrong?
     
  15. carllooper

    carllooper

    Joined:
    Aug 8, 2009
    Posts:
    64
    Thanks Ralph.
     
  16. rogerisland

    rogerisland

    Joined:
    Dec 23, 2011
    Posts:
    3
    Hi Ralph,

    This is really good stuff - just one more question:
    Via the sendMessage method what sort of objects could I theoretically push accross from Flash to Unity? I'm thinking images (loaded from web or created) or audio files... is that possible? As a kind of WWW. replacement as it's missing in the current release?

    Thanks!
     
  17. RalphH

    RalphH

    Administrator

    Joined:
    Dec 22, 2011
    Posts:
    592
  18. RalphH

    RalphH

    Administrator

    Joined:
    Dec 22, 2011
    Posts:
    592
    @rogerisland; I'd advice to handle that type of media on the AS3 side for now; however, I will follow up with a new example showing how to for example put a video on a unity texture.
     
  19. Nevers

    Nevers

    Joined:
    May 6, 2008
    Posts:
    39
    so i went back and reinstalled the setup and followed the instructions and as far as i can tell, it's still not working:

    Install "content debugger" from Adobe Flash Player [used ie9]:
    Check
    Go to http://flashplayerversion.com/, and make sure that it says 'Debugger: Yes': [says WIN 11,1,102,55]
    Check
    Create a file called mm.cfg and added ErrorReportingEnable=1; TraceOutputFileEnable=1
    Check

    i drag the AS3Communication.html into the browser, it loads up, it says running the in the debug player at the bottom right of the screen.
    i click the button a few times

    Find and open your flashlog.txt
    it says: Player: init engine [space] MolehillGfxDevice: DirectX9 (Direct blitting)

    is this "Player: init engine MolehillGfxDevice: DirectX9 (Direct blitting)" the result i'm looking for? this appears before i press the button and only appears on load so i'm assuming the expected result would be different.
     
  20. RalphH

    RalphH

    Administrator

    Joined:
    Dec 22, 2011
    Posts:
    592
    Shifty Nevers : that looks fine to me; if you now hit the button you should get the flash traces; depending on what you compile the source with though, it might be stripping the traces out of the source code I provided above.
     
  21. carllooper

    carllooper

    Joined:
    Aug 8, 2009
    Posts:
    64
    I mentioned this in another thread but what would be really cool is to develop another api inside AS3 towards unity. In other words, an api targeting AS3 developers.

    I realise the current priority would be to assist unity developers in exporting from unity to flash, but there is a whole new market opened up here - for targeting AS3 developers. In other words the starting context would not be Unity but the Flash paradigm (Flex/.FlashDevelop) and the goal would be importing and controlling unity generated assets (AS3 files, etc).

    In both cases the end result is still Flash (swf/swc etc), but the difference being that one uses AS3 to write important code, rather than C# and Javascript (or in addition to such).

    Carl
     
  22. rogerisland

    rogerisland

    Joined:
    Dec 23, 2011
    Posts:
    3
    Hi Ralph, Thanks for the response. I'd need to load a texture from internet (created by a script) onto an object as part of the thing that I'm working on so can't do it in just all in AS3, so was thinking to load it in AS3 and push image object over to Unity for it to display on object. I guess it's simliar to the video texture example you've mentioned so I'll wait for that :)

    Thanks again for the quick response!
     
  23. RalphH

    RalphH

    Administrator

    Joined:
    Dec 22, 2011
    Posts:
    592
    @carllooper, it's a use case which we have thought and talked about indeed, however, priority right now is to make it work as fluid as can be with Unity. We have this on the radar, and the first steps are to improve the embedding API.
     
  24. Nevers

    Nevers

    Joined:
    May 6, 2008
    Posts:
    39
    i haven't edited any source yet. i've just simply downloaded, extracted and dragged the swf and html files into the browser. I've tried this at work at home and still no luck lol. I have cs4 installed so i'm thinking something may be blocking the traces. i'll try it on another machine with almost nothing installed and see if it works. Thx for the replys btw
     
  25. carllooper

    carllooper

    Joined:
    Aug 8, 2009
    Posts:
    64
    @UnityRalph, thanks Ralph. I look forward to the evolution of the Unity/Flash feature. The current iteration is great and there is plenty to test and play with. It's the best xmas present I've had in years. cheers.
     
  26. Mackey@ehsiplus.com

    Mackey@ehsiplus.com

    Joined:
    Jun 27, 2009
    Posts:
    45

    I was able to duplicate what the SimpleLoader.as does in Adobe Air With ActionScript3 ONLY project. Worked great... i can use other actionscript only classes and popup my own as3 only gui on top unitycontent...

    But when i try to do the same thing in a Flex Application (Air 3.2 or 3.1)... Once it execute the comple function:

    private function onUnityContentLoaderComplete(event:Event):void
    {
    uix.addChild(unityContentLoader);
    unityContentLoader.unityContent.setContentHost(this);//Set this instance as the callback handler for unity.
    }


    where uix is a <mx:UIComponent>

    IS DOES NOT SHOW THE SCENE... JUST WHITE BACKGROUND...

    Any thoughts on loading the unity content in a flex application?
     
  27. RalphH

    RalphH

    Administrator

    Joined:
    Dec 22, 2011
    Posts:
    592
    @shiftynevers; then it works as expected; you actually need to compile the source code in the AS3 example; you are looking at the "unembedded" unity content, which doesn't actually trace anything, because it's not embedded and thus has not UnityContentHost to call bac k into.
     
  28. RalphH

    RalphH

    Administrator

    Joined:
    Dec 22, 2011
    Posts:
    592
    @carllooper; glad you like it!
     
  29. RalphH

    RalphH

    Administrator

    Joined:
    Dec 22, 2011
    Posts:
    592
    @mackey, your problem can reside in many different area's. After xmas I'll post a flex embedding demo.
     
  30. Mackey@ehsiplus.com

    Mackey@ehsiplus.com

    Joined:
    Jun 27, 2009
    Posts:
    45
    Thanks Ralph ...

    Can't wait to see what you come up with.

    Running unity content in as3 project is awesome ... Doing it in a flex app would be "off the hook"... The types of apps you will be able to make will be insane...

    I love unity3d :)
     
  31. Mackey@ehsiplus.com

    Mackey@ehsiplus.com

    Joined:
    Jun 27, 2009
    Posts:
    45
    Just to post my sample code: No Errors but just cant see unitycontent...

    Also.. The commination still happens... can send messages to unity content....

    Weird... Only in flex application is this a problem.... PURE AS3 work perfect!

    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark"
    xmlns:mx="library://ns.adobe.com/flex/mx" implements="com.unity.IUnityContentHost" creationComplete="windowedapplication1_creationCompleteHandler(event)">

    <fx:Script>
    <![CDATA[
    import com.unity.UnityContentLoader;
    import com.unity.UnityLoaderParams;

    import mx.core.UIComponent;
    import mx.events.FlexEvent;

    private var unityContentLoader:UnityContentLoader;

    protected function windowedapplication1_creationCompleteHandler(event:FlexEvent):void
    {
    startLoad();
    }

    protected function startLoad():void
    {
    var params:UnityLoaderParams = new UnityLoaderParams(false,720,400,true);
    unityContentLoader = new UnityContentLoader("AS3Communication.swf", this, params, true);
    unityContentLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onUnityContentLoaderComplete);
    unityContentLoader.loadUnity();
    }

    private function onUnityContentLoaderComplete(event:Event):void
    {
    uix.addChild(unityContentLoader);
    unityContentLoader.unityContent.setContentHost(this);//Set this instance as the callback handler for unity.
    }

    //
    // IUnityContentHost - Handlers
    //

    //unityInitStart has to be implemented by whatever implements IUnityContenthost
    public function unityInitStart():void
    {
    //This is called when the content is loaded and the initialization of the unity engine is started.
    }

    //unityInitComplete has to be implemented by whatever implements IUnityContenthost
    public function unityInitComplete():void
    {
    //This is called when the unity engine is done initializing and the first level is loaded.

    //From this point on, you can use sendmessage to send over messages..in this case we send this instance, which is used by the send to flash script
    //to send over variables, use an anonymous object.
    var success:Boolean = unityContentLoader.unityContent.sendMessage("Main Camera","SetResponder",{responder:this});
    if(success){
    trace("successfully sent a message");
    }
    }

    public var unityObject:Object;
    public function unityHelloFunction(obj:Object):void
    {
    trace("unity script said hello : "+obj);
    unityObject = obj;
    }
    ]]>
    </fx:Script>

    <fx:Declarations>

    </fx:Declarations>

    <s:layout>
    <s:BasicLayout />
    </s:layout>

    <mx:UIComponent id="uix" width="100%" height="100%" />

    </s:Application>
     
  32. ccj

    ccj

    Joined:
    Jul 2, 2010
    Posts:
    18
    I have two question:
    1. how to get the attribute value in a Anonymous Object in c#
    2.how to sendmessage to flash ,I read the code, but do not quite understand

    FlashHelper.EmitAsm("SendToFlashScript$responder$['unityHelloFunction']({0})",this);

    How to use FlashHelper.EmitAsm to recive/send message,The official did not elaborate example
     
  33. laurent-clave

    laurent-clave

    Joined:
    Jul 18, 2011
    Posts:
    280
    Hello World !

    you have no other examples please?
     
  34. marty64

    marty64

    Joined:
    Dec 26, 2011
    Posts:
    7
    Hi!
    I have some problems trying to build this exemple : when I try it it Firefox, it tells me :"Fatal Error : Error: Stage3D Error : Error #3702: Context3D non disponible. (did you set a correct wmode?)
    at com.unity::UnityContent/onStage3DError()"

    I have a content debugger and the wmode set to direct.
    I'm not sure that I'm publishing the swf with the good version. I don't know how to set it (I'm building with FlashBuilder SDK: Flex 4.6)

    If someone could help me...
    Thanks in advance,
     
  35. drag0nsphere2

    drag0nsphere2

    Joined:
    Mar 18, 2010
    Posts:
    12
    Can someone explain how to use this to change the default loading picture and bar?

    thanks
     
  36. TheAssassin

    TheAssassin

    Joined:
    Jan 13, 2011
    Posts:
    51
    So how do I read the object that I get back in unity? I've tried just about everything I can find to read the data from it.
     
  37. hjupter

    hjupter

    Joined:
    Dec 23, 2011
    Posts:
    628
    Same here, I've tried everything I know and research about it but nothing seems to work... Please somebody help us with this
     
  38. ProtonOne

    ProtonOne

    Joined:
    Mar 8, 2008
    Posts:
    406
    This is how I am doing it.
    In ActionScript
    Code (csharp):
    1.  
    2. var msgId:int = 123;
    3. var msgString = "Hello World";
    4. unityContentLoader.unityContent.sendMessage( "FlashConnection", "OnFlashMessage", {id:msgId, msg:msgString} );
    FlashConnection is the name of the GameObject in Unity.
    OnFlashMessage is the name of the function that gameobject that will be called
    I am sending 2 parameters, an integer and a string (id and msg)

    In Unity
    Code (csharp):
    1. public class FlashConnection : MonoBehaviour {
    2.     public int idFromFlash = 0;
    3.     public string msgFromFlash = "";
    4.    
    5.     void OnFlashMessage( object o ){
    6. #if UNITY_FLASH
    7.         FlashHelper.EmitAsm("FlashConnection$msgFromFlash$ = {0}.msg;FlashConnection$idFromFlash$ = {0}.id;", o);
    8.         Debug.Log("Recieved from Flash: " + msgFromFlash + " " + idFromFlash );
    9. #endif
    10.     }
    11. }
    12.  
    This part seems strange, I would think since I have the object that I should be able to just grab data out of it without the EmitAsm, but I haven't found a way to avoid it. And storing the return values into public variables also seems a bit odd.
     
  39. hjupter

    hjupter

    Joined:
    Dec 23, 2011
    Posts:
    628
    Hey thx for the answer, I was already doing something like that but didnt know i could do it in one line

    FlashHelper.EmitAsm("SendToFlashScript$message$ = {0}.message", o);
    FlashHelper.EmitAsm("SendToFlashScript$chatName$ = {0}.name", o);
    Debug.Log("Message: "+message+" - name: "+chatName);

    But i was looking for a way to call a function within unity and send params without need to have everything on variables in the class
     
  40. marty64

    marty64

    Joined:
    Dec 26, 2011
    Posts:
    7
    How are you building your flash project? with Flash Builder? Which SDK do you use?
    I always have errors and I don't find why...

    "Fatal Error : Error: Stage3D Error : Error #3702: Context3D non disponible. (did you set a correct wmode?)
    at com.unity::UnityContent/onStage3DError()"

    Thank you in advance

    Martin
     
  41. ProtonOne

    ProtonOne

    Joined:
    Mar 8, 2008
    Posts:
    406
    I'm using http://www.flashdevelop.org/

    Didn't download anything but that, it installed some Flex library on its own during the install process.

    I've seen that Stage3D error when you try to open the swf file in a browser directly instead of using the html page to view it.
     
  42. marty64

    marty64

    Joined:
    Dec 26, 2011
    Posts:
    7
    Thank you a lot!
    I'm using Flash Builder, I will try with FlashDevelop!
     
  43. hjupter

    hjupter

    Joined:
    Dec 23, 2011
    Posts:
    628
    Flash Develop using the latest sdk 4.6 i think
     
  44. marty64

    marty64

    Joined:
    Dec 26, 2011
    Posts:
    7
    Ok ! It works in flash player!

    Thanks a lot for your help!
     
  45. tripknotix

    tripknotix

    Joined:
    Apr 21, 2011
    Posts:
    744
    I hope this helps everyone shave a few hours off of testing

    The following code works flawlessly to talk FROM unity3d TO flash

    FlashHelper.EmitAsm("SendToFlashScript$responder$['PlayerMove'](SendToFlashScript$playerTransform$.position.x)");

    SendToFlashScript is the class (SendToFlashScript.cs) ,
    $responder$ is the flash object,
    ['PlayerMove'] is the Function Name,
    (SendToFlashScript$playerTransform$ is the public variable called playerTransform,
    and i can directly call .position.x on it

    that is how you pass public variables from unity to flash

    i wont bother explaining how to set values directly into that line of code instead of variables, because it would just confuse beginners. that line of code above is already going to be a workout.
     
  46. rogerisland

    rogerisland

    Joined:
    Dec 23, 2011
    Posts:
    3
    Hello,

    I'm successfully setting and calling functions both ways with the methods described above but the one thing I haven't yet successfully cracked is what sort of collections are supported both ways without throwing cast errors?
    Trying to push an array of bytes (or chars... or anything in collection form..) from AS3 to Unity... not having any luck with AS3 Array.... Before I continue testing out other methods I just wondered if someone has "cracked" this one yet?

    Thanks!
    -Georg
     
  47. Democre

    Democre

    Joined:
    Mar 31, 2010
    Posts:
    345
    Could you post an example any way for us "beginners"?
     
  48. Mackey@ehsiplus.com

    Mackey@ehsiplus.com

    Joined:
    Jun 27, 2009
    Posts:
    45
    Hey Ralph... Any progress on how to use in a flex application?
     
  49. voidward

    voidward

    Joined:
    Jan 3, 2012
    Posts:
    8
    I'm having some problems compiling with flashbuilder, I'm not experienced with flashbuilder at all.
    I create a new actionscript project, add source folder as project folder, add unity swc file, swap main application file to preloader, set build version to 11.1.

    Project appears to build fine but all I get is an image that says "your custom screen" in the html with nothing else.

    What am I missing?
     
    Last edited: Jan 3, 2012
  50. Almog

    Almog

    Joined:
    Nov 20, 2011
    Posts:
    22
    Can you share you files, trying to understand this better and not sure how "SendToFlashScript.cs" should be