Scripts

From Unify Community Wiki
(Difference between revisions)
Jump to: navigation, search
(General Purpose Effect Scripts)
(added introduction and contributions sections)
 
(44 intermediate revisions by 24 users not shown)
Line 1: Line 1:
{| align="right"
+
{{Scripts Navigation}}  
  | __TOC__
+
  |}
+
  
= General =
+
== Introduction ==
 +
In this section you'll find a large assortment of sample scripts and code snippets contributed by members of the community. These can be accessed by selecting one of the category tabs above.
  
== General Concepts ==
+
=== Contributions ===
 +
Anyone is free to contribute their own original code to the wiki but you should keep a few things in mind when doing so:
  
*[[AManagerClass]] - How to add easy access to a singleton class in a scene.
+
# '''No Copyrighted Content''' - Code contributed must be either original or licensed in a way which allows sharing (e.g. public domain, open-source, etc.).
*[[AStarHelper]] - Textbook implementation of the A* pathing routine.
+
# '''Keep It Concise''' - Small scripts and code snippets are ideal. More complex code should be hosted on a platform like [https://bitbucket.org/ Bitbucket] or [https://github.com/ GitHub] instead.
*[[BasicDataStructures]] - Discussion of the use of the data-structures available in Unity.
+
# '''Use Proper Formatting''' - Please read the [[Help:Formatting| formatting help page]] before creating a new script. This will explain how to properly format and structure your code.
*[[BooMessenger]] - An efficient and simple to use messaging platform. Allows hierarchial grouping of message types.
+
*[[CoroutineScheduler]] - A coroutine scheduler implementation. Gain a better understanding of coroutines.
+
*[[CoUpdate]] - An alternative to Update which support yield instructions. Benefit from cleaner code.
+
*[[Executors_Framework|Executors Framework]] - A framework for multi-threading without getting a headache. (Warning: The Unity API is not thread-safe)
+
*[[CSharpEventManager]] - C# implementation of a messaging/notification system. Allows subscription to events without referencing their definitions.
+
*[[CSharpMessenger]] - Another C# messaging/notification system implemented using delegates and generics.
+
*[[CSharpMessenger Extended]] - C# messaging system using delegates and generics. Based on [[CSharpMessenger]] but has more error detection.
+
*[[FakeGizmoDemo]] - simple example of creating a fake Gizmo - a three-arrow axis, mouse-moveable, that can be applied to an object at Runtime, not just during editing. Also contains an example of Procedural Mesh Creation - using only code to create an in-game mesh object from vertices and triangles.
+
*[[JavascriptMultiDimArrays]] - Declare multi-dimensional arrays like int[,] or int[][] in JS (mostly obsolete in Unity 3.2, though still useful for jagged arrays)
+
*[[Lipis Runtime Gizmo]] - Update on Lipis Runtime Gizmo (works with Translation, Rotation, and Scale).  Included C# code and corrected javascript code removing unity 3D reserved words in code.
+
*[[MessageRouter]] - subscription based messaging with delayed notification, delivery stages, message filtering, tagging, and receiver assertions
+
*[[NotificationCenter]] - Register scripts to receive and post notifications.  Handles messaging across scripts without references to each other.
+
*[[SimpleRegex]] - How one might use regular expressions in Unity.
+
*[[SQLite]] - How to integrate SQLite into your project.
+
*[[ToggleGravity]] - How to toggle a property, in this case the global gravity setting, by the left mouse button.
+
  
== Utility Scripts ==
+
=== License ===
 
