Should I include the Canvas parent GameObject in a UI prefab in Unity - unity3d

I have four different Canvas elements in my Unity scene. This organizes them by concern, but also improves performance since I don't have to rebuild all the elements if I "dirty" one of them. I want to create prefabs of each so I can reuse them across the game, and also so there are less elements in my scene file (I have yet to figure out why Unity doesn't re-organize YAML to match the scene order and hierarchy. Currently I can see no reason and it makes source control a huge pain).
So, my question: Should I include the Canvas as the parent GameObject in the prefab, or should I make the first child the prefab (see image)? I see two perspectives:
On one hand it's nice to scan the list of elements in the root of the scene and see the blue objects and know they are automatically replicated across scenes. Plus, the more object stored in the prefab then there will be less to pollute my YAML file.
On the other, with a Canvas Scalar script on the parent, the sizes inside the prefab are going to be updated every time I change the resolution / platform and I've read it's not good always update them outside of prefab mode. The other issue is the fact that UI elements usually have a lot of external references to update text and so forth.

After a lot more research I've come to some conclusions about the answer:
As stated in this talk at Unite 2017, isolating UI element "islands" by concern AND how often they are updated will keep the UI from affecting performance. The video also states it is fine to use multiple Canvases inside other Canvases to achieve this goal.
If you add a prefab whose values are updated from outside the prefab they will appear as "overrides" to that prefab. This includes if you link to elements outside the prefab from within it and vice versa (see image). Importantly, it is not possible to apply these overrides to the prefab, and that's kind of the point. Unity accepts that these changes will happen and this is how it deals with them without breaking the prefab or the scene.
So the answer is yes, it's no problem to include the Canvas parent in the prefab, and you can even organize it inside other Canvas so they all inherit the same settings. Further, since the more code stored in prefabs decreases the extra (unorganized) identical code in the .unity YAML file (in my case from 17,000 lines to just less than 5000!) then this is the recommended way.

Related

Does changing multiple sprites on a single animation affect performance?

