Show Posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.


Topics - ArenMook

Pages: 1 ... 3 4 [5] 6 7 ... 10
61
NGUI 3 Documentation / UIRoot
« on: November 20, 2013, 11:44:01 PM »
Overview

UIRoot always lies at the bottom of the NGUI UI hierarchy (or top, depending on how you look at it!)

It's responsible for keeping the scale of the UI somewhat more manageable. Since widget coordinates are generally specified in pixels, a 800 by 400 widget will be 800 by 400 units, which is... quite large. UIRoot shrinks itself by the inverse of the screen's height, thus keeping the widgets small and easier to work with.

   

UIRoot has several scaling styles for you to play with. Flexible style lets your UI always be in pixels, and a 300x200 widget will always take 300 by 200 pixels on the screen. This also means that viewing your UI on a low-res device will make your widgets appear rather large in size, and viewing your UI on a high-res device will make your widgets appear small. On the plus side, with this setting your UI will always remain as crisp as possible.

Constrained is the exact opposite of that. When the UIRoot is set to this setting, your screen will always remain the same size as far as NGUI is concerned, regardless of the actual screen size. This means that if a 300x200 widget takes 25% of your screen with the resolution of 1920x1080, it will still take 25% of the screen when you drop your resolution to 1280x720. If you don't want to worry about how your UI will look at different screen sizes and you don't care much about making it as crisp as possible, choose this setting. Don't forget to set the Content dimensions setting when choosing this option.

You can further refine the constrain by choosing whether the content will Fit on the screen or whether it will Fill the screen (when 'fit' is off). Think of it as your Desktop wallpaper. When you choose the Fit method, the wallpaper will always be fully visible on the screen, where if you go with a Fill method, it will always completely fill the screen while maintaining its aspect ratio. Same idea here. See the attached image for more information.

ConstrainedOnMobiles setting is a combination of the two. It will behave as if the setting was "Flexible" on desktop builds, and it will act as if the size was "Constrained" when targeting mobile platforms.

If you go with the Flexible option, don't forget to set the Minimum and Maximum Height values. These values are used to keep your virtual screen size within "sane" values. So for example if your UI is set to Pixel Perfect mode, and the Minimum Height is set to 720, then some player tries to run your application with the resolution of 800 by 600, the UI will behave as if the setting was "Constrained" with the Content Height set to 720.

Shrink Portrait UI option is designed to adjust your UI's size when the screen is in Portrait mode. It's similar to a height-based adjustment, but it will take the width into consideration as well.

Pro-Tip

The UIRoot always scales itself by 2 / ScreenHeight, where ScreenHeight is either the actual screen height (in pixel perfect mode), or the manual height that you've specified (in fixed size mode). In doing so, the camera that draws the UI can remain at Orthographic Size of 1.

If you don't need the auto-scaling functionality of the UIRoot, you can get rid of this component altogether.

Class Documentation

http://tasharen.com/ngui/docs/class_u_i_root.html

If you have a question regarding this component or would like me to clarify something, just post a reply here.

62
NGUI 3 Documentation / UIToggle
« on: November 20, 2013, 11:19:04 PM »
Overview

A toggle is a generic component that has two states: on, and off. Toggle can be used to create checkboxes, tabs, radio button groups, and other similar widgets.



Toggle is a perfect example of a small to-the-point component that can be used to do a lot of things. Like most NGUI controls, the look of it is not hard-coded for you like it is in other systems. Instead, it's used in combination with other scripts to achieve the desired behaviour.

By itself, the toggle is simply capable of fading in and fading out the targeted object. Generally this "object" is a checkmark, a highlighted sprite, or some other indicator of an active state.

To create a basic checkbox, create a pair of sprites -- a background, and a foreground (make it a child of the background to make it simple). For the background choose something that looks like a button. For the foreground choose something that looks like a checkmark.

Attach the UIToggle script to the parent (the background), and reference the foreground in the UIToggle's Sprite parameter. That's it, you now have a checkbox.

You can turn it into a Radio Button by specifying a Group ID other than zero. Just set up your checkbox how you want it to be, give it a group ID, and duplicate your checkbox game object a couple of times (CTRL+D with it selected).

