Unity - Scripts

From NoskeWiki
Jump to: navigation, search

About Unity Scripts

NOTE: This page is a daughter page of: Unity


Unity is cross-platform game engine and authoring tool for creating 3D video games (see official website). Scripting is an essential part of unity as it defines your games behavior. Unity scripts can be written in UnityScript (JavaScript), C# or Boo. UnityScript is Unity's (proprietary) version of JavaScript and is the easiest to learn, since it has simple/minimalist syntax and most of the official tutorials are in UnityScript. If you want to make a serious program, however, C# is what I use and recommended as it's got strong typecasting and your options (and ability to import libraries) are more versatile. Which language is the best is largely personal preference, but most people advise against Boo. A useful poll of >300 users showed ~32% use C#, 30% use JavaScript, ~29% use C# only ~4% use Boo and ~30 code using both C# and JavaScript (which I found interesting!).


Setting up Autocomplete in MonoDevelop

Be default, Unity has it's own little code editor called "Unitron", but unfortunately this doesn't have autocomplete and isn't so great. If you are doing lots of development, you should consider setting Unity to use MonoDevelop - a more featured code editor which comes with Unity v3 (see: "getting started with monodevelop"). To do this go: menubar >> Preferences, then change "External Script Editor" to MonoDevelop (browse to it in the same Applications folder as Unity). Apply this, then go Assets >> Sync with MonoDevelop. When you double click any code in your Projects window it should now open in MonoDevelop, meaning you can make use of code folding and autocomplete.


Code Snippiets

CameraFly

The following code can be attached to a camera to make it free fly. Note that any movement you provide should be multipled by Time.deltaTime... without doing this the speed of your movement will vary depending on frames per second (meaning, you'll move really quickly on a fast computer). By default, every unity project has a certain number of default keys mapped... for example the w,s,a,d or arrow keys = "Vertical" and "Horizontal" movement, space = "Jump", and changes in the mouse position are mapped too. To see and/or change these mapping you can go: Edit >> Project Settings >> Input, then look at/expand and change the various "Axes" in the Inspector Window.

//-- "CameraFly.js" -- (from andrewnoske.com)
//--
//-- Add this simple script to your main camera to enable it to free fly in 3D using the mouse to rotate
//-- left/right/up/down and the w,s,a,d keys (or arrow keys) to move forward/back/strafe-left/right.
//-- The same code can be adapted to fly/control a plane too.
 
var moveSpeed = 5.0;        // Speed at which object moves.
var rotateSpeed = 2;        // Speed at which object turns.
 
function Update() {
 
  var moveZ = Input.GetAxis("Vertical")   * Time.deltaTime * moveSpeed;  // By default: [w]/[s] key for forward/back.
  var moveX = Input.GetAxis("Horizontal") * Time.deltaTime * moveSpeed;  // By default: [e]/[d] key for strafe right/left.
  gameObject.transform.Translate(moveX, 0, moveZ);    // Move object by this amount in x and z (relative to faced direction).
 
  var rotateAboutX = -Input.GetAxis("Mouse Y") * Time.deltaTime * rotateSpeed;  // Mouse movement up/down.
  var rotateAboutY = Input.GetAxis("Mouse X")  * Time.deltaTime * rotateSpeed;  // Mouse movement right/left.
  gameObject.transform.Rotate(rotateAboutX, rotateAboutY, 0);   // Rotate the object by this amount around X and Y axes.
  gameObject.transform.rotation.z = 0;              // Otherwise the camera will tilt.
}


FireProjectile

The next piece of code can be useful to fire projectiles from a gun.

//-- "FireProjectile.js" -- (from: andrewnoske.com)
//-- 
//-- Add this to your gun, player or camera object to fire projectiles while the user 
//-- presses fire (by default: left mouse or Ctrl key). Make sure you setup the "projectile":
//-- I recommend you use a Prefab and by adding a Rigidbody Component to your prefab
//-- (with gravity applied) it will fall in an nice arc.
 
var projectile : GameObject;     // The object you want to fire.
var projectileForce = 10;        // The force at which the object is fired (units/sec).
var fireRate = 0.5;              // The minimum time (in seconds) between shots.
var secTillProjectileGone = 10;  // Seconds till the projectile automatically disappears (removes itself).
private var nextFire = 0.0;      // Tracks when the next shot can be fired (in secs after the game started).
 
function Update()
{
  if(Input.GetButton("Fire1") && Time.time > nextFire)   // If [Ctrl] or left mouse clicked and ready to fire:
  {
    // Instantiate the projectile at the position and rotation of this transform:
    var clone = Instantiate(projectile, transform.position, transform.rotation);
 
    // Give the cloned object and instand velocity along the objects Z axis:
    clone.velocity = transform.TransformDirection (Vector3.forward * projectileForce);    
    clone.name = "missile";                              // Rename the clone to "missile".
    Destroy(clone.gameObject,secTillProjectileGone);    // Will remove this projectile after the specified seconds.
 
    // Update the time (in seconds) when the user can fire again:
    nextFire = Time.time + fireRate;        
  }
}


Important Lines

Screen.showCursor = true; 
Screen.lockCursor = false; 


Lists and ArrayLists

While making a dynamic array in UnityScript is fairly easy, it's a little tricker in Unity C#. To make a dynamic array in C# there are two options: "List" and "ArrayList" (both by .NET). Although the majority of functions are the same for both, the ArrayList, part of System.Collection, is quite unique in that it doesn't require you to specify a type. From what I've read, List is the better choice as it's faster and occupies less memory (see: "ArrayLists versus Lists"). List<T> requires you to specify a type, and is part of the "System.Collections.Generic", so you must type: "using System.Collections.Generic;" at the top of the file. The code below shows how to initialize and setup arrays:

string[] playerArrStatic = new string[5];        // Static array with 5 elements (cannot be resized later).
ArrayList playersArrayList = new ArrayList();    // Initializes an array list... notice no type is specified.
playersArrayList("one");                         // Adds an element to this array list.
 
using System.Collections.Generic;
List<string> playersList = new List<string>();   // Initializes an empty list of strings.
playersList.Add("one");
playersList.Add("two");
playersList.Add("three");
playersList.RemoveAt(1);                         // Will remove "two".
for(int i=0; i<playersList.Count; i++)
  Debug.Log(playersList[i]);                     // Will print "one" then "two".
playersList.Clear();                             // Clears the remaining two elements


See also: Unity Coding: Arrays, Hashtables and Dictionaries explained

Links