Skip to content

Instantly share code, notes, and snippets.

@booyaa
Created October 28, 2014 06:32
Show Gist options
  • Save booyaa/4f8534ad756c77a07079 to your computer and use it in GitHub Desktop.
Save booyaa/4f8534ad756c77a07079 to your computer and use it in GitHub Desktop.
Unity Hints and Tips; and Live Training Notes

#Unity Hints and Tips; and Live Training Notes (WIP)

link test

##collisions

player should have a collider, but not triggering. rigidbody maybe required (for physics?) target to collide with should have a collider and a trigger, also has the controller script

##microphones

##misc tips

###command line

file:///Applications/Unity/Unity.app/Contents/Documentation/html/en/Manual/CommandLineArguments.html

###concurrency

  • invoke vs startcoroutine.
  • yield return new WaitForSeconds(5f);
  • yield return YourMethod();

###TODO: which is worse GameObject.Find vs GameObject.FindWithTag

###GameObject.Find

don't use every frame update, if you can set once in a member variable.

###testing if an object has a public variable defined

var foo = other.gameObject.GetComponent<MakeSticky>();
if ( foo != null && foo.isStuck) {
	isStuck = true;
}

###pause time i.e. gameover

Time.timeScale = 0;

Not sure this is the best way to pause things

moving objects MoveTowards

Learn this tip via MindCandy's LearnUnity series. They used it to move baddies left and right.

Create an empty game object as your target and use Vector3.MoveTowards.

	public GameObject target;
	public float speed;

	void FixedUpdate() {
		float step = speed * Time.deltaTime;
		transform.position = Vector3.MoveTowards(transform.position, target.transform.position, step);
	}
		

###pixel art sprites look crap

switch filter mode from bilinear (default) to point

###screen caps

Application.CaptureScreenshot("filename.png")

Is there a way to avoid the gameover panel being included?

###titling/snap

32x32 sprite is usually 0.32x0.32 in Unity. Use a BoxCollider2D to confirm this. Change Snap Settings X,Y to match. You may need to change scale to 1.

#infi runners

##cameras

###background (no parallax)

create new a camera with a child quad object. your background is the texture.

also has a scroller script

	public float speed = 0;
	
	// Update is called once per frame
	void Update () {
		renderer.material.mainTextureOffset = new Vector2(Time.time*speed,0f);
	}

###main camera

tracks player's transform

	// Update is called once per frame
	void Update () { // stay ahead of player
		transform.position = new Vector3(player.position.x + 6, 0, -10);
	}

##layering

background cam has a depth of -2, the main cam has a depth of -1.

##player

player in mike's demo used 2D controller, but we're also responsible for movement. this is how the starting platform vanishes.

##destroyers

create a box collider Is Trigger prop enabled. use quad as this will readily accept the 2d collider.

void OnTriggerEnter2D(Collider2D other)
{
	if (other.tag != "Player")
	{
		Destroy (other.gameObject);
	}
}

##spawners

bit like a destroyer, createa a quad without a collider. you want an array of objects (how can this be randomly generated?) that you will spawn in the area.

add them via the inspector

	public GameObject[] obj;
	public float spawnMin = 1f;
	public float spawnMax = 2f;

	// Use this for initialization
	void Start () {
		Spawn();
	}
	
	void Spawn() {
		Instantiate(obj[Random.Range (0, obj.GetLength (0))], transform.position, Quaternion.identity);
		Invoke ( "Spawn", Random.Range (spawnMin, spawnMax));
	}

physics issues

objects falling through

http://stackoverflow.com/questions/9688237/how-to-prevent-colliders-from-passing-through-each-other

reading list

