Let's look at the class we created in this chapter and break it down into easily digestible parts.
Firstly, here is what a basic Unity C# class looks like, broken down to its bare essentials:
using UnityEngine; namespace HoloLensBeginnersGuide { public class LaunchBall : MonoBehaviour { //member variables and properties belong here. void Start() { } void Update() { } } }
Now, we will want to compare that to LauchBall.cs. A Unity C# class consists of the following:
- Using declarations: The using directive is primarily used for including namespaces in the application. Defaults in Unity are UnityEngine and System.Collections:
using UnityEngine; using System.Collections;
- Namespace: Namespace definitions are designed to prove a way to keep names separate from one another; this helps simplify reusing code later:
namespace HoloLensBeginnersGuide {
- Class declaration: The name of this LaunchBall class, which will normally derive from MonoBehaviour in Unity:
public class LaunchBall : MonoBehaviour {
- Member variables: These are the variables or data storage for the class; we will talk about this subject very soon:
// Member Variables public Vector3 launchBallHome = new Vector3(0.0f, 0.0f, 4.0f); public float lbSpeed; public bool checkLBToggle = true; private Color lbColor; Renderer rend; bool lbJump;
- Class methods: The actions this class can perform:
//Class Methods void TeleportBall() { if (transform.position.y >= 2) { transform.position = new Vector3(transform.position.x, -1, transform.position.z); } } void ChangeColor() { float redColor = 0.1f; lbColor.r = redColor; lbColor.g = Random.Range(0, 1f); lbColor.b = Random.Range(0, 1f); } void LaunchBallJump() { transform.Translate(Vector3.up * lbSpeed * Time.deltaTime); } void CheckLB() { int i = Random.Range(0, 1000); if(i < 997) { lbJump = true; } else { lbJump = false; transform.position = launchBallHome; } }
Here are our MonoBehaviour-specific methods Start() and Update() at work:
void Start() { gameObject.transform.position = launchBallHome; lbSpeed = 0.1f; lbColor = new Color(0.1f, 0.2f, 0.5f); rend = gameObject.GetComponent<Renderer>(); lbJump = true; } void Update () { if (lbJump) { TeleportBall(); ChangeColor(); rend.material.color = lbColor; LaunchBallJump(); } if (checkLBToggle) { CheckLB(); } }
- Statements and expressions: This is where a good deal of the work happens. All statements and expressions must end with a semicolon:
gameObject.transform.position = launchBallHome; transform.Translate(Vector3.up * lbSpeed * Time.deltaTime);