You can create an Animation to make your checkmark transition smoother, or just attach an Animation component to your Checkmark and reference the provided "Checkmark" animation clip. Reference this clip in the Animation field on your Toggle, and you will have an even better looking transition.

If you want your toggle to start active, check the Starting State checkbox.

Pro-Tip

You can create a tab using a Toggle by creating two sprites, one on top of the other. First create a dark sprite, then add a child to it and make it brighter. Attach a Toggle component to the dark sprite's object and reference the lighter sprite as the Toggle's Sprite. Give this tab a Group then duplicate it a few times to create a group of tabs.

Use together with the UIToggledObjects script to set up easy enabling and disabling of child panels, thus creating a multi-tabbed window.

Class Documentation

http://tasharen.com/ngui/docs/class_u_i_toggle.html

If you have a question regarding this component or would like me to clarify something, just post a reply here.

63
NGUI 3 Documentation / UIButton
« on: November 20, 2013, 10:39:58 PM »
Overview

Button is a simple component designed to receive hover, pressed and click events, and change the color of a remote sprite. You can also optionally attach an Image Button component to the same game object to get sprite swapping functionality as well.



A button can be anything. It doesn't have to be a widget. You can put a Button component on anything that has a collider. Regardless, you will most commonly be using the Button component in your UI hierarchy -- generally alongside a UI Sprite or on the game object directly above it.

In order for the button to work, the camera that's drawing the object where you place the Button component must have a UICamera script attached, as that's what sends out events. You must also have "Raycast Hit Triggers" turned on in the Physics Settings in your project.

Button works by receiving mouse over, press and click events, and translates them into appropriate color-changing actions on your the object specified in your Target field. This will most commonly be a widget (sprite, label, or texture), but can also be an object with a Light, or even a Renderer.

If you want to trigger a remote function when you click on the button, drag & drop the target game object into the "Notify" field, then choose the function from the drop-down list. Note that in order for the function to show up, it must be of "public void FuncName (void)" type. For example:
  1. public void MyClickFunction()
  2. {
  3.     Debug.Log("I was clicked!");
  4. }
Built-in components, such as tweens, have an assortment of pre-made functions for you to choose from (for example: PlayForward).

Pro-Tip #1

It's generally a good idea to put the Button component on the same game object as the button's background sprite. Hit ALT+SHIFT+C to quickly create a collider, and check the "Box Collider" option on the sprite so that the box collider auto-updates as you resize the sprite.

Pro-Tip #2

UIButton comes with only an OnClick notification. If you want OnPress, OnHover, OnSelect, OnDoubleClick, and/or others -- attach UIEventTrigger script to your button (or any other object for that matter).

Class Documentation

http://tasharen.com/ngui/docs/class_u_i_button.html

If you have a question regarding this component or would like me to clarify something, just post a reply here.

64
NGUI 3 Documentation / UILabel
« on: November 20, 2013, 09:46:54 PM »
Overview

UILabel is a Widget that can be used to display text.



All labels require a Font to work with. This font can be Dynamic (directly referencing a Unity Font), or it can be a Bitmap font -- a font embedded within an Atlas. Dynamic fonts are more robust as they don't require you to pre-generate your glyphs before hand, but Bitmap fonts can be drawn within the same draw call as the rest of your atlas, and can be decorated nicely in an image editing tool such as Photoshop.

You can change the alignment of the labels simply by switching the Pivot point. Top-left, Left and Bottom-left pivot point will result in a left-aligned text. Top, Center, or Bottom alignment will cause the text to be centered, and Top-right, Right or Bottom-right pivot will make your text right-aligned.

With the Dynamic font chosen you can set the Font Size as well as style directly on your label. You can also set the material that will be used to draw it, if you wish.

The big box is -- as you probably guessed -- where you enter text. It's a multi-line text box by default, unless limited by the Max Lines property below it.

Overflow handling lets you determine what happens when the label's text exceeds the allowed space.


  • Shrink Content means the content will be automatically shrunk to best fit the area. It works in conjunction with the Keep Crisp setting if you are using a Dynamic font, making the font size shrink down, not just scaling the content. This results in crisp labels regardless of whether they were shrunk or not.
  • Clamp Content simply means that if the text doesn't fit, it will be cut off.
  • Resize Freely option will make the label's dimensions controlled by the text entered in the field. You won't be able to resize the dimensions yourself.
  • The last option, Resize Height will add grow the height as necessary, but will keep the width constant.
