embed:tutorial2
文書の過去の版を表示しています。
目次
m
より実践的なソース組み込み
Unityのプロジェクトを新規作成
2Dにする理由はないですし、3Dで問題ないです。
Miniscriptのソースコード用意
オブジェクト準備
実装
以下のソースをCubeにアタッチしてみてください。
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Miniscript;
using TMPro;
public class ScriptMover : MonoBehaviour
{
public TMP_Text tmp_stage_frame;
private string loadText;
public TextAsset textAsset;
public Interpreter interpreter;
public string globalVarName="";
private int frame=0;
void Start(){
loadText = textAsset.text;
interpreter = new Interpreter();
interpreter.hostData = this;
//出力
//標準出力先の指定
interpreter.standardOutput = (string s,bool t) => Debug.Log(s);
interpreter.implicitOutput = (string s,bool t) => Debug.Log($"implicit {s}");
interpreter.errorOutput = (string s,bool t) => {
//エラーログ出力。(Unity側のエラーとして動く)
Debug.LogError(s);
};
//新関数定義
Intrinsic f;
//ボスの座標を一次保存、次のエリアで切替できるようにする
f = Intrinsic.Create("change");
f.AddParam("str", "");
f.code = (context, partialResult) => {
var rs = context.interpreter.hostData as ScriptMover;
rs.tmp_stage_frame.text = context.GetVar("str").ToString();
return Intrinsic.Result.Null;
};
RunScript(loadText);
}
public void RunScript(string sourceCode) {
string extraSource = "ship.reset = function(); self.x=0; self.y=0; self.rot=0;end function\n";
interpreter.Reset(extraSource+sourceCode);
interpreter.Compile();
ValMap data = new ValMap();
data["cnt"]=new ValNumber(0);
data["x"] = new ValNumber(this.transform.localRotation.x);
data["y"] = new ValNumber(this.transform.localRotation.y);
data["rot"] = new ValNumber(this.transform.localRotation.z);
interpreter.SetGlobalValue(globalVarName, data);
}
void Update(){
try{
//interpreter.Restart();
if( !interpreter.Running())
interpreter.Restart();
interpreter.RunUntilDone(1.0f);
}catch (MiniscriptException err) {
#if UNITY_EDITOR
Debug.Log("Script error: " + err.Description());
#endif
}
UpdateFromScript();
}
public void UpdateFromScript() {
ValMap data = null;
try {
data = interpreter.GetGlobalValue(globalVarName) as ValMap;
} catch (UndefinedIdentifierException) {
Debug.LogWarning(globalVarName + " not found in global context.");
}
if (data == null) return;
Transform t = transform;
Vector3 pos = t.localPosition;
float xx,yy;
Value xval = data["x"];
Value yval = data["y"];
Value rotVal = data["rot"];
if (rotVal != null) t.localRotation = Quaternion.Euler(xval.FloatValue(), yval.FloatValue(), (float)rotVal.FloatValue());
Value cntval=data["cnt"];
frame=cntval.IntValue();
}
}
終わったら画面UIのテキストをCubeの枠にドラッグ&ドロップしておいてください。
Miniscript言語で書いたソースコード用意
以下のテキストを用意して、ScriptMoverクラスのテキストに登録しておいてください。
serif=["This is Miniscript's test.","This is sample."] ship.x=ship.x+1 ship.rot +=2 ship.cnt+=1 change(serif[(ship.cnt/600)%2])
動かしてみましょう
embed/tutorial2.1673872128.txt.gz · 最終更新: 2023/01/16 21:28 by machiaworx


