Your browser (Internet Explorer 6) is out of date. It has known security flaws and may not display all features of this and other websites. Learn how to update your browser.
X

FAQ

A small FAQ with the mos often questions about Unity I’m asked. It’s focused on programming and the language used is C#.

1. Main links about Unity?

Official Forum

Questions and Answers, another official resource about Unity. Faster than the forum to get a solution.

Unify Community, wiki is very usefull, specially about Scripts and Shaders.

UnityArtist, Another forum, not as good as the official.

UnityMagazine, digital magazine made by some members of the official forum. It’s not free, but it’s a good resource about Unity.

LearnUnity, Will Goldstone’ blog, author of the first book about Unity Development.

Infinite Unity3D, another excelent blog, with a lot of tutorials, links, videos, etc.

Burgzercade, yet another blog, excelent by the way. Great videos here.

TornadoTwins, youtube channel about Game Development with Unity.

Unity iOS ShaderLab Tutorials, youtube channel about Unity shader language, ShaderLab, focused on iOS applications.

Design3, best site to watch video tutorials about Unity. It’s not free, but worth paying for it if you want to specialize on the tool.

Prime31 Studio, youTube channel about the use of C# with Unity.

iTween, tweens in Unity now very easy. A must to everyone. There are two other projects related to it. PathEditor (same link) to build trajectories easily and iTween Visual Editor.

UnityScrito2C#, usefull tool to port JavaScript code to C#. There’s a paid package that does the opposite at Unity Asset Store.

UnityScriptEditor, if you want to use UnityScript in Unity, than this is the tool you must use. It’s free, but it’s Windows Only

AngryAnt, Unity Guru blog. Two very useful projects: Behave, to create Behavior Trees to Unity, and Path, an implementation of A*.

UnitySteer, Steering algorithms implemented in Unity.

Finite State Machine, my own implementation of Finite State Machines in Unity.

2. How do I access a variable/function from one script in another one?

The GameObject (GO) with the tag “NPC” has the script AI.cs attached to it. The script defines the variable position and the function Attack() The GO controlled by the player has the script PlayerControl.cs. To access position or Attack() in PlayerControl:

[csharp]
using UnityEngine;

public class AI : MonoBehaviour
{
public float position;

public void Attack()
{
// Some Code
}
}
[/csharp]
[csharp]
using UnityEngine;

public class PlayerControl : MonoBehaviour
{
public void Update()
{
float p = GameObject.FindWithTag(“NPC”).GetComponent<AI>().position;

GameObject.FindWithTag(“NPC”).GetComponent<AI>().Attack();
}
}
[/csharp]

3. How do I link a object to another, by code, when there is a collision between them?

If I want to link a GameObject (GO) that has the tag “Weapon“, by code, using the script PlayerControl.cs, that is attached to another GO controlled by the player, that’s the easiest way

[csharp]
using UnityEngine;

public class PlayerControl : MonoBehaviour
{
public void OnCollisionEnter(Collision col)
{
// Check if it’s the desired object
if (col.gameObject.tag == “Weapon”)
{
col.transform.parent = transform;
}
}
}
[/csharp]

4. How do I make a timer?

[csharp]
using UnityEngine;

public class TimerControl : MonoBehaviour
{
private float timer = 0F;
public float timeStep = 5F; // number of seconds between each action

public void Update()
{
timer += Time.deltaTime;

if (timer >= timeStep)
{
timer = 0F;
// Place the code for the Action here
}
}
}
[/csharp]

5. How do I make a simple watch with a reset when there’s some kind of event ?

The script PlayerControl.cs is attached to the GameObject controlled by the player and the script TimerControl.cs is attached to a GUIText component which has the tag “timer”. The object that resets the timer has a tag “powerup”.

[csharp]
using UnityEngine;

public class PlayerControl : MonoBehaviour
{
public void OnCollisionEnter(Collision col)
{
if (col.gameObject.tag == “powerup”)
{
GameObject.FindWithTag(“timer”).GetComponent<TimerControl>().ResetTimer(5);
Destroy(col.gameObject);
}
}
}
[/csharp]
[csharp]
using UnityEngine;

public class TimerControl : MonoBehaviour
{
public int totalTime = 60; // total time in seconds
private float timeLeft;

public void Start()
{
timeLeft = totalTime;
}

public void Update()
{
if (timeLeft >= 0)
{
timeLeft -= Time.deltaTime;
string prefix = “Time: “;
guiText.text = prefix + FormatTime(timeLeft);
}
}

private string FormatTime(float time)
{
int minutes = (int)(time / 60);
int seconds = (int)(time % 60);
return string.Format(“{0:00}:{1:00}”, minutes, seconds);
}

public void ResetTimer(int time)
{
timeLeft += time;
}
}
[/csharp]

6. How do I make a simple Life Bar?

This script must be attached to a GameObject in your scene, like MainCamera.