I have been building a 2D sprite based game for which I want to have the player be able to customize their equipment. This means that although I am fine with drawing the content, I'd need to ensure animations in the game run fine on top of each other. For this, I have been preparing a game object with several children to account for the equipment:
Each of the children runs a single animation and should have to follow the player, which I accomplish by using transform.localPosition = Vector2.zero; on the Update of the script each takes, so they hook to the parent's pivot and follow the player. While this has worked for the most part, there are moments in which all of the objects are not synchronized and as such sometimes the parent object (the body) is seen where it shouldn't since the other game objects should render on top:
Aside from that, to make it easy for the children to follow the parent position I had made sprites which are all the same size, which risks me having to load a lot of transparent space per sprite.
Another problem that I just noticed as I'm trying to address the issue of loading too many useless pixels involves the positioning with other objects such as the Sword game object, which doesn't follow the player fully if I use sprites that are not perfect squares (see this question for details How to align sprites of smaller sizes to a moving gameobject sprite? and this one Sibling sprite doesn't appear to follow main GameObject sprite even when transform.position updates)
I tried to fix this by making the Sword a child of the Hero, but even then changing the position through a function that sets values to add on to transform values of the sword game object only change the position of it relative to the initial value. I attempted changing the pivot of the sword sprites to a custom value to guess where the center of it would align with the main game object and appear in the right position, but even that doesn't seem to work.
I'm kind of getting tired with my current process, as I have to rely on several animations for each of the game objects, both parent and children, so that these obey to different layers in a single animator (or in the case of the sword, a separate animator), all to ensure there is some synchronization that doesn't always occur:
I really don't mind the web that is turning out in what I'm doing, but the fact that I have to repeat it across multiple layers with no real guarantee that all the objects would appear right on top of each other due to the fact of having multiple animations playing, and loading multiple sprites with empty space is becoming more of a chore than enjoyment.
So I think I came up with a possible solution: If I could make a single animation for the whole equipment used at any given point (whether only wearing pants or wearing full equipment), then having this single animation could guarantee synchronization across parent and children without the need for animator layers or special functions to update position or worrying about pivots or square sprites if I can set the position of non-square sprites in the animation, with the downside that I would need to account for every single animation for each possible equipment variation (so if I had even 3 of each sword, pants, boots, etc. that would mean 3^6 animations) and make a more complex web of animator states. The only thing I'd be worried about in this case, however, would be the performance, if having too many animations for a player would affect how fast these load. But at the benefit of eliminating the other problems mentioned, my question boils down to this:
Is it better to have a single game object with animations that change multiple sprites across children game objects and a single animator that chooses states based on multiple variables, or game objects with multiple animations that change a single sprite for each, and a single or multiple animators with multiple layers that choose states based on multiple variables?
There isn't really a set answer for something like this. It really just depends on how good your/the players computer is when playing the game. Sorry if this isn't what you wanted.

How should I handle a multiple scenes project?

I'm trying to make this game using the approach of multiple scenes to make things more modular.
In my actual case I have an "Initialization" scene which holds some global state objects and the one to control the state machine of all the scenes in the game.
As for the other scenes, for now I divided them just in two: the base scenes (which for now contains everything besides UI) and its UI scenes (which basically have a Canvas and all the UI elements and UI-related scripts).
The confusion in my mind is simple though: as I tried to make the UI scenes as modular and independent as possible, there are a lot of points of interactions between the base scene and its UI scene.
For the sake of illustrating this question please take this problem I'm facing right now: I have camera animations that should be played as a response to user inputs to the UI (like the click of a button should trigger a specific camera animation). Thing is: that camera is not in the UI scene. The way I'm resolving this problem right now is creating a ScriptableObject which holds events for important actions triggered in the UI scene that are fired in the UI scene and subscribed in any other place. The same can occur in the opposite direction: the UI scene need to react to many actions that happens in other scenes.
Considering that the "camera animation" problem I explained above can happen with many other objects, if there is not a better way to handle that wouldn't splitting a game into multiple scenes be just too much of work just for the benefit of modularity? And by that I also asks: am I handling this problem the right way?
If you want to keep things consistent between scenes, there are a few ways to do it.
PlayerPrefs lets you keep variables consistent, I don't need to do a whole tutorial here, look it up.
DontDestroyOnLoad lets you take an object and make it consistent throughout the whole game. If you want, you can use DontDestroyOnLoad on one of your cameras and just delete the others in the other scenes if you want to keep a consistent camera.

Automatically add platform area tile as player approaches the edge of current tile

Firstly, I'm new to Unity and I'm currently learning c#, please be gentle!
As a project, I'd like to create a simple 3d platform game. The idea being the player starts on a square tile, which is the game platform playing area. They explore different elements on this tile by moving around.
The perspective is 3rd person, so the player is looking down on the action. As they approach the edge of the tile Unity recognises this and adds another tile to the existing one, basically doubling the playing area.
As the player moves around further to the tiles edge, other tiles are added, increasing the discovered areas each time.
My thinking to achieve this would be to have 5 tile game objects, that have different elements like trees already built on them. The question is what is the best way to achieve this.
Would it be to build the complete level with all tiles and then using code restrict how far ahead the player can see, basically to the width and length of the tiles.
Or would it be better to trigger a new tile to appear as the player approaches the edge of the current tile.
Thought, links to example code that I could recycle would be very handy.
Thank you.
The question is primarily opinion based, but here is some advise:
There is no right way to make a game in unity. The correctness is mainly focused on performance; memory and processing.
There are two approaches here:
condition: Your world is endless (or very large) and player moves very slowly over time (say each tile takes more than a second to traverse).
solution: Do not instantiate everything at start, instead when player reaches the edge of a tile look for the next tile in your level structure to retrieve its data and then instantiate its objects.
condition: Your world is not very large (say it has less than overall 10K objects) OR player can move fast (as in Age of Empires game).
solution: Instantiate everything in loading phase and deactivate the game objects as they are being instantiated so that nothing is getting processed at the start of the game. In this case the level structure is a collection of game objects where you activate or deactivate them.
Hints:
Pooling is a good practice when it comes to repetitive objects. Pool is basically an empty game object with a script, and many many deactivated children.
e.g. If you have 1K trees of the same kind you better have a tree pool. Create a game object named tree pool, add a pool script to it and make that script generate 1K deactivated tree game objects in the loading phase. Then whenever your level generator needs a new tree just fetch a tree from tree pool and activate and reposition it. Make sure you clean up the pool after the game ends to prevent memory leak.
you can implement the pool as you like to provide object variations for a specific pool.
Instantiation in run-time is costly especially in mobile devices. Whenever you need to instantiate several game objects at once consider using a coroutine to prevent lag or freeze (this applies to loading phase too).
e.g.
IEnumerable CreateObjects(Data[] data)
{
foreach(var e in data)
{
Instantiate(e);//instantiate here and then wait
yield return null;//this line prevents lag
}
}
//...
StartCoroutine(CreateObjects(data));
//...
Having many active game objects is also costly especially in mobile devices. If many active game object have heavy scripts, the update methods will ruin performance. If many active game objects have rigidbodies or colliders the physics engine processing gets heavy.
Activating game objects is costly but less than instantiation, since it only runs Start method on its script if any, and also causes the physics engine to re-evaluate its structure if it has static collider or rigidbody.
Rendering is costly if only the rendered visuals are (fully or partially) visible to the cameras.
Create an editor project where you can design your levels. in this project you will make use of unity's editor classes to generate some kind of data (JsonObject) which represents your whole world. (collection of levels, tiles in each level and objects in each tile). Moreover you can have other data such as objectives and stuff each stored in a different JsonObject. Then use this data in your game by reading it and storing its structure in memory.
The reason I recommend JsonObject to store data is its size, portability, flexibility, accessibility and simplicity to work with. JsonObject is a dictionary stored as a plain text. and since it's a text you can encrypt it as you like

Lightmap not working in Unity Prefabs

I am trying to do a 30 level gameplay in unity. To reduce the size I want to use prefabs. So path to travel is made as parts and kept prefabed. Using these parts I have made many levels and these are also kept as prefabs. The problem is for each level I have used individual light maps. Its also included in level prefabs(baked). ie, every prefab contains level paths and lights(baked).
But am not getting the preferred lightmap from the prefab. What do I need to do to make this happen?

Understanding scenes in Unity3d

I have some confusion with scenes in Unity3d and I was not able to find any resources about them.
When should scenes be used? For example in a platformer would every level have to be a different scene? Would the main menu be a scene?
Can one overlay scenes?
How do assets work between scenes? Are they attached to each individual scene and have to be reloaded every time. Can one specify when an asset is no longer needed?
How does one send data between scenes/interface between scenes?
I understand that this is a broad topic, but I didn't want to spam with multiple questions.
When should scenes be used? For example in a platformer would every
level have to be a different scene? Would the main menu be a scene?
There are no general rules about that. In theory you may have just one scene for the whole game.
How you organize your scenes is entirely up to you and often depends on the type of game you are creating.
I think that there are at least 3 features to be considered of using scenes:
they are a logical container for all pre-instantiated objects that might be useful to divide your game into multiple levels/sections.
You can serialize cross references between GameObjects and Components inside a scene (if GO A needs a ref to GO B, and they belong to the same scene, the reference can be serialized and you no longer need to find the referenced object at runtime)
When you load (not in an additive way) another scene, the resources already loaded into memory are automatically released
Can one overlay scenes?
Yes you can using LoadAdditive. Unfortunately, once 2 scenes are both loaded into memory there is no automatic way of distinguish objects belonging to one or the other. So if you load additive a second level environment, it's up to you to keep track of the previous environment and explicitly destroy it if you need to.
How do assets work between scenes? Are they attached to each
individual scene and have to be reloaded every time. Can one specify
when an asset is no longer needed?
As defaults every GameObject of a scene will be destroyed once the new scene is loaded (unless you use an additive scene loading). A way to make a GameObject survive across scenes is to mark it using DontDestroyOnLoad.
If you need to share a particular "configuration" of a GameObject, you can store it as a prefab, and reference it across scenes (but remember that once in a scene it's a prefab instance, so the GO shares with the prefab the initial serialized and not overriden properties, but 2 instances of the same prefab are different objects).
How does one send data between scenes/interface between scenes?
Several ways, depending on what kind of persistent data you want to share.
For a particular GameObject instance let the object survive using DontDestroyOnLoad.
If you have some configuration data that doesn't need to be attached to a specific GameObject you can consider storing a ScriptableObject inside the AssetDatabase and reference it.
If you have data that must persist across different game sessions you can consider storing them into PlayerPrefs.
There are 2 other ways that I don't like, but just to cite them:
Using a static field can sometimes help you in doing that, but it has several problems from my point of view
Save and load from disk (could be useful in several situations, but often it's a platform dependent way and you can have some trouble especially on different mobile platforms)
This is a broad topic btw, I hope this answer can be a quite decent overview.
When should scenes be used? For example in a platformer would every level have to be a different scene? Would the main menu be a scene?
There is no rule as to how many scenes you need to have in your game. However, scenes allow you to logically separate out parts of your game from the rest of it. You have to have a minimum of one scene.
By main menu, if you are referring to a canvas with your UI elements, it will be IN a scene and not a scene itself. Canvas is just another GameObject, that we mostly happen to use for showing game menus. I mostly create a Canvas GameObject, put a script by the name of "UIManager" and put DontDestroyOnLoad on it, so I have access to it in all scenes. Make it Singleton and I ensure that it is not duplicated.
Can one overlay scenes?
Yes, there is no restriction as to how many scenes you can load at a time. What purpose do you plan to overlay scenes though? Maybe there is a better way than loading additively.
How do assets work between scenes? Are they attached to each individual scene and have to be reloaded every time. Can one specify when an asset is no longer needed?
Assets are what you see in your 'project' hierarchy. I think you meant "GameObject"s in the scene, and if so, think of your gameobjects as entities with components (Entity-Component System). All entities in a scene get destroyed when its parent scene is destroyed until explicitly stated not to, using DontDestroyOnLoad in some component (a monobehavior in case of unity). The destroyed ones will get garbage collected.
So how they are loaded (or reloaded) depends on your implementation, on whether you are instantiating/destroying them time an again or if you put their instantiated prefabs in a cached object and retrieving later from it.
How does one send data between scenes/interface between scenes?
Heisen covered the ones I could think of. Just to add a little bit to it, it also depends on how you want to the architect your project. So if you had an underlying data structure to e.g. hold Commands, you are free to use it in any part of your project
Most games would be organised to have scenes for every level(including the main menu) but that is entirely up to you.
You can use the data from one scene to another if you save it in a text file or binary. There are a lot of tutorials on how to do this. I find documentation helps a lot.
Assets are universal in a project.
You can not overlay scenes.
When should scenes be used? For example in a platformer would every level have to be a different scene? Would the main menu be a scene?
When to use a scene is up to you. If you are just starting I would recommend using a different scene for each section of your game.
Can one overlay scenes?
Yes, using LoadSceneMode.Additive(). (LoadAdditive() is obsolete)
How do assets work between scenes? Are they attached to each individual scene and have to be reloaded every time. Can one specify when an asset is no longer needed?
By default, assets are deleted when using SceneManager.LoadScene(). However, if you use DontDestroyOnLoad(), the object will not be destroyed when entering new scenes. If you want to only keep an object through a few scenes instead of all, use Destroy() with some boolean logic.
How does one send data between scenes/interface between scenes? I understand that this is a broad topic, but I didn't want to spam with multiple questions.
You can send data through scenes by using the aforementioned DontDestroyOnLoad(), referencing the data on different scripts, using ScriptableObjects, using JSON Serialization, using StreamWriter(), using PlayerPrefs (Don't use for important information), the list goes on. I would personally recommend using ScriptableObjects for their accessibility, and StreamWriter() for it's encryption capabilities.