I am trying to create an interface that users can code at runtime Unity. It is tough to find resource about it.
I added MoonSharp as a code editor to Unity Input Field. Here is my basic UI
Now the question is that how can the user create a GameObject (eg Box) using a Prefab and set its coordinates? (using MoonSharp)
First Scripts:
using UnityEngine;
using TMPro;
using UnityEngine.UI;
public class MainGame : MonoBehaviour
{
MyScript testScript;
public TMP_InputField tmpInput;
public Toggle togInput1;
public Toggle togInput2;
public Toggle togOutput1;
public Toggle togOutput2;
private void Start()
{
string tmpString = @"
function Update()
if Input1 then
Output1 = true
else
Output1 = false;
end
if Input2 then
Output2 = true
else
Output2 = false;
end
end
";
testScript = tmpInput.GetComponentInChildren<MyScript>();
testScript.InitScript(tmpString);
tmpInput.text = testScript.MyString;
}
private void Update()
{
//testScript.RunScript();
}
public void UpdateScript()
{
string tmpString = tmpInput.text;
testScript.InitScript(tmpString);
testScript.Input1 = togInput1.isOn;
testScript.Input2 = togInput2.isOn;
testScript.RunScript();
togOutput1.isOn = testScript.Output1;
togOutput2.isOn = testScript.Output2;
}
}
Second Script:
using System.IO;
using UnityEngine;
using MoonSharp.Interpreter;
public class MyScript : MonoBehaviour
{
public bool Input1;
public bool Input2;
public bool Output1;
public bool Output2;
public string MyString;
Script script;
public void InitScript(string ScriptText)
{
script = new Script();
MyString = ScriptText;
script.DoString(MyString);
}
public void RunScript()
{
script.Globals["Input1"] = Input1;
script.Globals["Input2"] = Input2;
script.Globals["Output1"] = Output1;
script.Globals["Output2"] = Output2;
DynValue dynValue = script.Call(script.Globals["Update"]);
Output1 = script.Globals.Get("Output1").CastToBool();
Output2 = script.Globals.Get("Output2").CastToBool();
}
//public void InitScriptFromFile(string FileName)
//{
// script = new Script();
// StreamReader streamReader = new StreamReader(FileName);
// string tmpString = streamReader.ReadToEnd();
// streamReader.Close();
// script.DoString(tmpString);
//}
}