Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

[Scripts] Useful 4.6 Scripts Collection

Discussion in 'UGUI & TextMesh Pro' started by Melang, Aug 24, 2014.

  1. Melang

    Melang

    Joined:
    Mar 30, 2014
    Posts:
    166
    I decided to make this thread after I stumbled upon Riolis' window script. Please contribute any scripts that you think are useful when working with 4.6 UI. Also, don't forget about the cool scripts included in the UI Example Project, but I won't be listing them here.

    • UIWindowBase by Riolis - create draggable windows in 1 click - just drag this script to a panel with your window. Approved by Tim C :cool:
    • ReturnKeyTriggersButton - if put on an input field, makes pressing a Return key highlight and trigger a specified button. The highlight is optional.
    • TabNavigation - a temporary solution to Tab key currently not triggering the navigation to the next element. Should be placed on a persistent object in the scene, will trigger on all GUI elements. Works with "Select On Down" and all navigation types. By me, as is the previous script.
    • RayCastMask by senritsu - a must if you want to create a round button or a button of any other shape that's not rect. Change the button sprite texture to Advanced and check "Read/Write Enabled", then just add this script to your button.
    • ComboBox by jbooth - creates selection/dropdown lists for you! Especially useful since 4.6 won't have selection lists at the time of the release. Much like the official controls, it can be styled without any coding. I took the liberty to put the files in a .unitypackage for those who prefer it this way. Screenshot | Forum thread
    • uGUITools by Senshi - after you've resized a GUI element, positioning anchors to corners precisely can be difficult. With this script you can automatically position them from the menu or by pressing ctrl + [ , and do the reverse (corners to anchors) with ctrl + ] . Place the script in the Editor folder.
    • Interactable Text by Breyer - lets you add clickable links to your text! Instructions | Gif explanation
    • Accordion Type Layout by ChoMPi - if you're not familiar with accordion effect, take a look at the example video. Also has a collapsible version. Thread
    • RTS Style Selection Box by Korindian - the title is self-explanatory :) Thread
    • NicerOutline and BestFitOutline by me - a modified version of built-in Outline effect, but with a radius that scales along with Best Fit. Just use in place of the default outline, the radius that you set will be applied to the max font size, it will scale down from it when a smaller font is used. Screenshot NicerOutline also fixes the "holes" that Outline sometimes has - screenshot
    • Canvas Groups Activator by dakka - editor window, show and hide canvas groups
    • CurvedText by Breyer - lets you position the test on a curve for a cool effect!
    • Gradient Fill by Breyer - with a lot of possibilities like vertical, horizontal and diagonal gradient direction + global/local mode
    • ColorPicker by judah4 Screenshot
     

    Attached Files:

    Last edited: Oct 22, 2014
  2. jbooth

    jbooth

    Joined:
    Jan 6, 2014
    Posts:
    5,461
  3. Tim-C

    Tim-C

    Unity Technologies

    Joined:
    Feb 6, 2010
    Posts:
    2,221
    Melang and Exeneva like this.
  4. Melang

    Melang

    Joined:
    Mar 30, 2014
    Posts:
    166
    Thanks! Added both scripts to the list.
     
  5. jbooth

    jbooth

    Joined:
    Jan 6, 2014
    Posts:
    5,461
    The screenshot of the combo box is the "before" picture - the after one doesn't have all that junk in the hierarchy..
     
  6. Senshi

    Senshi

    Joined:
    Oct 3, 2010
    Posts:
    557
    Are Editor scripts allowed on the list? I had an annoyance in that, after positioning a UI element, I couldn't easily/ nicely/ precisely move the anchors to the element's corners. To that end I created a simple Editor script that adds a uGUI menubar item, with "Anchors to Corners" mapped to cmd+[ and "Corners to Anchors" mapped to cmd+]. Perhaps someone else will find this useful as well!

    EDIT: Updated version posted here.
     

    Attached Files:

    Last edited: Sep 25, 2014
    starikcetin, RaL, moghes and 11 others like this.
  7. Melang

    Melang

    Joined:
    Mar 30, 2014
    Posts:
    166
    Sure, added it to the list. Thanks!

    I've reached the max number of attachments in the first post, so gonna be adding the scripts as links to your attachments from now on.
     
    Last edited: Aug 29, 2014
  8. v21

    v21

    Joined:
    Jun 13, 2009
    Posts:
    9
  9. Freezy

    Freezy

    Joined:
    Jul 15, 2012
    Posts:
    234
    It would be nice to get a sample for how to get to the built in Images, or a way to initiate the default ui components with their graphics.

    This works as long as the images are already in the scene somewhere:
    Code (CSharp):
    1.  
    2. void GetImages() {
    3.         var images = Resources.FindObjectsOfTypeAll<Image>();
    4.         foreach( var image in images ) {
    5.             string name = image.name;
    6.             if( name.Contains( "Button" ) ) {
    7.                 buttonImage = image;
    8.                 Debug.Log( "Button set" );
    9.             } else if( name == "Panel" ) {
    10.                 panelImage = image;
    11.                 Debug.Log( "Panel set" );
    12.             } else {
    13.                 Debug.Log( name );
    14.             }
    15.         }
    16.     }
     
  10. Tim-C

    Tim-C

    Unity Technologies

    Joined:
    Feb 6, 2010
    Posts:
    2,221
    So the images live in the DefaultResourcesExtra package. What this means is that they only get included in a build if they are referenced by a scene / prefab that is included in the build. So if you want them included include them in some scene and then include that scene in the build... even if it is never used.
     
    narusuke15 likes this.
  11. Freezy

    Freezy

    Joined:
    Jul 15, 2012
    Posts:
    234
    Is there a way to load/retrieve them while within the editor? Or a way to instantiate the default properties for scripts.
    Creating a button currently involves a prefab or assigning a texture before hand. Creating custom controls would be easier to share / create if the workflow for adding them to the UI is the same.

    What I / we need is a way for the rightclick on gameobject in hierarchy, add UI / CustomControl to work identical to say UI / Button, where it populates the field with initial values. It's fine if we have to include some Editor only code here, it's just so that we can share a script instead of a whole package that just works out of the box without needing to assign some base textures manually.


    As an attribute this would rock
    [DefaultSprite("Button")]
    public Sprite image;
     
    Last edited: Aug 26, 2014
  12. Melang

    Melang

    Joined:
    Mar 30, 2014
    Posts:
    166
    Just wanted to say thanks to Senshi for this awesome "anchors to corners" solution. It allows to position anchors for stretching even when the parent rect is smaller than the child rect - totally impossible by default unless i missed something.

    This results in anchor values that are < 0 and >1 and they don't display correctly but they seem to work so far, nice!
     
    Senshi likes this.
  13. Senshi

    Senshi

    Joined:
    Oct 3, 2010
    Posts:
    557
    Ha, I found out about that unintended side-effect after posting as well! I was originally going to fix it as it doesn't seem very stable/ sustainable, but I hadn't gotten around to it yet. It also seems to save and load just fine, so... magic? Anyway, thanks for the thanks! =)
     
  14. dakka

    dakka

    Joined:
    Jun 25, 2010
    Posts:
    113
    Canvas Groups Activator editor window, show and hide canvas groups.

    Mod from Yilmaz Kiymaz's editor scripts presentation at Unite 2013
     

    Attached Files:

  15. Breyer

    Breyer

    Joined:
    Nov 10, 2012
    Posts:
    412
    Finally i decided to finish project with interactable text. check lighting scene in package and last sentence on screen. this is very little presentation but there is too late for more. maybe later i will add more explanation. I hope this is bug free (i bug hunted a lot) but i think it still could be optimized (i made some already but not 100%). If anyone need extends or optimize this i added some comment to code but this isnt very professional.

    maybe i will improve this but as Pro (paid version)

    NOTE: this not support fade-in/out like button and animation nor spriteswap (sprite of course isnt supported for text while animation will be added later if it is possible but probably as Pro)

    if u need link in text type <a href=nameAction>link</a> if u need dynamic color then type classic <color> before <a href> WARNING! use always html tag before link or u maybe see some strange shape in interactable area and color must be without "", with 8 length color declaration (never 6) and always first before link like <i><color=#ffffffff><a href=button>link</a></color></i>. This is due to optimization and no source code access constraint


    to install it - FIRST download unity ui example project into your project, delete old Lighting scene then download my package and open Lighting scene

    Enjoy!
     

    Attached Files:

    Last edited: Aug 29, 2014
  16. Breyer

    Breyer

    Joined:
    Nov 10, 2012
    Posts:
    412
    I created gif which explain how my package should look and behave in play mode

    activetext1.gif

    BTW i forgot to add that child button for text should have identical rect to parent (and recommend adjust anchors to parents corner

    @Melang

    Exactly
     
    Last edited: Aug 29, 2014
    IntDev and Melang like this.
  17. Melang

    Melang

    Joined:
    Mar 30, 2014
    Posts:
    166
    Just tested your package and it works great, thanks for sharing this with the community. With this, everyone can start making WoW-style chat links, and ingame encyclopedias. :)
     
  18. Melang

    Melang

    Joined:
    Mar 30, 2014
    Posts:
    166
    Here's a modified Outline script, its radius scales along with Best Fit font scale. By default, when outlined text gets scaled down, its outline radius remains the same, and can look too bold, this fixes it.
     

    Attached Files:

    Last edited: Aug 30, 2014
  19. [RV]CWolf

    [RV]CWolf

    Joined:
    Jan 24, 2013
    Posts:
    33
    Some excellent additions here at the moment. I can't wait for the source to be released and see where the community helps take uGUI =).
     
  20. Ippokratis

    Ippokratis

    Joined:
    Oct 13, 2008
    Posts:
    1,521
    Senshi likes this.
  21. Supergeek

    Supergeek

    Joined:
    Aug 13, 2010
    Posts:
    103
    Anchors to Corners and vice versa are very useful, thanks!
     
    Senshi likes this.
  22. rakkarage

    rakkarage

    Joined:
    Feb 3, 2014
    Posts:
    683
    sort children by z in hierarchy

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Linq;
    3. public static class GameObjectExtensions
    4. {
    5.     public static void SortChildren(this GameObject gameObject)
    6.     {
    7.         var children = gameObject.GetComponentsInChildren<Transform>(true);
    8.         var sorted = from child in children
    9.                      orderby child.gameObject.activeInHierarchy descending, child.localPosition.z descending
    10.                      where child != gameObject.transform
    11.                      select child;
    12.         for (int i = 0; i < sorted.Count(); i++)
    13.         {
    14.             sorted.ElementAt(i).SetSiblingIndex(i);
    15.         }
    16.     }
    17. }
    18.  
    Code (CSharp):
    1. gameObject.SortChildren();
     
    Senshi likes this.
  23. JPOnion

    JPOnion

    Joined:
    Aug 11, 2014
    Posts:
    7
    These are great!

    Quick question about the UIWindowBase script. Does this work when the canvas is set to world canvas? I've been trying to get this to work on mine, but either it doesn't work for world canvas or I'm doing something wrong.
     
  24. SilentWarrior

    SilentWarrior

    Joined:
    Aug 3, 2010
    Posts:
    107
    Hello.

    Simple drag'n'drop scrollview mouse wheel scroll.

    Create a C# script named MouseScrollRect and paste in the code :
    Simpler version..
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3. using UnityEngine.EventSystems;
    4.  
    5. [RequireComponent (typeof(ScrollRect)), RequireComponent (typeof(EventTrigger))]
    6. public class MouseScrollRect : MonoBehaviour, IScrollHandler
    7. {
    8.         ScrollRect scroller;
    9.  
    10.         void Start ()
    11.         {
    12.                 scroller = GetComponent<ScrollRect> ();
    13.  
    14.         }
    15.  
    16.         public void OnScroll (PointerEventData eventData)
    17.         {
    18.                 scroller.verticalNormalizedPosition += eventData.scrollDelta.y;
    19.         }
    20. }
    21.  
    Old version
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3. using UnityEngine.EventSystems;
    4.  
    5. [RequireComponent (typeof(ScrollRect)), RequireComponent (typeof(EventTrigger)), ExecuteInEditMode]
    6. public class MouseScrollRect : MonoBehaviour
    7. {
    8.  
    9.         ScrollRect scroller;
    10.         EventTrigger trigger;
    11.         // Use this for initialization
    12.         void Start ()
    13.         {
    14.                 scroller = GetComponent<ScrollRect> ();
    15.                 trigger = GetComponent<EventTrigger> ();
    16.  
    17.                 EventTrigger.TriggerEvent evt = new EventTrigger.TriggerEvent ();
    18.                 EventTrigger.Entry entry = new EventTrigger.Entry ();
    19.                 entry.callback = evt;
    20.                 entry.eventID = EventTriggerType.Scroll;
    21.                 evt.AddListener (onScroll);
    22.      
    23.                 trigger.delegates.Add (entry);
    24.  
    25.         }
    26.  
    27.         public void onScroll (BaseEventData BaseEventData)
    28.         {
    29.                 PointerEventData e = BaseEventData as PointerEventData;
    30.                 scroller.verticalNormalizedPosition += e.scrollDelta.y;
    31.         }
    32.  
    33. }
    34.  
     
    Last edited: Sep 12, 2014
    Melang likes this.
  25. orb

    orb

    Joined:
    Nov 24, 2010
    Posts:
    3,037
    I made an alternative to the input module in the default EventSystem, with additional support for right+middle mouse buttons. It's good enough to use until it's properly implemented in a later beta, and supports toggling drag support for the extra buttons if you want to support RMB/MMB drag for some special use. It's not 100% robust, in that it might confuse up events if you ram the whole bunch of buttons. But that's your own damn fault :)

    The required scripts:
    1. MouseInputModule.cs: https://gist.github.com/Urethramancer/65cb7e16a489fdd11c01
    2. ExtraMouseevents.cs: https://gist.github.com/Urethramancer/a35bdbdd7de030f6f487
    3. IExtraMouseEventsHandler.cs: https://gist.github.com/Urethramancer/77a2df0658373d81aa5c
    They add six new interfaces to implement. You'll figure them out from looking at the source :)
     
    Melang likes this.
  26. Adam-Buckner

    Adam-Buckner

    Joined:
    Jun 27, 2007
    Posts:
    5,664
  27. SilentWarrior

    SilentWarrior

    Joined:
    Aug 3, 2010
    Posts:
    107
    I am adding here a simpler version of the scroll view mouse wheel scroller, but this or the first version, does not work very good.

    If anyone can improve on it, please do so, and post here the result.

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3. using UnityEngine.EventSystems;
    4.  
    5. [RequireComponent (typeof(ScrollRect)), RequireComponent (typeof(EventTrigger))]
    6. public class MouseScrollRect : MonoBehaviour, IScrollHandler
    7. {
    8.         ScrollRect scroller;
    9.  
    10.         void Start ()
    11.         {
    12.                 scroller = GetComponent<ScrollRect> ();
    13.  
    14.         }
    15.  
    16.         public void OnScroll (PointerEventData eventData)
    17.         {
    18.                 scroller.verticalNormalizedPosition += eventData.scrollDelta.y;
    19.         }
    20. }
    21.  
     
  28. baustin27

    baustin27

    Joined:
    Feb 21, 2014
    Posts:
    12

    Is there a way to sort alphanumerically?
     
  29. rakkarage

    rakkarage

    Joined:
    Feb 3, 2014
    Posts:
    683
    check this option
    1.png
    and new button on top of hierarchy
    Untitled.png
     
    pea likes this.
  30. GibTreaty

    GibTreaty

    Joined:
    Aug 25, 2010
    Posts:
    792
  31. baustin27

    baustin27

    Joined:
    Feb 21, 2014
    Posts:
    12
    Nice, thank you, I should have been more specific sorry, but is there a way to sort and alphabetize buttons and toggles in a layout grid for ugui?
     
  32. Freezy

    Freezy

    Joined:
    Jul 15, 2012
    Posts:
    234
    try setting sibling index of the items you need sorted.
    Easiest way is to add the items to a list, then sort the list, then set the transform.SetSiblingIndex
     
  33. Breyer

    Breyer

    Joined:
    Nov 10, 2012
    Posts:
    412
    Finally, I created timer called UnityTimer (to match with UnityEvent like calling).

    there is one important but subtle feature - if you start UnityTimer first time in your code you MUST use Start(Monobehaviour) overload. This allow you to pause coroutine via disabling monobehaviour which was sent via Start(Monobehaviour) and resume via enabling same monobehaviour

    Recommendation: use UnityTimer as property if u need complex control over timer otherwise use simple Timer component - this class derive from Monobehaviour so could be attached to GO.

    Note: unfortunetly unity doesnt support simple unscaled coroutine so be sure ur timer havent to be unity time independent.... ah and place TimerHandler script in Editor folder
     

    Attached Files:

  34. Breyer

    Breyer

    Joined:
    Nov 10, 2012
    Posts:
    412
    Hi again i created Curved text effect. its may look really fine and fun see my screenshot

    curvetext.png

    actually, i try extend gradient fill effect (horizontal/vertical/diagonal fill)

    UPDATE:

    i figured out old curved text effect was a bit pain in the ass in configure because of ridiculous scale dimension in curve field like 500 (width of text rect) in x dim against 1 in y dim. Unfortunetly this is impossible to change without drawback (as far as i know). So i created modified effect but this have another drawback - on first attach it change line of text to uneven but curve field is now more fine in controlling. probably i will create special editor ext which will remove these inconvenience but later

    UPDATE 1:

    there is temporal solution: press shift during zooming curve. so i decided to delete modified version
     

    Attached Files:

    Last edited: Sep 17, 2014
    GibTreaty, MaxEden and Kogar like this.
  35. Breyer

    Breyer

    Joined:
    Nov 10, 2012
    Posts:
    412
    Next extension: extended gradient fill effect. I added a lot possibilities like vertical, horizontal and diagonal gradient direction + global/local mode (useful only with text, for image there is no differencies)

    see example

    local vertical
    localVertical.JPG

    global vertical
    globalVertical.JPG

    NOTE:

    if you use my curved text effect you should be carefull with effect ordering - previous image was made with gradient THEN curved text. See difference if we reverse order:

    diffbetweenordering.JPG

    this is very subtle but still noticeable....
     

    Attached Files:

    Last edited: Sep 19, 2014
    Melang and rakkarage like this.
  36. ChoMPi

    ChoMPi

    Joined:
    Jul 11, 2013
    Posts:
    112
    Might be a good idea to multiply the vertex color by the color you are applying for the gradient effect, this should allow you to have a base color and gradient on top of it : ]
     
  37. Breyer

    Breyer

    Joined:
    Nov 10, 2012
    Posts:
    412
    yeah you are right, fortunetly change this was very easy. I update previous gradient (now, multiplying is default) and text looks better now ;) thanks for feedback!


    identical setup but multiply color:

    multiplyGradient.JPG
     
    Last edited: Sep 19, 2014
  38. Breyer

    Breyer

    Joined:
    Nov 10, 2012
    Posts:
    412
    I added new checkbox OverwriteAllColor. see difference if checkbox is false

    overwriteallcolor.JPG

    this is useful if you use different <color> tags and you need expose them
     
  39. Breyer

    Breyer

    Joined:
    Nov 10, 2012
    Posts:
    412
    Sorry for many post in a row but i found showstopper bug: if base color of text or image was different than white then with OverwriteAllColor setted as false Gradient effect may disappear very often. This was caused by fact base color of image/text and vertex color of image/text are different but difference was really small like 0.002-3f while i compared base color vs vertex color for avoid overwrite color from <color> tag. I think this is bug in unity but not sure this may be nature of float point as well. So i wrote custom comparer and bug disappear - im not sure if 100% cases are bug free though....

    Please redownload new version in first post of Gradient
     
  40. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,447
    Universal window script. Works with any kind of canvas, orientation doesn't matter.

    Code (csharp):
    1. using System;
    2. using UnityEngine;
    3. using UnityEngine.EventSystems;
    4.  
    5. public class UIWindow : MonoBehaviour, IDragHandler
    6. {
    7.     private RectTransform rectTransform;
    8.     private Canvas canvas;
    9.     private RectTransform canvasRectTransform;
    10.  
    11.     private void Start()
    12.     {
    13.         rectTransform = GetComponent<RectTransform>();
    14.         canvas = GetComponentInParent<Canvas>();
    15.         canvasRectTransform = canvas.GetComponent<RectTransform>();
    16.     }
    17.  
    18.     public void OnDrag(PointerEventData eventData)
    19.     {
    20.         var delta = ScreenToCanvas(eventData.position) - ScreenToCanvas(eventData.position - eventData.delta);
    21.         rectTransform.localPosition += delta;
    22.     }
    23.  
    24.     private Vector3 ScreenToCanvas(Vector3 screenPosition)
    25.     {
    26.         Vector3 localPosition;
    27.         Vector2 min;
    28.         Vector2 max;
    29.         var canvasSize = canvasRectTransform.sizeDelta;
    30.  
    31.         if (canvas.renderMode == RenderMode.Overlay || (canvas.renderMode == RenderMode.OverlayCamera && canvas.worldCamera == null))
    32.         {
    33.             localPosition = screenPosition;
    34.  
    35.             min = Vector2.zero;
    36.             max = canvasSize;
    37.         }
    38.         else
    39.         {
    40.             var ray = canvas.worldCamera.ScreenPointToRay(screenPosition);
    41.             var plane = new Plane(canvasRectTransform.forward, canvasRectTransform.position);
    42.  
    43.             float distance;
    44.             if (plane.Raycast(ray, out distance) == false)
    45.             {
    46.                 throw new Exception("Is it practically possible?");
    47.             };
    48.             var worldPosition = ray.origin + ray.direction * distance;
    49.             localPosition = canvasRectTransform.InverseTransformPoint(worldPosition);
    50.  
    51.             min = -Vector2.Scale(canvasSize, canvasRectTransform.pivot);
    52.             max = Vector2.Scale(canvasSize, Vector2.one - canvasRectTransform.pivot);
    53.         }
    54.  
    55.         // keep window inside canvas
    56.         localPosition.x = Mathf.Clamp(localPosition.x, min.x, max.x);
    57.         localPosition.y = Mathf.Clamp(localPosition.y, min.y, max.y);
    58.  
    59.         return localPosition;
    60.     }
    61. }
     
    Last edited: Sep 19, 2014
    CaoMengde777 and Melang like this.
  41. CaoMengde777

    CaoMengde777

    Joined:
    Nov 5, 2013
    Posts:
    813
    thanks Alexzzzz !! just what i was looking for!!
    i made this change for convenience, to keep the window inside the canvas by x pixels .. so user doesnt lose the panel, the way you have it remains by like 1 pixel, which some may like, but i didnt .. , im using 20... 5 seemed like ok default, lol:

    Code (CSharp):
    1. public int keepWindowInCanvas = 5;            // # of pixels of the window that must stay inside the canvas view.
    2.  
    3.  
    4.  
    5. // keep window inside canvas
    6. localPosition.x = Mathf.Clamp(localPosition.x, min.x + keepWindowInCanvas, max.x - keepWindowInCanvas);
    7. localPosition.y = Mathf.Clamp(localPosition.y, min.y + keepWindowInCanvas, max.y - keepWindowInCanvas);
     
  42. TroyDavis

    TroyDavis

    Joined:
    Mar 27, 2013
    Posts:
    78
    I still prefer the simplicity of Riolis UIWindowBase.cs Code.

    It works fine for me using the Reference Resolution script on my Canvas.

    I did however add a reset for the the objects to return them to their original positions in case the user dragged them off the canvas and dropped them where they could not be seen.

    Simply set ResetCoords = true;
    on the object the script is attached too.

    Code (csharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3. using UnityEngine.EventSystems;
    4. using System.Collections;
    5.  
    6. public class UIWindowBase : MonoBehaviour, IDragHandler
    7. {
    8.     public static bool ResetCoords = false;
    9.     private RectTransform m_transform = null;
    10.     private Vector3 originalCoods = Vector3.zero;
    11.  
    12.     // Use this for initialization
    13.     void Start () {
    14.         m_transform = GetComponent<RectTransform>();
    15.         originalCoods = m_transform.position;
    16.     }
    17.  
    18.    void Update(){
    19.         if(ResetCoords)
    20.             resetCoords();
    21.     }
    22.  
    23.     public void OnDrag(PointerEventData eventData)
    24.     {
    25.         m_transform.position += new Vector3(eventData.delta.x, eventData.delta.y);
    26.    
    27.         // magic : add zone clamping if's here.
    28.     }
    29.  
    30.     void resetCoords(){
    31.         m_transform.position = originalCoods;
    32.         ResetCoords = false;
    33.     }
    34. }
     
    Last edited: Sep 21, 2014
  43. nhf75

    nhf75

    Joined:
    Apr 5, 2013
    Posts:
    35
    Hi CaoMenengde777,
    I'm using other way to keep the window inside the canvas. The signals (Screen.width - lim.sizeDelta.x) will depend on the anchor point.
    Sorry for my english.


    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3. using UnityEngine.EventSystems;
    4. using System.Collections;
    5.  
    6. public class UIWindowBase : MonoBehaviour, IDragHandler
    7. {
    8.         RectTransform m_transform = null;
    9.    
    10.         // Use this for initialization
    11.         void Start ()
    12.         {
    13.                 m_transform = GetComponent<RectTransform> ();
    14.         }
    15.    
    16.         public void OnDrag (PointerEventData eventData)
    17.         {
    18.                 m_transform.position += new Vector3 (eventData.delta.x, eventData.delta.y);
    19.                 Limit (m_transform);
    20.                 // magic : add zone clamping if's here.
    21.         }
    22.  
    23.         RectTransform Limit (RectTransform lim)
    24.         {
    25.                 lim.anchoredPosition = new Vector2 (Mathf.Clamp (lim.anchoredPosition.x, 0,Screen.width - lim.sizeDelta.x), Mathf.Clamp (lim.anchoredPosition.y, 0, Screen.height - lim.sizeDelta.y));
    26.                 return lim;
    27.         }
    28. }
     
  44. Erisat

    Erisat

    Joined:
    Jan 31, 2013
    Posts:
    88
    This thread should be a sticky and be at the top of this forum. Some very useful scripts here :)
    I have nothing to do with this script, but I like it. Definitely belongs on this list: http://forum.unity3d.com/threads/color-picker.267043/

    Kudos to all of you who have developed these scripts, and also to OP for making this thread :D
     
    judah4 likes this.
  45. apatheteec

    apatheteec

    Joined:
    Mar 21, 2014
    Posts:
    1
    I signed in just to express how much time I saved and will save because of this.
    Thanks a lot Senshi!
     
    Senshi likes this.
  46. Orbcreation

    Orbcreation

    Joined:
    May 4, 2010
    Posts:
    231
    I made a little package that includes some of my UI extensions.

    An enhanced slider that interacts with an accompanying input field:
    - set the nr of decimals,
    - set whether in between values are allowed (like Slider.wholeNumbers, but also with nr of decimals)
    - prevent receiving in between onValueChanged messages while the slider is still being pulled (in case the actions connected to onValueChanged are too heavy to perform every frame)

    Some simple, but useful extensions to RectTransform:
    - set width and height without having to figure out the new offsetMin, offsetMax values.
    - position the RectTransform on an exact position, regardless of the pivot, anchors and offsets

    A fix for the InputField caret not being aligned with the text when the pivot is not 0.5, 0.5

    I also made a handy listbox, but that is already in the assetstore
    Schermafbeelding 2014-09-24 om 08.54.46.png
     

    Attached Files:

  47. Senshi

    Senshi

    Joined:
    Oct 3, 2010
    Posts:
    557
    Awesome, glad to hear you found it useful! And thanks for taking the time to let me know! =)

    I completely forgot to post this earlier, but I've since updated my uGUI Tools script for anyone who's interested. It's a pretty minor change, but it now works for multiple selected items as well, which can be a bit of a timesaver sometimes.

    I've also added some mirroring tools (Mirror Around Anchors and Mirror Around Parent Center), thought I'm not sure how useful these are for general use.

    (@Melang Could you update the link in your main post please? =))
     

    Attached Files:

    Last edited: Sep 25, 2014
  48. judah4

    judah4

    Joined:
    Feb 6, 2011
    Posts:
    256
    This is a very helpful thread, thank you.
     
  49. Freezy

    Freezy

    Joined:
    Jul 15, 2012
    Posts:
    234
    I did a quick test to see if I could improve shadows somehow, trying to keep away from an 8 sided shadow.
    Using a shader does not result in knowing which pixels are on the edges of letters.
    It would be really nice if Unity just added some more features to the runtime font generation pipeline.
    Or just gave an example of how we could hook into glyph generation on runtime.


    Either way here is an example for adding custom vertices to the ui text.
    You can copy or alter those that are in verts or create your own.
    The uv coordinates apply to the glyph you are rendering.
    Adding to the front takes a lot of time and sadly the list we are passed is a reference but was not passed as ref, so if we want to add to the front we need to flip flop the arrays arround.

    Code (CSharp):
    1.  
    2.  
    3. #warning THE BELOW EXAMPLE DOES NOT RESULT IN A PRETTY SHADOW
    4. #warning it can however be used as an example for how to manipulate / add vertices to the List
    5.  
    6. using System;
    7. using System.Collections.Generic;
    8. namespace UnityEngine.UI {
    9.  
    10.     [AddComponentMenu( "UI/Effects/Scaled Outline", 16 )]
    11.     public class ScaledOutline : BaseVertexEffect {
    12.         public Color effectColor;
    13.         public Vector3 effectDistance;
    14.  
    15.         //temporary data
    16.         private Vector3 center;
    17.  
    18.         public override void ModifyVertices( List<UIVertex> verts ) {
    19.             if( !this.IsActive() ) {
    20.                 return;
    21.             }
    22.  
    23.             //assupmtions: one glyph = 4 verts
    24.             //scale around the center of the 4 verts might result in a nicer shadow
    25.             //scaling up for outer shadow
    26.             //scaling down for inner shadow
    27.  
    28.             //todo calc this based on camera settings, only usefull when you are using a z aware shader
    29.             float zOffset = effectDistance.z;
    30.  
    31.             List<UIVertex> newverts = new List<UIVertex>();
    32.  
    33.             //base count
    34.             int count = verts.Count;
    35.             verts.Capacity = count * 2;
    36.             for( int glyph = 0; glyph < count; glyph += 4 ) {
    37.                 var a = verts[glyph];
    38.                 var b = verts[glyph + 1];
    39.                 var c = verts[glyph + 2];
    40.                 var d = verts[glyph + 3];
    41.  
    42.                 a.color = effectColor;
    43.                 b.color = effectColor;
    44.                 c.color = effectColor;
    45.                 d.color = effectColor;
    46.  
    47.                 center = (a.position + b.position + c.position + d.position) * 0.25f;
    48.                 center.z -= zOffset;
    49.  
    50.                 //outer scale
    51.                 //effectDistance.x
    52.                 //inner scale
    53.                 //effectDistance.y
    54.  
    55.                 // final = center + ((position - center) * distanceFactor);
    56.  
    57.                 //get offsets to center
    58.                 a.position -= center;
    59.                 b.position -= center;
    60.                 c.position -= center;
    61.                 d.position -= center;
    62.  
    63.                 //copy now that they are in offset mode
    64.                 var e = a;
    65.                 var f = b;
    66.                 var g = c;
    67.                 var h = d;
    68.  
    69.                 var i = a;
    70.                 var j = b;
    71.                 var k = c;
    72.                 var l = d;
    73.  
    74.                 Vector2 factors = effectDistance;
    75.  
    76.                 //scaled outer
    77.                 ApplyShadow( newverts, ref a, effectDistance.x, effectDistance.x );
    78.                 ApplyShadow( newverts, ref b, effectDistance.x, effectDistance.x );
    79.                 ApplyShadow( newverts, ref c, effectDistance.x, effectDistance.x );
    80.                 ApplyShadow( newverts, ref d, effectDistance.x, effectDistance.x );
    81.              
    82.                 //horizontal inner
    83.                 ApplyShadow( newverts, ref e, effectDistance.x, effectDistance.y );
    84.                 ApplyShadow( newverts, ref f, effectDistance.x, effectDistance.y );
    85.                 ApplyShadow( newverts, ref g, effectDistance.x, effectDistance.y );
    86.                 ApplyShadow( newverts, ref h, effectDistance.x, effectDistance.y );
    87.  
    88.                 //vertical inner
    89.                 ApplyShadow( newverts, ref i, effectDistance.y, effectDistance.x );
    90.                 ApplyShadow( newverts, ref j, effectDistance.y, effectDistance.x );
    91.                 ApplyShadow( newverts, ref k, effectDistance.y, effectDistance.x );
    92.                 ApplyShadow( newverts, ref l, effectDistance.y, effectDistance.x );
    93.             }
    94.  
    95.             //background vertices need to be rendered first when using non-zwrite shaders
    96.             newverts.AddRange( verts );
    97.  
    98. // newverts is now correctly sorted for z independent rendering, sad panda would like verts to have been ref
    99. // verts = newverts;
    100.  
    101. //but instead we need to do:
    102.             verts.Clear();
    103.             verts.AddRange( newverts );  
    104.         }
    105.  
    106.         private void ApplyShadow( List<UIVertex> newverts, ref UIVertex vert, float xFactor, float yFactor ) {
    107.             vert.position.x *= xFactor;
    108.             vert.position.y *= yFactor;
    109.             vert.position += center;
    110.             newverts.Add( vert );
    111.         }
    112.     }
    113. }
    114.  
    Again, the above code is only useful as an example for adding custom shadows, raw scaling just does not play nice with letters like aopq.
     
  50. Melang

    Melang

    Joined:
    Mar 30, 2014
    Posts:
    166