Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

[Windows Phone 8] Assign action to button press which switches to UI thread.

Discussion in 'Windows' started by fendorio, Apr 15, 2014.

  1. fendorio

    fendorio

    Joined:
    Mar 8, 2014
    Posts:
    19
    Hi there, I'm trying to implement IAP for my windows phone game.

    In a unity script I define an Action<string,bool> Foo , and in the UI thread (mainpage.xaml) I want to assign that action a method defined in the UI thread.

    Something like so:

    UnityScript:

    public event Action<string,bool> Foo;

    void SomeGUIMethod()
    {
    if ( A button is clicked)
    {
    Foo("hello",true); //What I want to happen is for this to 'fire' off to the UI thread for the assigned method to be executed.
    }
    }

    Sadly Foo is always null when I return to the Unity thread.

    In my UI thread:

    MainPage.xaml.cs

    void Unity_Loaded()
    {

    var script = UnityEngine.Object.FindObjectOfType<MyScript>();

    script.Foo += SomeMethod; //I assign the method an eventhandler
    }

    void Foo(string arg1, bool arg2)
    {
    //Do stuff
    }

    So yeah, what I intend to happen is after Unity_Loaded is executed, the action is assigned a method, and once it's called it'll fire off to the UI thread to do it's stuff, sadly as soon as I get back to the Unity thread the Action is null.

    Can anyone give any insight into this? Has been bugging me all afternoon!
     
  2. Aurimas-Cernius

    Aurimas-Cernius

    Unity Technologies

    Joined:
    Jul 31, 2013
    Posts:
    3,640
  3. Tautvydas-Zilys

    Tautvydas-Zilys

    Unity Technologies

    Joined:
    Jul 25, 2013
    Posts:
    10,505
    What you're doing seems correct. Do you happen to have more than one object with that script attached in the scene? UnityEngine.Object.FindObjectOfType<MyScript>() will return the very first one in that case. Making the event static might help then.
     
  4. fendorio

    fendorio

    Joined:
    Mar 8, 2014
    Posts:
    19
    HI there, thank you both for the replies!

    What I believe I was doing was was using the '+=' operator to assign rather than the assignment operator '='.

    The fix I worked up was creating a static class with two Actions: InvokeUIThread and InvokeUnityThread,

    Then in Unity_Loaded I assigned them public methods defined in the mainpage.xaml:

    InvokeUIThread = Foo;

    public void Foo(Action action)
    {
    Dispatcher.BeginInvoke( () =>
    {
    action();
    }

    And likewise with the InvokeUnity Action, but replacing Dispatcher.BeginInvoke with UnityApp.BeginInvoke.

    Thanks again
     
  5. bleater

    bleater

    Joined:
    Apr 19, 2012
    Posts:
    24