Unity integration
*****************

"UnityPage" embeds a game built with Unity as a WebGL app in a PsyNet
page. Unity suits experiments that need a game-like 2D or 3D
environment, physics, or components from the Unity Asset Store. PsyNet
sends parameters to the game, and the game reports events such as
collected objects back to PsyNet as page answers.

The "demos/experiments/unity_autoplay" demo embeds a simple game. The
player (yellow cylinder) collects objects (red and blue cubes) to gain
points:

   [image]A Unity 3D scene with a player and collectable objects

   [image]The score increases with each collected object

   [image]The game ends when the score reaches the goal


How PsyNet and Unity communicate
================================

   [image]

PsyNet puts the game parameters in the page's "contents". When the
game starts, Unity reads them. As the game proceeds, Unity submits
answers to PsyNet, for example each time the participant collects an
object. PsyNet can then send a new page with different parameters.
Consecutive pages with the same "session_id" update the running game
instead of reloading it: PsyNet updates "psynet.page" and triggers the
"pageUpdated" event. The game decides when it has finished and moves
the timeline forward.


The PsyNet side
===============

In the demo, each participant is assigned one gain at random: the
number of points per collected object. The goal is the score that ends
the game. Both are set at the top of "experiment.py":

   DEBUG = False
   GAINS = ["2", "3", "4"]  # Points for collecting an object; one condition per value
   GOAL = 3  # Once the score reaches this goal the game is finished

The page class sets the location of the Unity build and the size of
the game container:

   class UnityGamePage(UnityPage):
       def __init__(
           self,
           contents: dict,
           session_id: str,
           time_estimate: Optional[float] = None,
           **kwargs,
       ):
           super().__init__(
               title="Unity Game",
               resources="/static",
               contents=contents,
               session_id=session_id,
               debug=DEBUG,
               time_estimate=time_estimate,
               game_container_width="960px",
               game_container_height="600px",
               **kwargs,
           )

       def format_answer(self, raw_answer, **kwargs):
           logger.info("----------------- format answer -----------------")
           logger.info(raw_answer)
           return raw_answer

"resources" is the URL of the directory that contains the build, under
the experiment's "static" directory. PsyNet loads the build from
"<resources>/scripts/Build/WebGL.*". "debug" selects the debug page
described under Debugging the game.

The game runs as a static trial maker. Each trial shows one Unity
page, which passes the goal and gain to Unity as "contents":

   def show_trial(self, experiment, participant):
       gain = self.definition["gain"]
       goal = GOAL
       data = {
           "goal": goal,
           "gain": gain,
       }

       page = UnityGamePage(
           # Send this string to Unity
           contents=data,
           # We stay in the same session.
           session_id=SAME_SESSION_ID,
           time_estimate=1,
           bot_response={"reward": 50, "expire": True},
       )
       return page  # list_of_pages

When an answer contains ""expire": true", the trial maker's
"finalize_trial" records this in a participant variable, and
"prepare_trial" then ends the game:

   def prepare_trial(self, experiment, participant):
       if participant.var.has("expire"):  # Finish the game
           logger.info("Ending game")
           return None, "exit"
       return super().prepare_trial(experiment, participant)

The trial maker is an ordinary element of the timeline:

   class Exp(psynet.experiment.Experiment):
       label = "Unity autoplay demo"

       timeline = Timeline(
           MainConsent(),
           trial_maker,  # The Unity game
           InfoPage("You finished the experiment!", time_estimate=0),
       )


The Unity side
==============

The PsyNet API for Unity consists of two files, which the demo
provides in "UnityFiles/":

"JaveScriptUnity.jslib"
   A plugin that reads the participant and page identity from the
   PsyNet page and exchanges JSON data with it. Place it in the Unity
   project's "Plugins" folder and leave it unchanged:

      [image]

"WebRequestManager.cs"
   A script that sends requests to PsyNet and reports the results
   through the "onPsynetSyncResponse" event. Attach it to an empty
   game object in the scene:

      [image]

The C# snippets below come from the "GameManager" script of the Unity
project used to build the demo. The Unity project itself is not
included in the PsyNet repository.


Handling responses from PsyNet
------------------------------

Subscribe to "WebRequestManager.onPsynetSyncResponse" in "OnEnable":

   void OnEnable()
   {
       WebRequestManager.onPsynetSyncResponse += HandlePsynetSyncResult;
   }