The Spacing field lets you adjust the distance between characters. Both positive and negative values are allowed. This value is in pixels.

Max Lines, as mentioned earlier, lets you control how many lines you want there to be at maximum. You can leave it at zero if you want it to be unlimited.

You can turn off Encoding if you don't want color tags and emoticons to be processed. Input fields do this by default.

If you want, you can give your labels a Gradient by specifying the bottom and top colors.

You can give your text a shadow or an outline Effect, but note that doing so will double the geometry in case of shadow, and multiply it by a factor of 5 in case of outline -- so be mindful of this feature. The Distance parameter controls how far the shadow or outline is from the base text, in pixels.

To change the label's text at run-time, you can do the following:
  1. UILabel lbl = GetComponent<UILabel>();
  2. lbl.text = "Hello world!";

Pro-Tip #1

You can add bold, italic, underline, and other effects to your label by using bbcode syntax like so:

[b]bold[/b]
[i]italic[/i]
[u]underline[/u]
[s]strikethrough[/s]

You can also embed clickable links in your labels like so:

[url=Some Message or Link]Click Me[/url]

To retrieve what you clicked on, attach a box collider to your label (ALT+SHIFT+C) and a script that has a function like this in it:
  1. void OnClick ()
  2. {
  3.     UILabel lbl = GetComponent<UILabel>();
  4.     string url = lbl.GetUrlAtPosition(UICamera.lastWorldPosition);
  5.     Debug.Log("Clicked on: " + url);
  6. }

Pro-Tip #2

You can give your labels a beveled look by specifying a dark foreground color and a bright Shadow effect.



Pro-Tip #3

You can make the text ignore the label's color tint by using the [c]text here[/c] tag, and change the alpha by using [Aa] syntax, like "[7f]".

Class Documentation

http://tasharen.com/ngui/docs/class_u_i_label.html

If you have a question regarding this component or would like me to clarify something, just post a reply here.

65
NGUI 3 Documentation / UIPanel
« on: November 20, 2013, 09:19:16 PM »
Overview

UIPanel is a component that collects and manages all widgets underneath it. UIPanel is responsible for creating the actual draw calls using the widget's geometry. Without panels, nothing can be drawn. If you're familiar with Unity, you can think of a UIPanel as a Renderer.

UIPanel inherits all the functionality of its base class -- UIRect.



All panels have a Depth value which affects all widgets underneath. If you're creating a complex UI with multiple windows, it's often best to have one UIPanel per window. The depth value of panels carries a lot more weight than the depth value on individual widgets, so it's a good idea to ensure that your panels don't share depth values. If values get shared, draw calls will start to get split up frequently in order to preserve the draw order, resulting in a lot more draw calls than usual.
  • Alpha property affects all the widgets underneath. It's a good way to fade out an entire window.
  • If your UI is affected by lighting, be sure to check the Normals checkbox.
  • If you are creating a scrollable panel that has a lot of geometry inside, you may want to toggle the Cull option in order to reduce the number of triangles drawn. Note that doing so may actually reduce performance, however (as the visibility of widgets will need to be checked every update!).
  • Checking the Static checkbox will improve performance by telling NGUI that widgets underneath this panel are not expected to move. NGUI will bypass checking for position/rotation/scale changes. Note that doing so means that moving widgets at run-time will not have any effect, however -- so be careful.
  • If you are trying to debug draw calls created by the panels, Show All option may help you. Doing so will let you see all the draw calls created by NGUI's panels in the order that they are drawn. Each draw call shows detailed information including the material used, which widgets are contributing to it, and even let you turn off the draw calls selectively in order to help you determine what's going on.
The panels can automatically Clip all children using the dimensions of your choice. To enable clipping, just choose one of the options under the Clipping drop-down, then adjust the dimensions of the purple rectangle in the Scene View like you would adjust the dimensions of any widget. If you're going down that route you can turn your panel into a Scroll View and make it draggable fairly easily as well.

In NGUI 3.5.5 and earlier versions, multiple clipped panels would not work. Only the last panel would clip the contents. This limitation was lifted in NGUI 3.5.6.

