Caching Variables in Unity

Today I was reviewing some Unity code and I got puzzled by this statement

private Rigidbody _cacheRigidbody;
void Start () { 
      // Cache reference to rigidbody to improve performance
      _cacheRigidbody = rigidbody;
  }

At first glance, I couldn’t understand what is the scope of declaring a cache variable when it is just referencing the same memory space.

Well…according to the Unity it is faster to cache the reference to the object on start() or awake() method, rather than use the GetComponent<Rigidbody>() or GameObject.Find() everytime you want to use a component.

Reduce GetComponent Calls

Using GetComponent or built-in component accessors can have a noticeable overhead. You can avoid this by getting a reference to the component once and assigning it to a variable (sometimes referred to as “caching” the reference). For example, if you are using something like:-

 
function Update () {
    transform.Translate(0, 1, 0);
}

…you would get better performance by changing it to:-

 
var myTransform : Transform;

function Awake () {
   myTransform = transform;
}

function Update () {
    myTransform.Translate(0, 1, 0);
}

Well that make sense now! 🙂

Advertisements

Unity 3D: Spectator Camera Like in Call of Duty

Like the title says we are going to create a spectator camera view. For those of you who don’t know what I’m taking about just watch this video and understand the goooodness 🙂

Ok let’s start

1) Open Unity (Duh…)

2) Create a C# Script File and name it Spectator.cs

3) Paste the following code

using UnityEngine;
using System.Collections;

public class Spectator : MonoBehaviour {

 //initial speed
 public int speed =20;

 // Use this for initialization
 void Start () {
 
 }
 
 // Update is called once per frame
 void Update () {

 //press shift to move faster
 if(Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
 {
    speed = 40; 
 
 }
 else
 {
    //if shift is not pressed, reset to default speed
    speed =20; 
 }
 //For the following 'if statements' don't include 'else if', so that the user can press multiple buttons at the same time
 //move camera to the left
 if(Input.GetKey(KeyCode.A))
 {
    transform.position = transform.position + Camera.main.transform.right *-1 * speed * Time.deltaTime;
 }

 //move camera backwards
 if(Input.GetKey(KeyCode.S))
 {
    transform.position = transform.position + Camera.main.transform.forward *-1 * speed * Time.deltaTime;
 
 }
 //move camera to the right
 if(Input.GetKey(KeyCode.D))
 {
    transform.position = transform.position + Camera.main.transform.right * speed * Time.deltaTime;
 
 }
 //move camera forward
 if(Input.GetKey(KeyCode.W))
 {
 
    transform.position = transform.position + Camera.main.transform.forward * speed * Time.deltaTime;
 }
 //move camera upwards
 if(Input.GetKey(KeyCode.E))
 {
    transform.position = transform.position + Camera.main.transform.up * speed * Time.deltaTime;
 }
 //move camera downwards
 if(Input.GetKey(KeyCode.Q))
 {
    transform.position = transform.position + Camera.main.transform.up * -1 *speed * Time.deltaTime;
 }

 }
}

4) Attach the Spectator.cs to the main camera

5) Attach the Mouse Look Script (comes as a ready component with Unity) to the main camera

Final Result:

Spectator

Write data from Unity 3D to SQL Server using ASP.NET

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)

Step 1

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

Connect Unity Button

2. Data Passed to ASP.NET
Asp.net unity

3. Data returned to UNITY

ASP.NET returned data