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.