By default, all of NGUI's panels will begin drawing with Render Queues of 3000 and go up from there. You can change that by choosing something under the Render Q drop-down list. If you want to add a particle system in between of two of your panels, simply make sure that the first panel's render queue is lower than the one used by the particle system's material, and the second one has it set to a higher than the particle system. If you want NGUI 2.X-like behaviour where all draw calls were Z-based instead of depth-based, specify an Explicit render queue (3000 is what NGUI 2.X used).

If you are looking for the documentation regarding the Anchors section, you can find it in the base class -- UIRect.

Pro-Tip

A kinematic Rigidbody gets added to your panels automatically because according to Unity this greatly improves performance in physics-heavy games. Moving static colliders is a very expensive operation in Unity, but moving rigidbodies is not.

Class Documentation

http://tasharen.com/ngui/docs/class_u_i_panel.html

If you have a question regarding this component or would like me to clarify something, just post a reply here.

66
NGUI 3 Documentation / UISprite
« on: November 20, 2013, 08:56:37 PM »
Overview

UISprite is the bread-and-butter of NGUI. It's a drawn sprite pulled from a texture atlas. Like other widgets, it inherits all the functionality of the UIWidget.


  • All sprites require an Atlas to be created first. Clicking the Atlas button will bring up a list of all the atlases in your project. To create a new atlas, use the Atlas Maker tool (NGUI -> Open -> Atlas Maker).
  • You can click the Edit button next to your Sprite selection to edit the selected sprite. This is also how you can add a border to your sprite, making it suitable to be 9-sliced.
  • By default, the newly added sprites are going to be of Simple type. This means they will be drawn much like UITextures, except their data will be coming from the atlas.
  • You can change the Sprite Type to be Filled if you're doing a cooldown timer or a progress bar.
  • You can change the Sprite Type to be Tiled if you want your sprite to repeat over and over, filling the area. It's best to not use small sprites for this as doing so will create too many triangles. It's also a good idea to give your sprite a 1 pixel border so that seams will be eliminated.
  • You can change the Sprite Type to be Sliced if you want to enable 9-slicing on your sprite. For this to work correctly you need to specify a Border on your sprite (click the Edit button above). An example of a sliced sprite would be a button's background.
Choosing the "Make Pixel-Perfect" option from the context menu will make the UISprite assume its original size. So if the source texture was 300 by 200 pixels, the width and height of your UISprite will be adjusted to exactly those dimensions. Note that this will not be the case with Tiled and Sliced sprites -- they have their own set of rules.

Pro-Tip #1

NGUI will automatically use the last selected atlas and sprite when creating new ones. This means if you have the Atlas Maker open and choose some sprite within, you can quickly create it by hitting ALT+SHIFT+S. Although note that duplicating the selected object is even easier (CTRL+D).

Pro-Tip #2

To change the sprite via code, use its spriteName:
  1. UISprite sprite = GetComponent<UISprite>();
  2. sprite.spriteName = "Some Sprite";
Just make sure that "Some Sprite" actually exists in the atlas! It's case sensitive.

Class Documentation

http://tasharen.com/ngui/docs/class_u_i_sprite.html

If you have a question regarding this component or would like me to clarify something, just post a reply here.

67
NGUI 3 Documentation / UITexture
« on: November 20, 2013, 08:27:59 PM »
Overview

UITexture is the most basic drawable component in NGUI. It inherits all the functionality of the UIWidget, and adds a visible component -- a texture -- that gets stretched across its dimensions.



  • You can specify a Texture that will be drawn. A default material will be created for you when you do. If you don't specify a texture, the material's texture will be used instead.
  • If you wish, you can specify a Material of your own. Even with the material specified, the Texture you specified above will be used instead of the material's main texture.
  • If you don't want to make a material, you can also just specify a Shader instead.
  • You can specify a UV Rectangle that will control which part of the texture will be drawn. X and Y control the UV offset, and W and H control the width and height of the UVs (texture coordinates). Like all texture coordinates, these values are usually 0 to 1 (with 0 meaning one side of the texture and 1 meaning the other). The UVs are bottom-left based, so if you wanted to draw the top 50% of the texture you'd specify UV Rectangle of (0, 0.5, 1, 0.5).