The handler receives a "PsynetSyncResponse", whose "opCode" identifies
the request that it answers:

   private void HandlePsynetSyncResult(PsynetSyncResponse res)
   {
       int opcode = res.opCode;
       string data = res.data;
       switch (opcode)
       {
           case Constants.PAGE_SUBMITTTED:
               AfterPageSubmitted();
               break;
           case Constants.PAGE_UPDATED:
               AfterPageUpdate(data);
               break;
           case Constants.PAGE_INIT:
               StartCoroutine(WebRequestManager.instance.GetPage(Constants.PAGE_UPDATED));
               break;
           case Constants.PAGE_ERROR:
               terminateGame.SetActive(true);
               break;
       }
   }


Starting the game
-----------------

"Start()" calls "WebRequestManager.Init()", which fetches the
participant and page identity. Requests to PsyNet are asynchronous, so
they run as coroutines and report back through the handler:

   void Start()
   {
       StartCoroutine(WebRequestManager.instance.Init(Constants.PAGE_INIT));
   }

When "Init()" completes, the handler calls "GetPage()" to fetch the
page contents. Game logic that depends on the parameters should start
only in "AfterPageUpdate(data)", once the contents have arrived.


Reading parameters from PsyNet
------------------------------

"AfterPageUpdate" parses the page as JSON. The "Ucontents" class in
the "Settings" script must match the "contents" dictionary in
"experiment.py" by name and type:

   public class Ucontents
   {
       public int goal = 0;
       public int gain = 0;
   }

"Ucontents" is part of "DashboardJson", which does not need changing:

   [Serializable]
   public class DashboardJson
   {
       public Uattributes attributes;
       public Ucontents contents;
   }

"GameManager" parses the page into a "DashboardJson" object and reads
the parameters:

   public DashboardJson dashboardJson = new DashboardJson();

   // In AfterPageUpdate
   dashboardJson = JsonUtility.FromJson<DashboardJson>(jsonData);
   m_Gain = dashboardJson.contents.gain;
   m_Goal = dashboardJson.contents.goal;


Sending answers to PsyNet
-------------------------

The "Answer" class in the "Settings" script defines the answer that
Unity submits. "expire" tells PsyNet that the game has finished:

   public class Answer
   {
       public int score, reward;
       public double timeElapsed = 0;
       public bool expire = false;
       public string answer = "This is place holder for comments";
   }

In the demo, "ScoreUp()" runs each time the player collects an object
and submits the answer with "SubmitPage()":

   public void ScoreUp()
   {
       m_Score += m_Gain;
       score.text = "Score: " + m_Score;
       if (m_Score > m_Goal)
       {
           answer.expire = true;
           terminateGame.SetActive(true);
       }
       answer.score = m_Score;
       answer.reward = m_Gain;
       StartCoroutine(WebRequestManager.instance.SubmitPage(answer, metadata, Constants.PAGE_SUBMITTTED));
   }

After a submission, PsyNet may send a new page, for example to change
the game's parameters. "AfterPageSubmitted()" fetches it:

   public void AfterPageSubmitted()
   {
       StartCoroutine(WebRequestManager.instance.GetPage(Constants.PAGE_UPDATED));
   }


Building and running the game
=============================

The demo was built with Unity 2020.3, using the free Unity Personal
license.


Debugging the game
------------------

The game can run inside the Unity editor while it communicates with a
local PsyNet experiment. Set "DEBUG = True" in "experiment.py" and run
"psynet debug local". After the consent page, PsyNet shows a debug
page with the game parameters instead of the game:

   [image]

Then run the game in the Unity editor, where "WebRequestManager"
connects to "http://localhost:5000". Running the game in Unity without
a PsyNet experiment produces errors such as these:

   [image]


Building for WebGL
------------------

1. In Unity, open **File > Build Settings** and select **WebGL**:

      [image]

2. Open **Player Settings**, and under **Publishing Settings** set
   **Compression Format** to **Disabled**:

      [image]

3. Name the app "WebGL", because PsyNet loads files named "WebGL.*".

4. Click **Build And Run**. Unity opens the build in a browser, where
   it reports an error because PsyNet is not running.

5. Check that the "Build" folder in the WebGL output contains these
   files:

      [image]

6. Copy the "Build" and "TemplateData" folders into the PsyNet
   experiment's "static/scripts/" directory.

7. Set "DEBUG = False" in "experiment.py".

Run "psynet debug local" from the experiment directory. After the
consent page, the game runs embedded in the page, and the timeline
continues when the game ends.
