Tuesday, April 23, 2013

C# versions of the Lynda.com Unity course scripts

I recently completed the Unity 3.5 essentials course on Lynda.com in order to get past the limitations of the drag and drop features.  The course uses Javascript, but I prefer C#.  I'm putting my converted code here for anyone else that would like it. 

I use the internal instead of private access modifier as this will hide the variable from the inspector, but still make it available to other classes.


Final RotationController class.

using UnityEngine;
using System.Collections;

public class RotationController : MonoBehaviour {
public bool RotationState = true;
public float RotationSpeed = 20f;
internal float initialSpeed;
// Use this for initialization
void Start () {
initialSpeed = RotationSpeed;
}
// Update is called once per frame
void Update ()
{
if(RotationState && RotationSpeed > 5f)
{
transform.Rotate(0, RotationSpeed * Time.deltaTime, 0);
}
}
void OnMouseDown()
{
RotationState = !RotationState;
RotationSpeed -= 0.5f;
if (RotationSpeed < 0)
RotationSpeed = initialSpeed;
}
}

Final ReportDistance Class

using UnityEngine;
using System.Collections;

public class ReportDistance : MonoBehaviour {
public Transform targetObject;

// Use this for initialization
void Start () 
{
targetObject = GameObject.Find("First Person Controller").transform;
}
// Update is called once per frame
void Update () {
if (targetObject)
{
float distance = Vector3.Distance(targetObject.position, this.transform.position);
//Debug.Log("Distance to target object: " + distance);
}
}
}

Final RayCaster Class

using UnityEngine;
using System.Collections;

public class RayCaster : MonoBehaviour {
RaycastHit hit; //holds properties of detected object

// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () 
{
if(Physics.Raycast(transform.position, transform.forward, out hit, 10))
Debug.Log("There is a " + hit.transform.name + " something in front of the object!");
else Debug.Log("There is nothing within 10 metres!");
}
}