Choosing the "Make Pixel-Perfect" option from the context menu will make the UITexture assume its original size. So if the source texture happens to be 300 by 200 pixels, the width and height of your UITexture will be adjusted to exactly those dimensions.

Pro-Tip

You can create your entire UI using UITextures then easily add them to the atlas by opening the Atlas Maker (NGUI -> Open -> Atlas Maker), selecting the root of your UI, and hitting the Create button. All your textures will be placed within this atlas and will be replaced with Sprites instead.

Class Documentation

http://tasharen.com/ngui/docs/class_u_i_texture.html

If you have a question regarding this component or would like me to clarify something, just post a reply here.

68
NGUI 3 Documentation / UIWidget
« on: November 20, 2013, 07:43:17 PM »
Overview

UIWidget is a basic NGUI component. In simplest terms, it's just a rectangle that you can position on the screen however you like. This widget, while has an area, is also completely invisible at run-time -- making it ideal for use as a container holding other components.



UIWidget also happens to be the base class for all drawn NGUI elements -- including sprites and labels that you use to create your user interfaces. UILabel, UISprite, UITexture and UI2DSprite classes all derive from UIWidget.
  • You can move the widget by pressing the mouse anywhere within the rectangle and moving it around.
  • As you move the widget, it will snap to the edges and center of other nearby widgets and panels. Hold Control if you don't want snapping to occur.
  • You can drag the round handles around in order to scale the widget.
  • Hovering the mouse just outside the round handles will let you rotate the widget. Hold Control if you don't want angle snapping.
  • You can add a collider to make this area intercept events, and you can anchor other widgets to it if you like.
  • If you have a box collider on the widget, you will see a new option: Box Collider. It's on by default, and it will automatically resize the collider to match the widget's dimensions.
  • You can quickly add a child UIWidget to the selected object by using the shortcut key ALT+SHIFT+W.
In the code, the widget's position is specified using the Transform component -- just like any other game object. The position is always relative to the widget's Pivot point. A pivot point basically means "the point widget rotates around".

Widgets also have Depth that controls their order when clicking on them (and in case of derived classes such as Sprite and Label -- their draw order). This order can be observed by right-clicking on the widget in the Scene View and choosing the Select menu. Doing so will give you a list of all the selectable widgets underneath the mouse in the same order that they will be drawn / receive events -- top to bottom.



The same context menu can also be used to add siblings and children to your widgets as well as attach scripts and create new elements.

If you are looking for the documentation regarding the Anchors section, you can find it in the base class -- UIRect.

Class Documentation

http://tasharen.com/ngui/docs/class_u_i_widget.html

If you have a question regarding this component or would like me to clarify something, just post a reply here.

69
NGUI 3 Support / (!!!) Improving NGUI: Voice your opinion
« on: November 13, 2013, 05:15:44 AM »
As some of you may know, I created NGUI 2 years ago for myself because I needed a UI system. Since then it has grown and evolved over the first year, but then I joined Unity and the development slowed down. That was in part because of my contract with Unity which allowed for only minor changes to NGUI, and in part because I was too busy with support and the new full-time job at Unity.

This is now changing, and as many of you also know, a new UI that I've been contributing to at Unity is coming soon... but it's still based off of NGUI, and my view of what's important is biased because of that. And so I turn to you, the users. What's important to you? What would you like to see in both NGUI and/or Unity's GUI?

Some mentioned contextual menus in the editor. I've done a first pass on that recently by adding a way to right-click on widgets in order to show the hierarchy of what's underneath. Do you want to see more options there, or do you worry that it will be cluttered and unusable? An example would be the ability to create widgets from the context menu, add child objects, attach common components... To me that seems redundant since NGUI has hotkeys for that (ALT+SHIFT+S to add a sprite, ALT+SHIFT+L to add a label, T for texture, C for collider, etc). What do you think?

Also, which areas do you want improved / redesigned? The anchor / stretch system redesign is already on the roadmap. More intuitive way of specifying clipped regions is as well, and will come before the anchor/stretch system. What else? I know the lego-like structure of NGUI's widgets does not appeal to everyone and some find it complicated (checkbox being several game objects / components for example), while others like the fact that it's flexible and offers a way to customize their UI without modifying code. What about you?