[csharp]
using UnityEngine;

public class LifeBar : MonoBehaviour
{
public int maxHP;
public int left;
public int top;
public Texture2D hpBar;

private Texture2D currentHPBar;

private int barWidth, barHeight;

private int hp;
public int HP
{
get { return hp; }
set
{
hp = value;
if (hp > maxHP) hp = maxHP;
if (hp < 0) hp = 0;
}
}

public void Start()
{
hp = maxHP;

if (hpBar != null)
{
currentHPBar = hpBar;
barWidth = hpBar.width;
barHeight = hpBar.height;
}
else
{
barWidth = 100;
barHeight = 20;
currentHPBar = new Texture2D(barWidth, barHeight);

for (int i = 0; i < barWidth; i++)
for (int j = 0; j < barHeight; j++)
currentHPBar.SetPixel(i, j, Color.red);

currentHPBar.Apply();
}
}

public void OnGUI()
{
GUI.DrawTexture(new Rect(left, top, hp, barHeight), currentHPBar);
}
}
[/csharp]

7. How can I drag a GameObject with the mouse?

This script can be attached to any GameObject in your scene and your camera must have the tag “MainCamera”. It also changes the color of the selected object to make it more visible among the other objects in the scene.

[csharp]
using UnityEngine;

public class DragObject : MonoBehaviour
{
private Transform target = null;
private Color originalColor = Color.clear;
public Color selectedColor;
public float vel;

public void Update()
{
// Test if Left button was pressed and there was
// no object selected
if (Input.GetMouseButton(0) && target == null)
{
// Cast a Ray from Camera Position
Vector3 v = new Vector3(Input.mousePosition.x,
Input.mousePosition.y,
0);
Ray ray = Camera.main.ScreenPointToRay(v);

// This object will store the closest object
// in front of the camera
RaycastHit hit;

// Test if there’s something in front of the camera
if (Physics.Raycast(ray, out hit))
{
// Hide the Cursor
Screen.showCursor = false;

target = hit.transform;

if (target.renderer.material != null)
{
if (originalColor == Color.clear)
originalColor = target.renderer.material.color;

target.renderer.material.color = selectedColor;
}
}
}

// Reset the target if Left button was released
else if (Input.GetMouseButtonUp(0) && target != null)
{
// Show Cursor again
Screen.showCursor = true;

if (target.renderer.material != null)
{
target.renderer.material.color = originalColor;
originalColor = Color.clear;
}

target = null;
}

// Move the target
if (target != null)
{
Vector3 moved = new Vector3(Input.GetAxis(“Mouse X”),
Input.GetAxis(“Mouse Y”),
0);
target.position += moved;
}
}
}
[/csharp]

8. How can I rotate a GameObject with the mouse like in the Editor?

This script can be attached to any GameObject in your scene and your camera must have the tag “MainCamera”. It also changes the color of the selected object to make it more visible among the other objects in the scene.

[csharp]
using UnityEngine;

public class RotateObject : MonoBehaviour
{
private Transform target = null;
private Vector2 oldMouseRotate;
private Color originalColor = Color.clear;
public Color selectedColor;
public float rotX;
public float rotY;

public void Start()
{
oldMouseRotate = new Vector2(Input.mousePosition.x,
Input.mousePosition.x);
}

public void Update()
{
// Test if Right button was pressed
if (Input.GetMouseButton(1) && target == null)
{
// Cast a Ray from Camera Position
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

// This object will store the closest object
// in front of the camera
RaycastHit hit;

// Test if there’s something in front of the camera
if (Physics.Raycast(ray, out hit))
{
// Hide the Cursor
Screen.showCursor = false;

target = hit.transform;

if (target.renderer.material != null)
{
if (originalColor == Color.clear)
originalColor = target.renderer.material.color;

target.renderer.material.color = selectedColor;
}
}
}

// Reset the target if Left button was released
else if (Input.GetMouseButtonUp(1) && target != null)
{
// Show Cursor again
Screen.showCursor = true;

if (target.renderer.material != null)
{
target.renderer.material.color = originalColor;
originalColor = Color.clear;
}

target = null;
}

if (target != null)
{
float yAngle = oldMouseRotate.x – Input.mousePosition.x;
float xAngle = Input.mousePosition.y – oldMouseRotate.y;

Vector3 rotVector = (Vector3.right * xAngle * rotX * Time.deltaTime)
+ (Vector3.up * yAngle * rotY * Time.deltaTime);
target.transform.Rotate(rotVector, Space.World);
}

oldMouseRotate.x = Input.mousePosition.x;
oldMouseRotate.y = Input.mousePosition.y;
}
}
[/csharp]

9. How can I instantiate a GameObject at random positions with a specific frequency?

Attach this script to an empty gameobject in your scene. Its position will be used as the center of the random sphere to generate the objects. Its orientation will be used as the starting orientation for the objects to be instantiated, but you can always compute a new orientation to the objects.