http://www.third-helix.com/2012/02/05/making-2d-games-with-unity.html http://www.third-helix.com/2013/09/30/adding-to-unitys-builtin-classes-using-extension-methods.html http://gamedevelopment.tutsplus.com/articles/how-to-fix-common-physics-problems-in-your-game--cms-21418 http://gamedevelopment.tutsplus.com/tutorials/creating-dynamic-2d-water-effects-in-unity--gamedev-14143 http://gamedevelopment.tutsplus.com/tutorials/how-to-generate-shockingly-good-2d-lightning-effects-in-unity-c--cms-21275 http://gamedevelopment.tutsplus.com/articles/how-to-fix-common-physics-problems-in-your-game--cms-21418 http://devmag.org.za/2012/07/12/50-tips-for-working-with-unity-best-practices/ http://www.wildbunny.co.uk/blog/2011/12/11/how-to-make-a-2d-platform-game-part-1/ http://www.wildbunny.co.uk/blog/2011/12/14/how-to-make-a-2d-platform-game-part-2-collision-detection/ http://www.wildbunny.co.uk/blog/2011/12/20/how-to-make-a-2d-platform-game-part-3-ladders-and-ai/ http://www.wildbunny.co.uk/blog/2011/04/06/physics-engines-for-dummies/ http://answers.unity3d.com/questions/634831/how-do-i-make-make-objects-stick-to-a-ball-and-aff.html http://answers.unity3d.com/questions/19924/how-to-call-a-routine-every-3-seconds.html

##unity videos

###object pooling

###Live Training testing tools

  • 4:24 where to download from asset store

###Live Training 14 Jul 2014 - Unity Tips and Tricks 2

  • 4:17 player inventory (useful code snippet)
  • 17:10 scale and orientation
    • unity unit is a cube, which is a 1m^3
    • 18:55 how to scale your model in blender, create a cube and compare it against the unity cube.
  • 35:33 stopped

###Live Training 23 Jun 2014 - Unity Tips and Tricks

  • 15:18 - Execution order of event functions file:///Applications/Unity/Unity.app/Contents/Documentation/html/en/Manual/ExecutionOrder.html
  • 39:30 - shift space (full screen)
  • 39:41 - change sky box and sunlight
  • 44:00 - by manuk4 medieval environment
  • 45:52 - terrain creation
  • 51:17 - create water use a water texture

###Live Training 10 Jul 2014 - Comm between gameobjs

*15:13 - How to automatically add a rigidbody to an object when you add your script to the gameobj

[RequireComponent (typeof(Rigidbody))] // to classs
  • 21:01 - Use case for GetComponentsInChildren, group of particle emitters.
  • 30:22 - Using GameObject.FindGameObjectsWithTag to pick a random spawn point and instantiate a spark.
  • 40:39 - An alternative pattern to singleton class, also how to grab a reference from an instantiated object.

###Live Training 12 Aug 2014 - Intro to plugins

  • 7:07 managed code/plugins - launch mono w/o unity.

    • 8:05 Create new project Library
    • 14:34 nav to where dll has been compiled, drag the dll into the project view of unity into a folder called plugins
    • 16:07 tip: make sure your lib matches the target you're build for the cpu and .net 2.0 (for cross platform)
    • create a new script, to reference the DLL just use namespace.ClassName:
     void Start () {
     	RandomNumber.MyClass obj = new RandomNumber.MyClass();
     	Debug.Log ("Hello from RandomNumber.dll: " + obj.GetRandom()); 
     }
    
  • 21:31 native plugins (pro only) - skipped because it was vs and c++ might not be supported in unity free

    • for reference c++
     .#include <iostream>
     .#define DllExport _declspec (dllexport)
     
     extern "C"
     {
     	DllExport int GetRandom() 
     	{
     		return rand();
     	}
     }
    
    • copy to the plugin dir note: the different icon
    • 31:31
     [DllImport("RandomNumberDLL")]
     private static extern int GetRandom();
     
     void Start () {
     	Debug.Log ("Hello from RandomNumber.dll: " + GetRandom()); 
     }
    
    • 32:40 right click on attribute and resolve, which adds using System.Runtime.InteropServices;
    • 37:54 how to detect if a plugin will work for a given platform
	using Unity...
	
	public class RandomNumberWrapper // note the lack MonoBehaviour
	{
	#if UNITY_STANDALONE_WIN
		const string dll = "RandomNumberDLL";
	#elif UNITY_STANDALONE_OSX
		const string dll = "RandomNumberBundle";
	#elif UNITY_IOS // IOS doesn't load DLL individual they get bundled as __Internal
		const string dll = "__Internal";
	#else
		const string dll = "";
	#endif
	
	[DllImport(dll)]
	
	public static int GetRandNum() // this will act as our wrapper for unsupported platform
	{
		#if (UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_IOS)
			return GetRandom();
		#else
			return -1;
		#endif
	}
	void Start() ....
	
	
	}

