Search code examples
c#androideclipseunity-game-engine

Access Unity variables in eclipse


Is it possible to access variables (for example a highscore) from a Unity game in Eclipse?

The variables are stored in unity scripts like this:

using Assets.Scripts.Events;
using Assets.Scripts.Utils;
using UnityEngine;

namespace Assets.Scripts
{
    public class ScoreManager : CommandMonoBehaviour
    {
        public int Score;

        public void Start()
        {
            Subscribe(GameEvents.BasketGotMovingObject, OnBasketGotMovingObject);
        }

        private void OnBasketGotMovingObject(GameEventArgs<MovingObject> args)
        {
            Score = Mathf.Max(0, Score + args.Value.BonusPoints);
            GameEvents.ScoreUpdated.Publish(new GameEventArgs<int>(Score));
        }
    }
}

The project has been exported to a "Google Android Project" through the Unity IDE.

The onCreate Function in the exported project looks like this:

protected void onCreate (Bundle savedInstanceState)
{
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    super.onCreate(savedInstanceState);
    
    getWindow().takeSurface(null);
    setTheme(android.R.style.Theme_NoTitleBar_Fullscreen);
    getWindow().setFormat(PixelFormat.RGB_565);

    mUnityPlayer = new UnityPlayer(this);
    if (mUnityPlayer.getSettings ().getBoolean ("hide_status_bar", true))
        getWindow ().setFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN,
                               WindowManager.LayoutParams.FLAG_FULLSCREEN);

    int glesMode = mUnityPlayer.getSettings().getInt("gles_mode", 1);
    boolean trueColor8888 = false;
    mUnityPlayer.init(glesMode, trueColor8888);

    View playerView = mUnityPlayer.getView();
    setContentView(playerView);
    playerView.requestFocus();
}

There is only a "UnityPlayer". How can I access the script variables like int Score?


Solution

  • Assuming that you have opened the solution in eclipse, make sure you get the component of the game object the script is attached to. You could use

    var scoreManager = GameObject.FindOnbjectOfType(typeof(ScoreManager)) as ScoreManager;
    

    If you don't know the object to which the ScoreManager script belongs to. If you do know the object to which te script belongs to you could use the following (replace obj with the actual name)

    var scoreManager = obj.GetComponent<ScoreManager>():
    

    And from there you could do

    scoreManager.Score
    

    I am also assuming the class you are deriving ScoreManager from at some point derives from MonoBehaviour which is the required class to attach scripts to game objects in the scene.

    Hope this helps