2016年11月26日

Unity C#とMoonSharpの実験

割と簡単なコードで、MoonSharpとC#とのコルーチンで処理をピンポンさせつつ合間にちゃんとUnityの他の処理も実行させることが出来ました。これで、ゲームのシナリオ進行やイベント演出等をMoonSharpで直列で書きつつ具体的な処理についてはUnityでまったく制約なく書くことが出来そうです。 MoonSharpはC#で書かれたLuaライクなスクリプト言語で、一部の機能を除いてLuaととてもよく似ています。APIもC#の機能を活用しつつLuaのAPIから類推出来る部分も多いので、Luaを使ったことがあるならすぐに使えるようになると思います。


    using UnityEngine;
    using System.Collections;
    using MoonSharp.Interpreter;

    public class NewBehaviourScript : MonoBehaviour {
      // Use this for initialization
      void Start () {
        StartCoroutine(CSharpFunc());
      }

      IEnumerator CSharpFunc()
      {
        string src = @"
        function wait(i)
          coroutine.yield(i)
        end
        return function ()
          for i=1,10 do
            wait(i)
          end
        end  
        --coroutine.yieldは関数の中からでも呼べる。
        ";
        Script s = new Script();
        DynValue luafunc = s.DoString(src);
        DynValue cr = s.CreateCoroutine(luafunc);//C#からでもコルーチンを作れる
        while (true)
        {
          DynValue x = cr.Coroutine.Resume();
          if (cr.Coroutine.State == CoroutineState.Dead) break;
          Debug.Log(x);
          yield return null;
        }
      }

      // Update is called once per frame
      int count = 0;
      void Update () {
        count++;
        if (count<15)
        {
          Debug.Log("Update");
        }
        //Updateで全部流れてしまわないように15回だけ表示している。
      }
    }
    //出力に数字とUpdateが入り交じり、C#のCSharpFunc、MoonSharpのコルーチン、Updateがそれぞれ呼ばれてるのが分かる。
posted by NTak_Indies at 08:19| Comment(2) | TrackBack(0) | 日記
この記事へのコメント
コメントを書く
お名前:

メールアドレス:

ホームページアドレス:

コメント:

この記事へのトラックバックURL
http://blog.sakura.ne.jp/tb/177814753

この記事へのトラックバック