[Scripts] Useful 4.6 Scripts Collection

Anchors to Corners and vice versa are very useful, thanks!

1 Like

sort children by z in hierarchy

using UnityEngine;
using System.Linq;
public static class GameObjectExtensions
{
    public static void SortChildren(this GameObject gameObject)
    {
        var children = gameObject.GetComponentsInChildren<Transform>(true);
        var sorted = from child in children
                     orderby child.gameObject.activeInHierarchy descending, child.localPosition.z descending
                     where child != gameObject.transform
                     select child;
        for (int i = 0; i < sorted.Count(); i++)
        {
            sorted.ElementAt(i).SetSiblingIndex(i);
        }
    }
}
gameObject.SortChildren();
1 Like

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.

Hello.

Simple drag’n’drop scrollview mouse wheel scroll.

Create a C# script named MouseScrollRect and paste in the code :
Simpler version…

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

[RequireComponent (typeof(ScrollRect)), RequireComponent (typeof(EventTrigger))]
public class MouseScrollRect : MonoBehaviour, IScrollHandler
{
        ScrollRect scroller;

        void Start ()
        {
                scroller = GetComponent<ScrollRect> ();

        }

        public void OnScroll (PointerEventData eventData)
        {
                scroller.verticalNormalizedPosition += eventData.scrollDelta.y;
        }
}

Old version

```csharp
~~using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

[RequireComponent (typeof(ScrollRect)), RequireComponent (typeof(EventTrigger)), ExecuteInEditMode]
public class MouseScrollRect : MonoBehaviour
{

    ScrollRect scroller;
    EventTrigger trigger;
    // Use this for initialization
    void Start ()
    {
            scroller = GetComponent<ScrollRect> ();
            trigger = GetComponent<EventTrigger> ();

            EventTrigger.TriggerEvent evt = new EventTrigger.TriggerEvent ();
            EventTrigger.Entry entry = new EventTrigger.Entry ();
            entry.callback = evt;
            entry.eventID = EventTriggerType.Scroll;
            evt.AddListener (onScroll);
 
            trigger.delegates.Add (entry);

    }

    public void onScroll (BaseEventData BaseEventData)
    {
            PointerEventData e = BaseEventData as PointerEventData;
            scroller.verticalNormalizedPosition += e.scrollDelta.y;
    }

}~~
```

1 Like

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 :slight_smile:

The required scripts:

They add six new interfaces to implement. You’ll figure them out from looking at the source :slight_smile:

1 Like

I’ve added a sample “pause” script in this thread:

See it in action as part of our live training archive:

3 Likes

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.

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

[RequireComponent (typeof(ScrollRect)), RequireComponent (typeof(EventTrigger))]
public class MouseScrollRect : MonoBehaviour, IScrollHandler
{
        ScrollRect scroller;

        void Start ()
        {
                scroller = GetComponent<ScrollRect> ();

        }

        public void OnScroll (PointerEventData eventData)
        {
                scroller.verticalNormalizedPosition += eventData.scrollDelta.y;
        }
}

Is there a way to sort alphanumerically?

check this option
1771787--112314--1.png
and new button on top of hierarchy
1771787--112315--Untitled.png

1 Like

Here is a Joystick that I’ve made for uGUI

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?

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

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

1776125–112642–UnityTimer.cs (1.4 KB)
1776125–112643–Timer.cs (536 Bytes)
1776125–112644–TimerHandler.cs (2.25 KB)

Hi again i created Curved text effect. its may look really fine and fun see my screenshot

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

1777407–112768–CurvedText.cs (1.69 KB)

3 Likes

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
1780095--112996--localVertical.JPG

global vertical
1780095--112997--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:

1780095--112998--diffbetweenordering.JPG

this is very subtle but still noticeable…

1780095–113056–Gradient.cs (3.1 KB)

2 Likes

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 : ]

yeah you are right, fortunetly change this was very easy. I update previous gradient (now, multiplying is default) and text looks better now :wink: thanks for feedback!

identical setup but multiply color:

1780166--113009--multiplyGradient.JPG

I added new checkbox OverwriteAllColor. see difference if checkbox is false

1780221--113026--overwriteallcolor.JPG

this is useful if you use different tags and you need expose them

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 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

Universal window script. Works with any kind of canvas, orientation doesn’t matter.

using System;
using UnityEngine;
using UnityEngine.EventSystems;

public class UIWindow : MonoBehaviour, IDragHandler
{
    private RectTransform rectTransform;
    private Canvas canvas;
    private RectTransform canvasRectTransform;

    private void Start()
    {
        rectTransform = GetComponent<RectTransform>();
        canvas = GetComponentInParent<Canvas>();
        canvasRectTransform = canvas.GetComponent<RectTransform>();
    }

    public void OnDrag(PointerEventData eventData)
    {
        var delta = ScreenToCanvas(eventData.position) - ScreenToCanvas(eventData.position - eventData.delta);
        rectTransform.localPosition += delta;
    }

    private Vector3 ScreenToCanvas(Vector3 screenPosition)
    {
        Vector3 localPosition;
        Vector2 min;
        Vector2 max;
        var canvasSize = canvasRectTransform.sizeDelta;

        if (canvas.renderMode == RenderMode.Overlay || (canvas.renderMode == RenderMode.OverlayCamera && canvas.worldCamera == null))
        {
            localPosition = screenPosition;

            min = Vector2.zero;
            max = canvasSize;
        }
        else
        {
            var ray = canvas.worldCamera.ScreenPointToRay(screenPosition);
            var plane = new Plane(canvasRectTransform.forward, canvasRectTransform.position);

            float distance;
            if (plane.Raycast(ray, out distance) == false)
            {
                throw new Exception("Is it practically possible?");
            };
            var worldPosition = ray.origin + ray.direction * distance;
            localPosition = canvasRectTransform.InverseTransformPoint(worldPosition);

            min = -Vector2.Scale(canvasSize, canvasRectTransform.pivot);
            max = Vector2.Scale(canvasSize, Vector2.one - canvasRectTransform.pivot);
        }

        // keep window inside canvas
        localPosition.x = Mathf.Clamp(localPosition.x, min.x, max.x);
        localPosition.y = Mathf.Clamp(localPosition.y, min.y, max.y);

        return localPosition;
    }
}
2 Likes