NGUI Example: Interaction


This example shows that your UI can easily be a part of your 3D scene. Since NGUI simply generates meshes for you, you can position them in your scene freely. You can create signs, interactable in-game HUD windows, dynamic effects such as Scrolling Combat Text from World of Warcraft, and just about anything else you can think of.

When it comes to interaction, you will find NGUI’s event system to be extremely flexible, with only two conditions:

  1. The camera that sees your object must have a UICamera script attached.
  2. The object that wants to receive an event must have a collider. No need for it to be a widget. Any in-game object will work.

There are a variety of scripts under the Component/NGUI/Interaction menu that you can use:

For example in order to create an object that changes color on touch or mouse over, you can simply attach UIButtonColor script to its collider and specify what object it should be working with. It doesn’t need to be a widget either — if you specify an object with a renderer or a light as its target, and it will also work just fine.

Want the object to grow slightly? UIButtonScale. Move? UIButtonOffset. You can activate remote disabled Tween components by using UIButtonTween. You can even make it possible to drag an object around by attaching UIDragObject script to the collider and specifying what it should be dragging. You can look at Example 7 to see how this script was used to make an interactable scroll list.

But in this example we stick to the basics: the buttons trigger a remote tween animation on the cubes and the window, making its position change.

When it comes to creating your custom event scripts, NGUI makes it as simple as possible. Simply create a MonoBehaviour that implements one of the functions mentioned on the Event page, and attach it to the collider of your own choice.

For example the following script will print “Hello World!” to the debugger when you click on a collider that has it attached.

 Posted by at 7:47 PM on January 13, 2012

  2 Responses to “NGUI Example: Interaction”

  1. this example is not working correctly in 1.33 (the cubes are not shown).

    gameObject.GetComponentsInChildren() only work with activate GameObjects. use gameObject.GetComponentsInChildren(true) instead (UIButtonTween.cs line 82).

    I also can’t see the reason why you check mTweens.Length > 0 inside the foreach (Tweener tw in mTweens) loop. It should always be greater than 0, otherwise you wouldn’t get in the loop in the first place (at least if you are not doing something strange with that public variable elsewhere).

  2. Thanks, both have been fixed and will be in the next version. The get components thing wasn’t supposed to happen until SetActiveRecursively(true) btw.