More importantly still... what frustrates you in NGUI? What makes you go "AAAARRRGHGHHHH!!"? I myself tend to rage quite a bit IRL (mainly related to Mecanim lately... ugh!), so I am quite guilty of hating the system because I don't understand it. So if something is driving you nuts and you want it changed / explained, feel free to vent here and I will do my best to do something about it.

So, in short -- I want to improve both NGUI and uGUI, and your opinions can do just that. :)

70
TNet 3 Support / [TNet 2] FAQ & Useful Info
« on: November 07, 2013, 05:23:51 AM »
TNet Class Documentation

Various useful posts
Q: How to set up a remote lobby server where users can register their own servers?

1. Start the TNServer as a lobby server on a remote PC. Note that it has to be a remote PC as this is a lobby server, not a game server. I started it on my Amazon EC2 micro instance, for example.

Windows:
  1. TNServer.exe -name "Remote Lobby" -tcpLobby 5129
OSX & Linux:
  1. mono TNServer.exe -name "Remote Lobby" -tcpLobby 5129
2. Create a new scene, add a game object, add a new script to this game object:
  1. using UnityEngine;
  2. using TNet;
  3.  
  4. public class Test : TNBehaviour
  5. {
  6.         void Start ()
  7.         {
  8.                 TNServerInstance.serverName = "My Server";
  9.                 TNServerInstance.Start(5127, 0, null, TNServerInstance.Type.Tcp,
  10.                         Tools.ResolveEndPoint("your.lobbyServer.com:5129"));
  11.         }
  12. }
3. Assuming you changed "your.lobbyServer.com" to be your remote server's address, hit Play. You should now see the game server get added to your lobby server and stay on the list.

71
NGUI 3 Support / A question for ex-pirates!
« on: September 22, 2013, 04:10:58 AM »
Ohai. As some of you guys may know already, I'm one of those weird people who doesn't believe that piracy is a problem in the software world as long as there is the "if you like it, buy it!" emphasis on it, like on certain share sites (looking at you, persians!).

I knew of a few people who actually messaged me last year saying they pirated NGUI but then liked it so much that they actually bought a legit license. And that's pretty damn awesome. I far prefer that to someone who buys it upfront then bitches to me because it doesn't have a "MAKE MY GAME" button, if you know what I mean.

And going with that, I am actually curious if anyone here has gone legit lately in the similar fashion?

72
Misc Archive / Terminus Seven
« on: September 01, 2013, 12:01:21 AM »
Back Story

Quote
"It may have been our government that put a man into space, but we were the ones that laid claim to it." - John Richards, CEO, Edison Motors Corporation.

In the mid 22nd century the earth's population swelled to nearly 30 billion. Poverty, hunger and strife were commonplace. More people were dying from malnutrition than in the constant wars waged by our failing governments in their futile attempt to control what was left of the Earth's dwindling natural resources.

In the end, it was the coalition of seven of the Earth's largest mega-corporations that proved to be our salvation when they banded their considerable resources together and developed faster-than-light travel, allowing us to establish new, peaceful colonies on distant planets and nearby stars.

Within the span of mere four decades, the Terminus Seven, as the media called the council of corporations, established over a thousand remote colonies in a hundred remote star systems, managing each one autonomously. The old governments tried to resist at first, but had little to offer their weary, disillusioned people. On March 19th, 2187, nearly four million people rose up in what was then known as London, toppling their failed government and paving the way for the very fist official Corporate Rule on the Old Earth.

The effect on the rest of the world was swift and brutal. Within a mere month, the Earth was fully under Terminus control.

The governments were no more.

------

The year now is 2887.

The Seven are still in control, but the strong bonds between them have been all but forgotten. While no outright wars have been recorded between the different factions, increasingly intense skirmishes have become quite common, threatening the fragile stability of the known galaxy.

You are a freelancer -- an unaffiliated ship's captain. You have the freedom to go anywhere, and do anything. Will you choose to exploit the ever-growing chaos between the Seven for your own benefit, or will you step in and give them a united purpose once more?

What will you do with such a big galaxy, and all the freedom in the world?

