Calling Unity Code from Android
October 9, 2012 by Chris Johnson. Filed under
Deprecated: Creation of dynamic property WP_Term::$cat_ID is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 378
Deprecated: Creation of dynamic property WP_Term::$category_count is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 379
Deprecated: Creation of dynamic property WP_Term::$category_description is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 380
Deprecated: Creation of dynamic property WP_Term::$cat_name is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 381
Deprecated: Creation of dynamic property WP_Term::$category_nicename is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 382
Deprecated: Creation of dynamic property WP_Term::$category_parent is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 383
Deprecated: Creation of dynamic property WP_Term::$cat_ID is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 378
Deprecated: Creation of dynamic property WP_Term::$category_count is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 379
Deprecated: Creation of dynamic property WP_Term::$category_description is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 380
Deprecated: Creation of dynamic property WP_Term::$cat_name is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 381
Deprecated: Creation of dynamic property WP_Term::$category_nicename is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 382
Deprecated: Creation of dynamic property WP_Term::$category_parent is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 383
public, reader animated.
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.