* don't use Application.platform to determine at run time it's inefficient and add code you might not be need. preprocessor will only include the code that isn't grey.

references:

  • plugins - file:///Applications/Unity/Unity.app/Contents/Documentation/html/en/Manual/Plugins.html
  • native (pro only) - file:///Applications/Unity/Unity.app/Contents/Documentation/html/en/Manual/NativePluginInterface.html
  • preprocessor directives - file:///Applications/Unity/Unity.app/Contents/Documentation/html/en/Manual/PlatformDependentCompilation.html
  • how to use mono dlls file:///Applications/Unity/Unity.app/Contents/Documentation/html/en/Manual/UsingDLL.html

###Live Training 11 Nov 2013 - The Particle System

###Topdown 2D Game

Mike makes a point and click space samurai game. Teach you about mechanim, how to make a simple three frame laser sword. Also how to wire up an explosion animation. useful tip about creating a new animation is to drag the selected frames into the gamescene it will create an game object with the controller assigned. You can create a prefab of this object so you can spawn it.

Also having layers in your mechanim means you can have multiple animations running simultaneously i.e. player moving and idle along with sword animations.

###The new UI

  • 3:09 setup sprites in a 9 square format to keep them scalable.
  • talks about pivots and anchors (almost makes sense). shows how the ui can scale between different resolution.
  • 12:56 - ui/button transitions - tinting, images
  • You can set very basic button one way button toggle functionality. The Back button was linked to OrthographicCamera false and the Accept button was linked to OrthographicCamera true.
  • 19:45 - link text output to a slider (dynamic), take away is to remember that you can also link to an Unity Object not just primatives. Uses the Update Value (script) event.
  • 22:53 - link text's script w/o parameter to the slider (using traditional public variables and linking the slider object to the script. Uses On Value Change (boolean) event.
  • 27:00 - scroll rect and scroll bar (reading in game documentation or letters).
    • 31:18 - masking the content out of the view. add an image component to the scroll rect, then add a mask component. there's a toggle to determine if you allow the content to be visible or masked by the image (presumably this is an order of presidence thing what happens if there's multiple images?). At this point you can already drag scroll the content w/o the need for additional interfaces!
    • 31:48 - add scroll bar. default is horizontal. you don't want this ui to be a child of the scroll rect otherwise it'll be masked so make it a chanel of the main panel.
  • 34:25 - render order top to bottom in hierarchy means top most ui will be draw first and subsequent ui will be drawn over it.

###UI Events and Event Triggers

  • 01:20 - Event System (Script) you can link First Selected property to a button. This will allow to trigger the button w/o using the mouse, this could be useful for gamepads.
  • 01:59 - refers to navigation items, but details are on the page for this ui lesson.
  • 02:19 - default for input actions per second is 10. think bounce rate.
  • 03:54 - if your ui component doesn't have a event i.e. an image you can add one by clicking on Add Component > Event > Event Trigger. Then select the event you wish to add. In the example, Mike dragged the Image object onto its trigger PointerEvent (BaseEventData), selected it's Bomb script which had a public function called TurnRed.

###UI Image

  • 01:00 - how to assign a shader to a UI Image. Create a material, for it's shader choose from those in the uGUI list.
  • 01:15 - Image type: sliced is the 9 square (scalable sprit we saw in the new UI video). There's a link to the sprite editor in the tutorial page.
  • 02:39 - Image type: fill - if this is programatic, could use for transitions or health bars? file:///Applications/Unity/Unity.app/Contents/Documentation/html/en/ScriptReference/UI.Image.html radial fills could be used for car speedometers?

###UI mask