73
NGUI 3 Support / Limited support Aug 26-31 (Unite 2013)
« on: August 27, 2013, 02:18:56 AM »
Hey guys,

Just be aware that support will be limited during this year's Unite conference as I will be there doing my part, and it's unlikely that I will get much free time.

Apologies! But hey, if you're going to be here, come down and say 'hi'.

74
TNet 3 Support / Custom Object Creation functions (TNet 2)
« on: August 15, 2013, 12:36:08 PM »
Let's face it -- sometimes the generic TNManager.Create functions aren't enough. Sometimes it's useful to be able to pass custom data along. For example, creating a unit and wanting to assign its team. With Unity's objects it's easy -- Instantiate returns a game object that you can then modify, but with the creation having to go through proper synchronization, things get... tricky.

Well, TNet 1.8.0 aims to change that.

Adding a custom creation callback is now as simple as adding a new RFC call. In fact, the syntax is very similar as well.

The first thing you will want to do is to have a MonoBehaviour script attached to the same game object as your TNManager, or one of its children. This way TNManager will be able to find the function you are about to add. If you have a Game Manager, I'd suggest you add the following code there.

If you don't want to add the script under your TNManager, then you will need to register it with the TNManager by calling TNManager.AddRCCs<YourScriptType>();. TNet will check the script and add all of its RCCs automatically.

Next, add the actual RCC (remote creation call) function to your script. To do that, simply create a prototype for it. The function prototype for it is: [RCC(#)] GameObject FunctionName (GameObject prefab, ...); -- where "#" is the ID (10 to 255 range, inclusive), and "..." can be your custom parameters -- whatever you want them to be. For example, here's a function that expects a name to be passed along with position and rotation:
  1.         [RCC(10)]
  2.         static GameObject OnCreate (GameObject prefab, Vector3 pos, Quaternion rot, string unitName)
  3.         {
  4.                 GameObject go = Instantiate(prefab, pos, rot) as GameObject;
  5.                 go.name = unitName;
  6.                 return go;
  7.         }
Note that the function then returns the game object you've created so that TNet can do some other work with it (namely setting the TNObject IDs, if needed).

The last step is to call the new TNManager.CreateEx function somewhere. You can call it directly if you wish, but it's probably easier to create a wrapper function for it next to your RCC call and so that it's easy to find later:
  1.         static public void Create (GameObject prefab, Vector3 pos, Quaternion rot, string unitName, bool persistent = true)
  2.         {
  3.                 TNManager.CreateEx(10, persistent, prefab, pos, rot, unitName);
  4.         }
Note that the first 2 parameters passed to TNManager.CreateEx must be the ID of your RCC function and the persistent flag (whether the object will remain behind if the player leaves). The following parameters should match your RCC function's parameters.

As you probably guessed, calling your custom GameUnitManager.Create(...) function will indeed create your object as if you called TNManager.Create, except that your custom function will be doing the work -- including setting the name of the object.

Here is the complete script, for your convenience:
  1. using UnityEngine;
  2. using TNet;
  3.  
  4. public class GameUnitManager : MonoBehaviour
  5. {
  6.         /// <summary>
  7.         /// Step 1: Use this function instead of TNManager.Create when you want to create a new unit.
  8.         /// </summary>
  9.  
  10.         static public void Create (GameObject prefab, Vector3 pos, Quaternion rot, string unitName, bool persistent = true)
  11.         {
  12.                 TNManager.CreateEx(10, persistent, prefab, pos, rot, unitName);
  13.         }
  14.  
  15.         /// <summary>
  16.         /// Step 2: Create a function that will be called when the unit creation packet arrives.
  17.         /// Make sure that this script is attached to the same game object as TNManager or one of its children,
  18.         /// or that you registered this MonoBehaviour by calling TNManager.AddRCCs!
  19.         /// </summary>
  20.  
  21.         [RCC(10)]
  22.         static GameObject OnCreate (GameObject prefab, Vector3 pos, Quaternion rot, string unitName)
  23.         {
  24.                 GameObject go = Instantiate(prefab, pos, rot) as GameObject;
  25.                 go.name = unitName;
  26.                 return go;
  27.         }
  28. }

Pages: 1 ... 3 4 [5] 6 7 ... 10