Hi everyone. In this exercise we are going to pass data from UNITY 3D to an ASP.NET site. Eventually the site can connect and store data in SQL Server.
Unity 3D – Setup
1. Create a new GameObject, name it Scripts and assign with it a C# Script (LogData.cs)
2. For testing purposes we are going to create a new button in the OnGUI() method which will pass parameters to ASP.NET site upon click. Here is the whole implementation of the LogData class.
public class LogData : MonoBehaviour { //The URL to the server - In our case localhost with port number 2475 private string url = "http://localhost:2475/"; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void OnGUI() { // Make a background box GUI.Box(new Rect(10,10,100,90), "Loader Menu"); // Make the first button. if(GUI.Button(new Rect(20,40,80,20), "Connect")) { //when the button is clicked //setup url to the ASP.NET webpage that is going to be called string customUrl = url+ "LogUserScore.aspx"; //setup a form WWWForm form = new WWWForm(); //Setup the paramaters form.AddField("UserID", "47"); form.AddField("Score", "100"); //Call the server WWW www = new WWW(customUrl, form); StartCoroutine(WaitForRequest(www)); } } IEnumerator WaitForRequest(WWW www) { yield return www; // check for errors if (www.error == null) { //write data returned from ASP.NET Debug.Log(www.text); } else { Debug.Log("WWW Error: "+ www.error); } } }
ASP.NET – Setup
1. Create a new ASP.NET web application and create a Web Form with name LogUserScore.aspx
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace UnityConnectASP.NET { public partial class LogUserScore : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Page.Request.HttpMethod == "POST") { //read paramaters string UserID = (Request.Form["UserID"]); string Score = (Request.Form["Score"]); //store data into MS SQL Database //---Insert into database etc etc--- //load total score from database //Using a dummy value 200 string totalScore = "200"; //Return data to Unity, such as total score Response.Clear(); Response.ContentType = "application/text; charset=utf-8"; Response.Write("Total Score: " + totalScore); Response.End(); } } } }
2. Optional: To allow your game to be played from any domain, in the root folder of the site (where the web.config is located), create a crossdomain.xml file and write:
<?xml version="1.0"?> <cross-domain-policy> <allow-access-from domain="*"/> </cross-domain-policy>
Testing the Code
1. Connect Button is clicked
3. Data returned to UNITY