+
Unless otherwise specified, all code provided on the Wiki is licensed under Creative Common's Attribution-ShareAlike 3.0 Unported (CC BY-SA 3.0).
*[[Angle]] - Helper class to work with angles.
+
*[[ArrayPrefs]] - Functions for saving and loading arrays of ints, floats, and strings using PlayerPrefs. (Made obsolete by [[ArrayPrefs2]].)
+
*[[ArrayPrefs2]] - Faster and better than ArrayPrefs. Save/load Vector2, Vector3, Quaternion, Color as well as a bunch of different array types.
+
*[[BoolPrefs]] - Adds GetBool and SetBool, which are missing from PlayerPrefs.
+
*[[ComponentInstantiationUtility]] - Static C# class that allows you to instantiate pre-parented components as game objects with one easy line of code.
+
*[[CustomRandom]] - C# Random number generator, when you must have a random number generator that works the same way on all platforms!
+
*[[DeepCopy]] - Creates a deep copy of an array or hashtable.
+
*[[deepSearch]] - Searches recursively from the parent down.
+
*[[ExpandoObject]] - Create ECMAScript-style expando objects in Unity Javascript.
+
*[[ExtRandom]] - An extension to the Unity class Random
+
*[[FingerManager]] - Easily manage multi-touch phases for iPhone.
+
*[[HexConverter]] - Functions for converting decimal colors to hexadecimal... and back.
+
*[[HSBColor]] - This utility script provides a HSB color model in addition to Unity's built in RGB Color class.
+
*[[Interpolate]] - Interpolation utility functions for easing, Bezier splines, and Catmull-Rom splines.
+
*[[IsVisibleFrom]] - An extension method for checking if an Renderer is rendered by a specific Camera.
+
*[[IPhoneToMouse]] - Replaces iPhoneInput commands with Input so you can use it in PC/Mac Version too.
+
*[[LABColor]] - This utility script provides an LAB color model. Lab color is designed to approximate human vision and so it aspires to perceptual uniformity.
+
*[[LanguageFilter]] - Removes badwords from strings using regular expressions.
+
*[[LayerMaskExtensions]] - Extension class to add usability and easier debugging to LayerMasks.
+
*[[Layers]] - A utility script for holding easily-accessible layers and easily creating masks.
+
*[[Mathfx]] - This script contains a growing number of small and useful math functions (short for Mathf eXtended).
+
*[[Matrix]] - A class for doing 3D matrix math against Vector3 objects.
+
*[[MazeGenerator]] - Randomly generates a maze.
+
*[[MD5]] - Generate an MD5 hash for a string.
+
*[[MeshCreationHelper]] - Helper to create a new mesh from some mesh's submesh.
+
*[[MeshMerger]] - Draw a large number of meshes with a single draw call.
+
*[[MeshSmoother]] - Deformation of a mesh by applying Laplacian/HC-Algorithm Smoother, also script for finding adjacent vertices in a mesh.
+
*[[MetadataSystem]] - Mechanism for ciphered, compressed preferences and declarative metadata system with runtime overrides.
+
*[[MetaMorph]] - MetaMorph is a Unity3d and Blender3d toolkit that allows mesh animation in Unity games using Blender shapekeys.
+
*[[MixupGO]] - Flatten GameObjects and all attached components into a single object using duck typing  in Unity Javascript.
+
*[[ObjExporter]] - A simple utility class for exporting a mesh to an obj file.
+
*[[ObjExporterColorUvs]] - Enhanced version of [[ObjExporter]] that also exports vertex color and multiple uvsets to an obj file.
+
*[[ObjImporter]] - Import .obj files at runtime.
+
*[[PlaySoundAtInterval]] - Plays a sound file at the specified intervals of time.
+
*[[PolyContainsPoint]] - Like Rect.Contains, except instead of a rect, you can define any arbitrary polygon.
+
*[[PrintPolyCount]] - Prints total vertex and triangle count in the object hierarchy.
+
*[[PropertyListSerializer]] - Loads and saves a .plist XML file to and from a hierarchical hashtable.
+
*[[ReflectedObject]] - Reflects a target object, providing quick access by name to reading/writing its fields/properties, and calling its methods.
+
*[[Set]] - A set data structure.
+
*[[Shell]] - A replacement for the built-in shell function removed from Unity 1.6.1.
+
*[[SimpleDictionary]] - Implements a simple dictionary-like object AND lets you save/load the dictionaries to text files.
+
*[[Simple LOD Manager]] - Script to handle arbitrary number and distances for Level-Of-Detail in models
+
*[[SpeedLerp]] - Replacements for Mathf.Lerp, InverseLerp, SmoothStep, etc. that are typically 1.5X faster or more. Also adds Vector2Lerp and SuperLerp.
+
*[[Startup Manager]] - A singleton class that handles starting up scripts in a sorted order based on a priority variable
+
*[[StringToValue]] - Functions for finding data within a string.
+
*[[StringUtil]] - Word wrap and line count functions.
+
*[[TextScanner]] - A utility class for parsing strings using std C sscanf format strings.
+
*[[TextureDrawCircle]] - A function that draws circles inside a texture.
+
*[[TextureDrawLine]] - A function that draws lines inside a texture.
+
*[[TextureScale]] - Resize textures, while scaling the contents using either bilinear or point filtering.
+
*[[TextureUtils]] - Functions for colorizing, masking, and merging textures at runtime.
+
*[[TileSelector]] - An Inspector extension that creates a pop-up window to select a tile or a NxM group of tiles from a main tileset, for use in a sprite object.
+
*[[TinyXmlReader]] - A class that reads XML text and parses it for use.
+
*[[Triangulator]] - A utility class for splitting a 2D polygon into triangles.
+
*[[UnitSphere]] - A collection of random unit vector generating functions. (C#)
+
*[[Unity_Custom_Input_Manager]] - Allows you to change input configuration on the fly. Default inputmanager only allows you to change on start.
+
*[[UnityPaint]] - A script to draw anti-aliased lines, brush strokes and vector lines on a texture.
+
*[[UVTransfer]] - Editor script to transfer UVs between two models.
+
*[[VertexInfo]] - Displays the vertex numbers of a mesh at the runtime.
+
*[[XKCDColors]] - A collection of 948 color constants, from the xkcd color survey (C#).
+
 
+
== Really Simple Scripts ==
+
 
+
*[[3DMenu]] - A simple main menu for 3d text in your scene
+
*[[ConstantVelocity]] - Set a local velocity to an object (useful for missiles perhaps?)
+
*[[Flashlight]] - Allows the switching on and off of a light in script.
+
*[[GlobalUpdatePump]] - Register any method in any object to be called in one of Unity's update loops.
+
*[[OnCollideExplode]] - Spawn a prefab (explosion) on collision, and remove the GameObject from the game.
+
*[[OnCollideSound]] - Spawn a prefab (preferably a sound) if a collision is over a certain magnitude.
+
*[[OnExplosionEffect]] - Give an explosive effect over an area.
+
*[[OnMouseDown]] - Sends OnMouseDown messages on an iPhone.
+
*[[PointerManager]] - Hides the mouse pointer when it is not in use.
+
*[[SwitchCamera]] - Switches between cameras in your scene.
+
*[[Teleporter]] - Teleport all objects from one place to another.
+
 
+
== Code Snippets ==
+
 
+
*[[Accessing number of drawcalls from script]] - Retrieve the number of drawcalls for statistical purposes
+
*[[Calculating Lead For Projectiles]] - These script fragments allow you to add some lead ahead of the target allowing projectiles/missiles to collide with the target.  Uses a quadratic rather than an iterative solution.
+
*[[Load Data from Excel 2003]] - This script allows you to load information from excel spreadsheets into Unity, written in C#.
+
*[[Save and Load from XML]] - This script allows you to save and load data from an XML file, written in C# (JS version included).
+
*[[Save and Load from XML U3 Collections]] - Save and load all game objects in a scene, modify the code to add in what you want saved about the game object, written in C#.
+
 
+
= Controllers =
+
 
+
== Camera Controls ==
+
*[[AspectRatioEnforcer]] - Force the screen to a desired aspect ratio, using letterboxing/pillarboxing as necessary.
+
*[[CameraGradientBackground]] - A simple two-color gradient background for your camera.
+
*[[CarSmoothFollow]] - A smooth car follow script that dampens height, rotation and velocity based distance.
+
*[[CrossFade]] - Smoothly fade the view from one camera to another.
+
*[[CrossFadePro]] - Smoothly fade the view from one camera to another, with motion in both cameras.
+
*[[DreamWipe]] - Fade the view from one camera to another, with the wavy distortion seen with dream sequences or flashbacks
+
*[[FadeInOut]] - Fade a full-screen image in or out, good for fade in outs.
+
*[[Floating Origin]] - Translates everything so that the camera stays at the origin to resolve spatial jittering in large scale games.
+
*[[FlyThrough]] - A basic fly through camera movement like the one within the editor.
+
*[[Headbobber]] - Make an object bob up and down smoothly when you're pressing one or both of the horizontal/vertical axes.
+
*[[KeyboardOrbit]] - Tweaked version of the MouseOrbit script that allows keyboard control (or whatever is bound to the "Horizontal" and "Vertical" axes)
+
*[[KeyboardCameraControl]] - A C# script allowing various configurations for keyboard camera control. Also handles left keyboard modifiers (Alt,Ctrl,Shift)
+
*[[MinimapCamera]] - This script can be attached to a camera to provide some basic minimap functionality such as zooming and a full-screen toggle.
+
*[[MouseCameraControl]] - A C# script allowing various configurations for mouse camera control. Also handles left keyboard modifiers (Alt,Ctrl,Shift)
+
*[[MouseLookPlus]] - A javascript mouselook with key control. based on the standard assets C# mouselook.
+
*[[MouseLookPlus2]] - A modification of MouseLookPlus to allow for moving and strafing the camera.
+
*[[MouseOrbitImproved]] - Improved version of the original MouseOrbit script. Zooms with the mousewheel and uses linecast to make sure that object isn't behind anything.
+
*[[MouseOrbitZoom]] - A camera that combines orbiting zooming and panning, initially set up to mimic the 3dsMax camera controls.
+
*[[MultipleCameraSwitcher]] - A script that allows you to switch between different cameras in your scene. Supports four camera views that can be toggled with a button.
+
*[[OffsetVanishingPoint]] - Sets the vanishing point of a camera to an arbitrary position.
+
*[[RectangleWipe]] - Make an animated rectangular zooming screen wipe from one camera to another.
+
*[[ScreenWipes]] - Base script used by [[CrossFade]], [[CrossFadePro]], [[DreamWipe]], [[RectangleWipe]], [[ShapeWipe]], and [[SquishWipe]].
+
*[[ShapeWipe]] - Make an animated screen wipe, where an arbitrary shape containing the second view zooms in or out, and rotates.
+
*[[SmoothFollow2]] - This is designed to make a camera smoothly follow a ship in space.
+
*[[SmoothFollowWithCameraBumper]] - Based on SmoothFollow2, this features a bumper mechanism to prevent the camera from going through
+
*[[SmoothFollowAdvanced]] - Based on SmoothFollow2 & SmoothFollowWithCameraBumper, this features a design capability and controller input.
+
*[[SmoothLookFrame]] - Looks at a target but tries to keep another target within the camera's view.
+
*[[SmoothMouseLook]] - Modified version of MouseLook.cs script included in Unity's Standard Assets. It moves the camera with an easing effect.
+
*[[SquishWipe]] - Make an animated screen wipe from one camera to another, where the first image is squished out of view.
+
*[[StaticBackground]] - Use a static image as the background to your 3d scene.
+
*[[TouchLook]] - Use the iOS touches to rotate the camera
+
 
+
== Character Controller Scripts ==
+
 
+
*[http://arongranberg.com/unity/a-pathfinding A* Pathfinding] - An A* pathfinding-system for out-of-the-box pathfinding in Unity.
+
*[[AimDownSights]] - An expansion script for the FPSWalker that smoothly animates aiming down the sights of an attached gun model.
+
*[[Biped Parts Finder]] - Editor script for search simplification of parts of a biped body.
+
*[[Click To Move]] - Moves an object towards the mouse position when the Left Mouse Button is clicked
+
*[[ClickCharacterController]] - Uses Locomotion to move a character to the point the Left Mouse button is clicked
+
*[[DoubleJumpController]] - A hack for the 2d gameplay tutorial character controller script, it allows the character to make a second jump when jumping, or make a little jump when falling.
+
*[[Finite State Machine]] - A simple Finite State Machine framework to control NPCs.
+
*[[Force2D]] - Constrain a GameObject to move in two dimensions.
+
*[[FPSWalkerEnhanced]] - Adds features to standard FPSWalker, such as sliding down slopes, falling damage, and walk/run modes
+
*[[Gesture_Recognizer]] - A math based gesture recognition script.
+
*[[GridMove]] - A controller for character movement typically seen in old-school 2D RPGs and strategy games.
+
*[[HeadLookController]] - A component that can be used to make a character look towards a specified point in space, smoothly turning towards it with for example the eyes, head, upper body, or whatever is specified.
+
*[[JCar]] - A car using wheel colliders.
+
*[[KeyCombo]] - A class that can be used to detect fighting-game style combos.
+
*[[LookAtMouse]] - Cause an object to rotate toward the cursor, along the y axis.
+
*[[Pathfinding]] - ['''Old'''] A pathfinding-system using raycasting to avoid obstacles
+
*[[PhysicsFPSWalker]] - Another physics based fps walker script.
+
*[[RigidbodyFPSWalker]] - An physics based FPS walker that works with rigidbodies and thus is affected by forces, joints or other rigidbodies
+
*[[SeekSteer]] - A class that can be used to move an object to follow a loose path of waypoints
+
*[[ShipControls]] - Place this script on a [http://www.otee.dk/Documentation/ScriptReference/Rigidbody.html RigidBody] for 2D spaceship controls like [http://otee.dk/gallery/udwc/OverWhelmedArena.html OverWhelmed Arena].
+
*[[SimpleTankController]] - A script that emulates simple tank movement.
+
*[[VariableSpeedFPSwalker]] - An FPS walker script having different speeds for walking forward, strafing, and back-pedalling.
+
*[[WaypointMaster]] - Implementation of A* algorithm, based on waypoints.
+
 
+
== Animation Controllers ==
+
 
+
*[[AniMate]] - Script to quickly and easily create animations/tweens of almost any value and including eased, rigidbody and rotation animation.
+
*[[AnimationStepSync]] - Repositions object after animation ends - useful for positioning via animations.
+
*[http://www.pixelplacement.com/iTween/ iTween] - Focusing on the established solutions and frameworks of projects such as TweenLite, Tweener, and other tweening systems, iTween is a battle-tested solution for streamlining production in the Unity3D environment.
+
*[[MoveObject]] - Basic functions for when you just need to move something from point A to point B, or rotate by a given number of degrees, without anything fancy.
+
*[[Tween]] - An adaptation of the Tweener class of FLASH for unity.
+
 
+
= GUI =
+
 
+
== Graphical User Interface Scripts ==
+
 
+
*[[AutoType]] - Automaticly types a string of text typewriter style.
+
*[[Box_Script]] - Use this system to easily make simple GUI elements in nice looking boxes with buttons that actually do something useful. All generated at runtime from a MenuStyle.
+
*[[Button]] - Use this script on a guiTexture object for regular push buttons that send a message when clicked.
+
*[[Custom_2D_Pointer]] - Make a custom pointer that changes shape at the edges of the screen.
+
*[[Custom Mouse Pointer]] - Make a custom pointer that and draw it over OnGUI Elements.
+
*[[CustomScrollView]] - Helper-class that implements a scrollview where you can explicitly hide/show the scrollbars. Done with two nested groups
+
*[[DraggableGUIElement]] - Click and drag on GUITexture or GUIText to move it around the screen.
+
*[[DragSlider]] - Use this script with a pair of [http://otee.dk/Documentation/ScriptReference/GUITexture.html GUITexture]s to make a functioning slider.
+
*[[DMGInput]] - Passthrough for the Input.GetMouseButton* functions that will allow you to ignore clicks on registered GUI Rects. (Ex: Click on GUI, and not on the object behind in the scene.
+
*[[Fade]] - General routines that allow fading of GUITextures or materials (including GUITexts) from anywhere, both in and out and using either alpha or colors, with optional easing.
+
*[[FadeIn]] - Allows you to show/hide a [http://www.otee.dk/Documentation/ScriptReference/GUIText.html GUIText] or [http://www.otee.dk/Documentation/ScriptReference/GUITexture.html GUITexture] when pressing a key/button.
+
*[[ForwardAllMouseEvents]] - Send mouse events to some sort of controller type GameObject.
+
*[[GetTimeString]] - A simple function that can be placed anywhere and used to display times. Useful for racing games.
+
*[[GUIBuilder]] - Generic classes for easing the pain of GUI creation. (BETA)
+
*[[GUIFly]] - Use this script on an object to make it respond to a "Fly" message so that it may move on and off the screen in a pleasing manner.
+
*[[GUIHelpers]] - a simple static class for helpers, AlignRect to start.
+
*[[GuiRatioFixer]] - Use on a [http://otee.dk/Documentation/ScriptReference/GUIText.html GUIText] / [http://otee.dk/Documentation/ScriptReference/GUITexture.html GUITexture] object to automatically adjust aspect ratio
+
*[[GuiRatioFixer2]] - Alternate script based on screen's aspect to use on a [http://otee.dk/Documentation/ScriptReference/GUIText.html GUIText] / [http://otee.dk/Documentation/ScriptReference/GUITexture.html GUITexture] object to automatically adjust aspect ratio
+
*[[GUIScaler]] - Automatically scale a [http://otee.dk/Documentation/ScriptReference/GUITexture.html GUITexture] with the screen size / resolution
+
*[[GUITextField]] - A wrapper for GUI.TextField / GUILayout.TextField that implements focussing, allowing text to be "committed" only when the field is unfocussed (very useful for networking code).
+
*[[MainMenu]] - Shows how delegation works in C# in order to switch between different menus on the fly easily
+
*[[ObjectLabel]] - Makes a GUIText label follow an object in 3D space. Useful for things like having name tags over players' heads.
+
*[[ScaledRect]] - A static class that formats Rect values and rescales them based on output screen resolution, handy for dynamically scaling all OnGUI elements.
+
*[[ScreenShotMovie]] - Captures a screenshot sequence for use when making a movie
+
*[[SplashScreen]] - Fade a splash logo in, wait for a certain interval, then fade out, while the next level is loaded.
+
*[[TakeScreenshot]] - Captures sequentially numbered screenshots when a function key is pressed.
+
*[[Timer]] - Attach to a GUIText object to create a fade-able timer.
+
*[[ToggleButton]] - Extends the Button class to create a toggle button.
+
 
+
== Unity 2.0 GUI Scripts ==
+
 
+
*[[Blinking Text Entry Cursor]] - Make your cursor blink on input fields
+
*[[CustomGetMouseButtonDown]] - custom wrapper functions for Input.GetMouseButton(Down) which can be modified to block clicks when over a window
+
*[[DrawLine]] - Draws a line in the GUI (makes up for the severe lack of an equivalent function in the GUI class).
+
*[[DropDownList]] - A hierarchy based drop down list that works like the Hierarchy window in Unity.
+
*[[FileBrowser]] - Implement a crude file browser.
+
*[[GUICam]] - Holds GUIRect a rectanle of camera pixelRect in GUI oriented co-oridinates (0,0) is top left
+
*[[GUIExtensions]] - A library of GUI extensions to fill in some missing gaps.  Notably:  TextArea that auto-selects on focus.
+
*[[GUIx]] - extended GUI functions
+
*[[ImprovedFileBrowser]] - A much better file browser.
+
*[[ImprovedSelectionList]] - A list of elements that can be selected and optionally double-clicked
+
*[[IOSTextField]] - Text fields for iOS with specialized keyboard configurations
+
*[[Marquee]] - Creates a scrolling label that moves from left to right across the screen.
+
*[[PasswordField]] - Allows the user to type in a field masked by *'s (or any other character) [Unity has this built-in now.  Leaving it as an example of more complex widget construction, but shouldn't be preferred for actual usage.]
+
*[[PauseMenu]] - Standard pause menu used by Fugu Games for web players and widgets
+
*[[PopupList]] - A button that pops up a selectable list when clicked
+
*[[Position To Rect]] - Convert a GUITexture position to Rect (GUI coordinates)
+
*[[SelectList]] - A list of elements of which one can be selected.
+
*[[WithPrefs]] - Functions that change values and modifies preferences in one simple step
+
 
+
== Heads Up Display Scripts ==
+
 
+
*[[FramesPerSecond]] - Use this script on a [http://unity3d.com/Documentation/Components/class-GuiText.html GUIText] object to display FPS counter.
+
*[[MessageDisplayer]] - Use this script on a [http://unity3d.com/Documentation/Components/class-GuiText.html GUIText] object to have a self-disappearing list of status messages.
+
*[[MessageList]] - Create a list of timed self-fading messages.
+
*[[Radar]] - Use this script on a GameObject to display a radar.
+
 
+
== Editor GUI Scripts ==
+
 
+
*[[EditorGUIExtension]] - Some extensions to make coding the GUI for utilities/custom inspectors easier.
+
*[[TransformInspector]] - Reverse engineered version of the Unity 3 Transform component inspector. Makes extending the default inspector much easier.
+
*[[Custom Inspector Inspector]] - (snippet) Show a control for editing the custom inspector within the inspector itself. Handy while writing one.
+
 
+
= Effects =
+
 
+
== General Purpose Effect Scripts ==
+
 
+
*[[3D Physics Based Rope]] - Creates a rope using physics and the TubeRenderer (Use included modified code).
+
*[[Animating Tiled texture]] - A texture made of many tiles animated through setting the uv offsets
+
*[[Animating Tiled texture - Extended]] - Use one animation cell-sheet texture for many animations and skins.
+
*[[Animated Color Procedural Texture]] - A simple script to make limitless number of textures based on 2d graphs
+
*[[CameraFacingBillboard]] - Use this script on a billboard or similar object to make it align itself with the camera.
+
*[[CameraRenderSettings]] - Allows storing seperate render settings per camera - an extended version of the Fog Layer script above.
+
*[[Character Shadow]] - Cast shadows from an object! ''(requires Unity Pro)''
+
*[[DoFAutoFocus]] - An autofocus component for the Pro Depth of Field (DoF) Imageeffect ('''C#''')('''Pro''').
+
*[[Flickering Light]] - Adds flickering effect to Light object. Flicker styles are Campfire and Fluorescent.
+
*[[Flocking]] - A flocking script with randomness and target following.
+
*[[Fog Layer]] - Lets you determine per camera if fog should be enabled or disabled
+
*[[LineRenderer Rope]] - Creates a rope using physics and the LineRenderer component.
+
*[[LookAtCameraYonly]] - Use this script on a billboard or other object to have it face the camera but only rotate on the Y axis.
+
*[[MeleeWeaponTrail]] - A smoothed TrailRenderer meant for melee weapons of animated 3d models. Based on [[TimeBasedTrailRenderer]].
+
*[[MarchingSquares]] - MarchingSquares (2D Surface Reconstruction)
+
*[[MeshMorpher]] - A Mesh Morpher script with scripting API
+
*[[MetaBalls]] - 3D Metaballs
+
*[[MorphTargets]] - Improved MeshMorpher script with multiple blendable targets
+
*[[Noise Library]] - LibNoise ported to Unity. Perlin, Multirigged Fractal, Voronoi, Billow
+
*[[Open Source Particle System]] - A custom particle system that exposes particle movement deltaTime among other things.
+
*[[OptimizedTrailRenderer]] - Started from Yoggy's trail renderer above, this one updates every frame and is built for one-time use.
+
*[[Particle Spiral Effect]] - Particle effect script for creating spirals, whirlpools, galaxies, etc.
+
*[[Perlin Noise]] - Noise functions for smoothly moving objects around or anything else
+
*[[ReverseNormals]] - Reverses normals & back face culling of a mesh
+
*[[Scrolling UVs]] - C# script that smoothly scrolls a material's UVs in an arbitrary direction.  Supports arbitrary material names and material indices.
+
*[[SetRenderQueue]] - Sets the render queue for transparency sorting on an object or all of its children.
+
*[[Shadow Volumes in Alpha]] - Shadow volume based shadows ''(requires Unity Pro)''
+
*[[Skinned_Morph_Targets | Skinned Morph Targets]] - A set of scripts for morphing skinned meshes, including support for animating blend shapes together with skeletal animation.
+
*[[SoftBodies]] - Cloth, Springy Noodles, Jello Blocks, etc..
+
*[[StopEmittingAfterDelay]] - After a configurable delay, particles will fade naturally, then finally the object will get destroyed with autodestruct.
+
*[[Spline Controller]] - Interpolates any GameObject along a user-defined spline
+
*[[SVG]] - Render SVG Files.
+
*[[TextureMask]] - A simple shader for masking off areas of a texture.
+
*[[Texture swap animator]] - Feed it a bunch of textures and it will cycle through them. Useful for simple animations not on a texture atlas.
+
*[[TubeRenderer]] - LineRenderer too flat? Make it a tube instead.
+
*[[TimeBasedTrailRenderer]] - The Built in trail renderer does not fade its segments based on the time they have been alive. This one does.
+
*[[Trail Arc Renderer]] - Designed for melee trail swings, this creates a trail using Catmull-Rom spline interpolation
+
*[[Underwater Script]] - Simple underwater effects script. Works with indie!
+
*[[VectorLine]] - Renders a 2D vector line with an arbitrary width, color, and number of segments ''(requires Unity Pro)''
+
 
+
== Image Postprocessing Effects ==
+
 
+
These scripts require Unity Pro.
+
 
+
*[[BloomEffect]] (OBSOLETE) - Sometimes referred to as "glow", use this effect to make bright parts in your scene bleed.  This script is made obsolete by the GlowEffect shipped with Unity 1.5.
+
*[[BoostColors]] - A very simple and fast way to boost the contrast of saturation of the graphics in your game.
+
*[[InvertCamera]] - A simple script that will invert everything rendered by a camera.
+
 
+
= Physics / Simulation =
+
 
+
== Physics Scripts ==
+
 
+
*[[CollisionIgnoreManager]] - Script to manage ignoring collisions between groups of colliders.
+
*[[ComplicatedRigidbodyControl]] - Attach a rigidbody to an arbitrary transform, or a method to make rigidbodies never overshoot.
+
*[[DontGoThroughThings]] - Script that uses raycasting to avoid fast-moving objects going through obstructions.
+
*[[DragObject]] - Similar to DragRigidbody (drag rigidbodies around with the mouse), but much more stable and with more direct control.
+
 
+
== Simulation Scripts ==
+
 
+
*[[Compass]] - This script simulates a compass with North relative to the Z axis of a reference object
+
*[[DayNightController]] - Implements a Day/Night cycle relative to the game world, with a World-Time clock, and optional Direcitonal Light control.
+
*[[GameTime]] - This script rotates a directional light to match the rotation of the sun based on the system time.
+
*[[GPS Global Positioning System]] - This script simulates a GPS device providing real world GPS locations based on a reference point
+
*[[Gravity]] - Simulates body-to-body gravity (i.e. planetary gravity)
+
*[[IMU Inertial Measurement Unit]] - This script simulates an IMU providing velocities and accelerations of the object it is attached to in the objects local frame.
+
*[[OpenStreetMap for unity iPhone]] - A simple OpenStreetMap script for unity iPhone
+
*[[SICK Laser Scanner]] - This script simulates the SICK LMS type planar laser scanner
+
*[[Simple planetary orbits]] - Visually define the orbital path of one object around another fixed object, like a planet around the sun
+
*[[sunLight]] - A script that rotates a directional light based on longitude/latitude.
+
*[[Trajectory Simulation]] - Demonstrates simulating the trajectory of a launched object
+
*[[WheelColliderSource]] - Source code based off the Unity3D WheelCollider and associated classes.
+
 
+
= Networking =
+
 
+
*[[NetworkView_Position_Sync]] - Network position interpolation, extrapolation, packet timestamp preservation and more in non-authoritative applications
+
 
+
== WWW Scripts ==
+
 
+
*[[CookieCutter]] - Access browser cookies from Unity web players.
+
*[[FeedMe]] - A simple XML "feed" displayer which uses [[TinyXmlReader]]
+
*[[GetXMLHack]] - Get XML data into the web player using browser script instead of WWW() (which has been buggy for me!)
+
*[[Json]] - Another JSON script
+
*[[JSONParse]] - A robust, simple JSON Parser written in UnityJS.
+
*[[MeshSerializer2]] - Save Unity meshes to files for the Web, load them with WWW interface.
+
** [[MeshSerializer]] - an old version of the same (simpler format, but larger file sizes)
+
*[[MoreJSONScripts]] - Yet another JSON Script
+
*[[PlayerPrefsx]] - ( '''Now obsolete in Unity 2.1''') An extension to CookieCutter which allows you to save data in both standalones and cookies for the web without having to think about it.
+
*[[Server Side Highscores]] - A complete tutorial for implementing a server side php script for storing high scores and how to post the scores to the server.
+
*[[UnityLitJSON]] - A fork of [http://litjson.sourceforge.net/ LitJSON] that's been edited to work with Unity.
+
*[[UnityObject]] - A nice & clean way to embed .unityweb in your web browser. Plugin Detection, Communication, Clean HTML
+
*[[VersionCheck]] - A very basic version checker. This can be used to check if the version of the game the user is running is the latest, and if not, send them to a URL to download the latest.
+
 
+
== Unity 1.x Networking Scripts ==
+
 
+
*[[NetworkCursor]] - Serverless realtime networking. An example where one Unity instance controls another via a TCP/IP socket. Could be expanded to do many types of realtime networking.
+
*[[Sender]] - Uses a Server to send data from the parent object to whatever is on the other end of the connection.
+
*[[Server]] - TCP network host, based on NetworkCursor, but expanded to do more.
+
*[[Simple TCP/IP Client - Server]] - This contains source code for C# that you can use to create a server for Windows and a DLL in C# that you can use with Unity
+
 
+
= Sound =
+
 
+
*[[JukeboxController]] - A very basic jukebox class. This can be used to manage multiple audio clips across different levels.
+
*[[Loudness]] - Better control of AudioSource.volume and AudioListener.volume.
+
*[[Sound Manager]] - a simple jukebox script with crossfading and event-driven music "interrupts".
+
*[[Volume Slider]] - fade or increase a sounds volume smoothly over time
+
 
+
= Development =
+
 
+
== Debugging Scripts ==
+
 
+
*[[AllocationStats]] - Utility for showing how much memory your application has allocated.
+
*[[DetectLeaks]] - a simple GUI script for displaying the amount of objects currently loaded by type
+
*[[DebugConsole]] - A script to allow scrolling feedback from your scripts.
+
*[[DebuggerX]] - A simple javascript singleton that allows you to send debug to the console or the GUI
+
*[[DrawArrow]] - builds upon Debug.DrawRay() to add arrowheads at the tip
+
*[[NUnit]] - de-facto standard for unit testing in .NET
+
*[[Profiler]] - a simple c# script for profiling the performance of scripts, based on tags
+
*[[Reporter]] - a simple delayed action system info script that could be used for support purposes
+
*[[UUnit]] - a Simple xUnit framework that can be run inside Unity.
+
*[[SharpUnit]] - a unit testing framework adapted from UUnit but written in C#. Can also be run inside Unity3D.
+
 
+
== Performance Scripts ==
+
 
+
*[[CombineChildrenBones]] - Similar to MeshMerger, this script combines MeshFilter meshes into a single skinned mesh and then tracks transform changes
+
*[[CombineSkinnedMeshes]] - A Script that allows to combine multiple skinned meshes to just one SkinnedMeshRenderer. Useful for Avatar System!
+
*[[SkinMeshCombineUtility]] - Script to work with CombineSkinnedMeshes.
+
*[[SpriteManager]] - A script that allows many independently-moving 2D sprites to be drawn using a single draw call.  This is particularly useful to increase iPhone performance.
+
*[[StaticPerformanceOptimization]] - A script that optimizes performance statically based on the users graphics card by dropping terrain resolution and quality settings
+
 
+
== Editor Scripts ==
+
 
+
*[[AddChild]] - Adds an empty GameObject as a child of each selected object.
+
*[[AddComponentRecursively]] - Adds a component to an object, and all the children of that object.
+
*[[AssetPathPrinter]] - Prints to console and copys to clipboard asset paths for all selected project window items
+
*[[AutoMeshCollisionCreator]] - Automatically convert mesh from 3D Package into Mesh Collider on Import.
+
*[[AutoSave]] - Editor script for automatic saving the scene and assets with an interval.
+
*[[Bake Material to Texture]] - Allows to bake complex materials into a single texture. Can be useful for converting assets from Desktop to Mobile ('''Pro Only''')
+
*[[BoxColliderUtilities]] - Allows to scale or rotate BoxColliders side-aligned
+
*[[BuildAssetBundlesFromDirectory]] - Creates Asset Bundles from all files in a Directory ('''Pro Only''')
+
*[[Camera view window]] - Shows the rendered image of any camera that has this script on, the window is displayed inside the scene view.
+
*[[CopyTransform]] - Copies the local transform of the selected game instance in the scene and then pastes it into another one you select.
+
*[[CountLines]] - Count all the files and lines in your project
+
*[[CreateGameObjectLocal]] - Creates a new empty GameObject under the active GameObject (GameObject in the Inspector). Has Undo, menu shortcut and a prefab disconnection warning.
+
*[[CreatePrefabFromSelected]] - Creates a prefab containing the contents of the currently selected game object.
+
*[[Create project directories]] - Simple script which creates various directories under your Assets folder, best used when creating a new project.
+
*[[DeleteComponentsInChildren]] - Helps to delete a special type of components which are attached to the children of the selected Gameobject.
+
*[[DeleteMyPlayerPrefs]] - Deletes playerprefs for the editor via a menu item
+
*[[EdgeAlignerTool]] - A tool to align one or more edges of the AABB of a selected game object to those of the AABB of another selected game object
+
*[[EncloseTerrain]] - A simple script to enclose your terrain in a wall.
+
*[[ExportNormalmap]] - Exports the normalmap generated from a grayscale texture.
+
*[[ExportOBJ]] - Wraps the Utility script ObjExporter.cs (above), adding File/Export/Wavefront OBJ menu item.
+
*[[ExportVisualStudio]] - Creates Visual Studio 2005, 2008 and 2010 projects. Designed for minimal friction for non-techy people.
+
*[[Expose_properties_in_inspector]] - Small script collection which exposes properties ( get/set accessors ) in the inspector.
+
*[[FbxAnimListPostprocessor]] - Import a list of splitted animations for FBX 3D models.
+
*[[FindObjects]] - Find objects by name or attached component type.
+
*[[GetBBox]] - Find the bounding box of the selected game object (including any children)
+
*[[GetSize]] - Get the size in game units of a selection.
+
*[[HeightmapFromGridFloat]] - Applies the selected GridFloat file (topo data from USGS seamless server) as a heightmap to the active terrain.
+
*[[HeightmapFromTexture]] - Applies a selected texture as a heightmap to the active terrain.
+
*[[HierarchyFastHide]] - Makes list in window of game objects that have Mesh Renderer and adds toggle for user to turn it on and off. In Alpha State, but working with some limitations.
+
*[[HierarchySelectObject]] - Editor script that automatically selects and scrolls to the desired gameObject in the hierarchy window.
+
*[[InsertParent]] - An alternative to the built-in Make Parent command, this script inserts a new GameObject which becomes the parent of all selected objects.
+
*[[InvertSelection]] - Inverts the editors hierarchy selection
+
*[[iPhoneTextureImportSettings]] - iPhone specific script to change texture import settings for multiple textures at once.
+
*[[Layer Search]] - Search objects in the scene by Layer.
+
*[[LoadSceneAdditive]] - Loads a selected scene into the current scene. Good for copying scenes.
+
*[[Mac App Store PostProcessor]] - Post Processing Build Script to auto-sign and auto-package your game for the Mac App Store.
+
*[[Macros]] - Execute arbitrary code snippets.
+
*[[MassMaterialEditor]] - Affect the some settings of the RenderSettings and Materials of selected objects simultaneously.
+
*[[MassSetMaterials]] - Sets the materials of all selected objects simultaneously.
+
*[[Mesh2Collider]] - Use an external 3D app to model and place primitive colliders.
+
*[[MoveToOrigin]] - Moves the selected GameObject(s) to (0, 0, 0).
+
*[[MultipleObjectsToLayer]] - an editor utility that lets you move multiple selected objects into a layer at the same time.
+
*[[New Skybox Generator]] - Generates Skybox by rendering 6 images and combining them with skybox material. Select multiple scene objects to render Skyboxes from multiple locations. ('''Pro Only''')
+
*[[Normalize]] - Normalize terrain
+
*[[Notes]] - Allows you to add notes to any GameObject.
+
*[[Object2Terrain]] - Convert a standard mesh object to a Unity terrain.
+
*[[OpenVisualStudioProject]] - Open the current visual studio project (To launch Express).
+
*[[PixelLightMapper]] - A pixel based light mapper for Unity.
+
*[[RaiseHeightmap]] - Raises or lowers the entire terrain by a specified amount.
+
*[[REPL]] - Editor panel that lets you interactively edit and run C# code.
+
*[[SaveFontTexture]] - Saves auto-generated bitmaps that Unity makes from vector fonts as .png files so they can be edited externally
+
*[[SceneDumper]] - Dump information about the scene to a text file.
+
*[[CreateScriptableObjectAsset]] - Easily create an asset file of a ScriptableObject-inheriting class instance in Unity's intuitive style.
+
*[[SelectByComponent]] - Selects all gameobjects in the scene which have the declared component type attached.
+
*[[SetGOFlags]] - Set or Clear 'Static', 'Active', 'Cast Shadow', 'Receive Shadow' on selected objects (and their children)
+
*[[Skybox Generator]] - Generates the 6 images necessary to create a Skybox in Unity. ('''Pro Only''')
+
*[[SnapToGrid]] - Snaps objects to a grid in 3 dimensions.
+
*[[Take3DScreenshot]] - Take a "3d screenshot"; a series of screenshots captured while rotating around a given object. Useful for QTVR creation.
+
*[[TerrainImporter]] - Imports heightmaps and splatmaps from terrain applications.
+
*[[TerrainObjExporter]] - Exports Unity terrain objects as .obj files.
+
*[[TerrainPerlinNoise]] - Generates the terrain heights from a perlin noise function. **Warning: Uses Unity's undocumented Mathf.PerlinNoise() function. This may not work past Unity version 2.6.1**
+
*[[TextureImportSettings]] - Editor script to change texture import settings for multiple textures at once.
+
*[[ToggleActiveRecursively]] - Activates/deactivates entire hierarchies at once.
+
*[[ToggleActiveRecursivelyAllGameObjects]] - Activates/deactivates entire hierarchies at once and for all selected game objects.
+
*[[TransformUtilities]] - Includes tools to Align objects, copy, randomize and add noise to their transforms.
+
*[[WorldUVs]] - UV maps meshes in world space, allowing textures in separate meshes to seamlessly line up with each other.
+
*[[UPPEditor]] - PlayerPrefs-file-editor. Allows you to view and edit UPP files within Unity.
+
 
+
= External Links =
+
 
+
*[http://code.google.com/p/opensteerdotnet/ opensteer .NET]
+
*[http://ctrl-j.com.au/pages/jcarsrc.html Ctrl-J Sample Projects (wheel collider car and other stuff)]
+
*[http://marsxplr.com/view-1314 Mars Explorer Sample Project (offroad raycast car with buoyancy, flight, minimap, etc) ]
+
*[http://roidz.weebly.com/ Unity Custom Inputmanager:] Customize inputs from keyboard,mouse & joystick (xbox controller supported) on the fly - also for webgames.
+

Latest revision as of 20:29, 14 November 2018

Scripts   General   Editor   Controllers   UI   Effects   Physics/Simulation   Networking   Audio   Utility

[edit] Introduction

In this section you'll find a large assortment of sample scripts and code snippets contributed by members of the community. These can be accessed by selecting one of the category tabs above.

[edit] Contributions

Anyone is free to contribute their own original code to the wiki but you should keep a few things in mind when doing so:

  1. No Copyrighted Content - Code contributed must be either original or licensed in a way which allows sharing (e.g. public domain, open-source, etc.).
  2. Keep It Concise - Small scripts and code snippets are ideal. More complex code should be hosted on a platform like Bitbucket or GitHub instead.
  3. Use Proper Formatting - Please read the formatting help page before creating a new script. This will explain how to properly format and structure your code.

[edit] License

Unless otherwise specified, all code provided on the Wiki is licensed under Creative Common's Attribution-ShareAlike 3.0 Unported (CC BY-SA 3.0).

Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Toolbox