###Live Training 22nd September 2014 - Animate Anything

  • 8:49 use GameObject > Move To View to move an object to the current Scene viewport
  • animating a door (changing from state to state) that already has key frames animated
    • 10:15 animation controller (if your model has animations then the animator component will be automatically added)
    • 11:04 link the controller to the controller slot on your animator
    • 11:32 open up the animator window and drag and drop the animations states you wish to add (orange is the default state)
    • 12:25 to link / transition between states you need a transform link, ctrl-click to create a link. for doors you'll need a two way transition for open and close.
    • 12:51 by default the state change between transition is controlled by exit time, to control through a script create a new parameter i.e. boolean called Open. Then wire up the Condition for each state to reflect the variable state i.e. for the Close state the Open should be false vica versa. The script will alter this parameter.
    • 16:00 add a box collider to the door model to stop clipping, but use a sphere collider with a wide radius on the prefab as the trigger.
    • 16:20 code example - Get a reference to Animator component, OnTriggerEnter animator.SetBool("Open", true), OnExit Open = false.
  • how to activate lights using mechanim
    • 25:30 set lights to brightness 0, add animator component, create a new animator controller
    • 26:38 open animation windows to create two clip/curves? (on/off)
      • create a new clip: DeactivateLight
        • select the first light
        • create a new curve
        • select from the transform list light brightness
        • adam left the starting keyframe with light brightness of 0
      • create a new clip: ActiveLights
        • select the first light
        • create a new curve
        • select from the transform list light brightness
        • delete the keyframe at the end
        • n.b. you're in record mode and the transform component will also be tinted in red
        • change brightness to 1
    • 29:18 go to animator window, you may need to drag your new animation clips into the window
    • 30:00 update script, animator.setTrigger("Activate")
    • 32:23 go back to animator window, create a new parameter trigger called Activate, set the condition of the transform as Activate.
    • 33;18 Tip: To add an array gameobjs as reference, lock the gameobj where you wish to add the reference then drag you gameobjs over.
    • 34:14 Tip: You can clone these animated game objects and the animation will be reused, but entirely independant i.e. when you trigger the door it won't open the cloned door or turn the cloned lights.
    • 43:50 if curves are greyed out...
    • TODO: Find out which is more efficient MechAnim or script for triggered events?
    • TODO: Can MechAnim be used as a FSM?

useful references:

  • glossary - file:///Applications/Unity/Unity.app/Contents/Documentation/html/en/Manual/AnimationGlossary.html

###Live Training 8th September 2014 - Using UI Tools

  • using 2D to position ui elements
  • player icon, health and ammo bar

placement use anchors (shift and alt) to place the element in the right area and then offset. Don't leave anchors in the centre (default).

  • enemy icon and health (percentage is wrong)
  • 33:34 pause manager
    • quiting #if UNITY_EDITOR pragma using UnityEditor #if to either stop the game playing (if in editor) or quit the application
    • public functions so they can be bound to buttons
    • 36:02 buttons with overlays and scaling.
    • 42:00 panels
    • 49:00 wiring up pause manager (which is linked to pause canvas) to the pause button's on click event. useful thing to note is that the pause manual will disappear automatically if you resume (how?).
  • 1:00 - q&a

###Live Training 12th of May 2014

  • to tile and snap, hold down V.
  • use sorting layers to separate sections i.e. background, foreground
  • use sorting order with layers to set object hierarchy (but only after you determined an object should live in that layer). this is better than using z index.
  • use pixel density when import images to scale it to your scene, don't forget to hit import again. this is better than using transformation scale.
  • if you drag an object into the hierarchy rather than the scene it will always have zero origin
  • group tiled objects into a parent gameobject
  • when to use kinematic - for arcade games, where you don't want gravity to influence gameobjects we want it to respond to scripting and use colliders.
  • scripting - Update is called once per frame, FixedUpdate is called once per physics frame.
  • Use Camera.main to get the default camera, this could allow you to override for an interesting 2nd play of a level by changing camera.
  • 30:47 Vector3 rawPosition = cam.ScreenToWorldPoint(Input.mousePosition)
  • 34:20 Screen clamping player
  • bombs/bowling balls aren't kinematic, we want gravity to influence them, but they need still colliders.
    • create physics 2d mat
    • then create prefab based on object
    • zero origin
  • 45:00 adding an edge collider to the player to guide/collide with bombs and bowling balls.
  • 47:30 making the bowling balls disappear into the hat (requires front and back sprites)

2D scroller

  • parallax scrolling
  • 30:00 tiling xevious

tips and tricks

  • docs > scripting > scripting overview > execution order of event functions (has diagram of script life cycle)
  • unity answers: what are the c# errors messages (for the various csNNNN errors)
  • S-F to track an object in play mode
  • to view private variables in scripts within the inspector switch to Debug
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment