teaching machines

Calling Unity Code from Android

Previously I integrated Android with Unity by having Unity poll methods I defined in Java. We used reflection to pull out the activity object and invoked my custom methods on it.

Today I looked into going in reverse: can I call Unity methods from Android? It turns out to be pretty simple. I first made a little controller script that I attached to a Sphere game object named Ball:

using UnityEngine;
using System.Collections;

public class BallController : MonoBehaviour {
  private const float JUMP = 1.0f;

  public void Left() {
    transform.Translate(-JUMP, 0.0f, 0.0f);
  }

  void Right() {
    transform.Translate(JUMP, 0.0f, 0.0f);
  }

  void Up() {
    transform.Translate(0.0f, JUMP, 0.0f);
  }

  void Down() {
    transform.Translate(0.0f, -JUMP, 0.0f);
  }
}

In my custom Android Activity, I can invoke one of these methods like so:

UnityPlayer.UnitySendMessage("Ball", "Left", "");

The first parameter is the game object whose method I want to call. The second is the method I want to call on that game object. The last parameter in that call is for parameters to the method. There are none for Left, so I left it blank. That’s all there was to it.

Comments

  1. aqua says:

    i want to do mUnityPlayer = new UnityPlayer(this) in android java code, when i run app error shown up : : Caused by: java.lang.ExceptionInInitializerError

    if i cannot call unityplayer function in java code
    pls help…
    graceful
    aqua

Leave a Reply

Your email address will not be published. Required fields are marked *