[csharp]
using UnityEngine;

public class ObjectFactory : MonoBehaviour
{
public GameObject obj;
public float frequency;
private float timer;

public void Update()
{
timer += Time.deltaTime;

if (timer >= frequency)
{
timer = 0;

// Change the parameters of Range for different random values
// Set py to transform.position.y if you want the object to be in the same plane
float px = transform.position.x + UnityEngine.Random.Range(-10, 10);
float py = transform.position.y + UnityEngine.Random.Range(-10, 10);
float pz = transform.position.z + UnityEngine.Random.Range(-10, 10);
Vector3 pos = new Vector3(px, py, pz);

GameObject.Instantiate(obj, pos, transform.rotation);
}
}
}
[/csharp]

10. How can I keep the GUI resolution independent?

[csharp]
using UnityEngine;

public class MyGUI : MonoBehaviour
{
private Matrix4x4 originalMatrix;
public int originalWidth;
public int originalHeight;

public void Start()
{
originalMatrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(Screen.width / originalWidth, Screen.height / originalHeight, 1));
}

public void OnGUI()
{
GUI.matrix = originalMatrix;
// GUI code
}
}

[/csharp]

11. How can I make the camera move towards a target when there’s something between them?

This script is a little variation from one found in the forum with the name of WoWCamera, so I’ve kept the same name for the class. Attach this script to the camera and set the variables (the most important is target, the one the camera should follow). Their names are very obvious, but if you have any doubt, send me an email through the Contact menu

[csharp]
using UnityEngine;

public class WoWCamera : MonoBehaviour
{
public  Transform target;
public  float     targetHeight      = 2.0f;
public  float     distance          = 2.8f;
public  float     maxDistance       = 10.0f;
public  float     minDistance       = 0.5f;
public  float     deltaDistance     = -0.28f;
public  float     xSpeed            = 250.0f;
public  float     xSpeedDump        = 0.02f;
public  float     ySpeed            = 120.0f;
public  float     ySpeedDump        = 0.02f;
public  float     yMinLimit         = -40.0f;
public  float     yMaxLimit         = 80.0f;
public  float     zoomRate          = 20.0f;
public  float     rotationDampening = 3.0f;
private float     x                 = 0.0f;
private float     y                 = 0.0f;

public void Start()
{
Vector3 angles = transform.eulerAngles;
x = angles.y;
y = angles.x;
}

public void LateUpdate()
{
// If no target, don’t move the camera
if (!target) return;

// If either mouse buttons are down, let them govern camera position
if (Input.GetMouseButton(0) || (Input.GetMouseButton(1)))
{
x += Input.GetAxis(“Mouse X”) * xSpeed * xSpeedDump;
y -= Input.GetAxis(“Mouse Y”) * ySpeed * ySpeedDump;
}

// otherwise, ease behind the target if any of the directional keys are pressed
else if (Input.GetAxis(“Vertical”) != 0 || Input.GetAxis(“Horizontal”) != 0)
{
float targetRotationAngle  = target.eulerAngles.y;
float currentRotationAngle = transform.eulerAngles.y;
x = Mathf.LerpAngle(currentRotationAngle, targetRotationAngle, rotationDampening * Time.deltaTime);
}

// Compute the Distances
distance -= (Input.GetAxis(“Mouse ScrollWheel”) * Time.deltaTime) * zoomRate * Mathf.Abs(distance);
distance  = Mathf.Clamp(distance, minDistance, maxDistance);
y = ClampAngle(y, yMinLimit, yMaxLimit);

// Rotate the Camera
Quaternion rotation = Quaternion.Euler(y, x, 0);
transform.rotation  = rotation;

// Position the Camera
Vector3 position  = target.position – (rotation * Vector3.forward * distance + new Vector3(0, -targetHeight, 0));
transform.position = position;

// If there’s something between the camera and the target
RaycastHit hit;
Vector3 trueTargetPosition = target.transform.position – new Vector3(0, -targetHeight, 0);

// Cast the line to check:
if (Physics.Linecast(trueTargetPosition, transform.position, out hit))
{
// If so, shorten distance so camera is in front of object:
float tempDistance = Vector3.Distance(trueTargetPosition, hit.point) – deltaDistance;

// Finally, repositon the camera
position           = target.position – (rotation * Vector3.forward * tempDistance + new Vector3(0, -targetHeight, 0));
transform.position = position;
}
}

static float ClampAngle(float angle, float min, float max)
{
if (angle < -360) angle += 360;
if (angle > 360) angle -= 360;
return Mathf.Clamp(angle, min, max);
}
}
[/csharp]

12. How do I change the pivot of a imported mesh?

Check this scrpit in the UnifyWiki. SetPivot.

13. How do I create a circular minimap?

Check this tutorial. First one, how to create the camera. Second, how to make circular mask for the minimap.