Unity best practices for unloading unused areas of a map - unity3d

I'm wondering about the best way of reducing my CPU and memory overhead for areas of the game world that do not need to be updated every frame.
I have just started to consider this issue as I'm currently implementing a shadow detection system using Raycasts.
My problem is this:
I can have about 100 lights in my level that on every frame send a Raycast to nearby characters to determine if these characters are in shadows.
My game is a low poly PC game, and I understand the overhead from Raycasting isn't that drastic. So its not a major concern. But I'm still not sure of the best approach to optimising this.
I have been thinking of a few soltions, but am unsure if there is "standard" per say.
1. exit update loop if player is too far away
void Update() {
if (Vector3.Distance(playerPos, transform.position) > someRadius) {
return
}
}
This is the most glaringly obvious solution, with even more obvious concerns.
This update loop will still be hogging CPU cycles , performing 2 calculations on every frame, for every light point.
2. Disable Light gameObjects when the player is too far away
This method is more efficient in terms of CPU overhead, as those will be negated. However I'm still hogging uneccesary memory.
In order to make this solution more scalable I would have to design some kind of "enabler" that keeps track of game objects that should be enabled/disabled based on the player position.
But at this point I know I'm re-inventing the wheel, and feel very sure that there is an industry standard for this.
Is there an alternative to enabling/disabling?
I see a lot of game developers talking about physically unloading areas of their game from memory and writing those areas to disk, when the player is not nearby.
I wonder is this achieved by simply destroying and re-instantiating the objects.
Question
Is Unity opionated about this?
The page here lists an example, similar to my first solution. But they are talking about 100s of thousands of updates per frame here.
Maybe I don't need to worry as much as I think
Thanks!

If you want not render objects, that are not in your camera area, Occlusion culling is what you exactly need. Watch this link:
https://docs.unity3d.com/Manual/OcclusionCulling.html
If You want change how your object looks based on range between camera and your object, You have to use LOD(Level Of Detail). Here is documentation:
https://docs.unity3d.com/Manual/class-LODGroup.html

Related

Way to stop the navmesh obstacle avoidance pushing other agents around when they bump into each other

I am using Unity's navmesh system to make an RTS game with tanks.
When the tanks get close to each other, the avoidance system kicks in and they try to get out of each other's way. However, they often bump into each other and end up pushing others out of the way. This shouldn't be possible with vehicles as heavy as tanks, and it looks unnatural.
Is there a way to have the navmesh agents try and avoid each other, but not bump into each other, and if they do, definitely not push each other around?
I have tried altering the obstacle avoidance priority, but there is still at least always one tank that pushes others out of the way.
I have also tried altering the rigidbody, for example making stationary tanks work with gravity and making them really heavy. I have also frozen all rigidbody constraints. However, other tanks are still able to push them out of the way with ease.
At the moment, when tanks stop moving I have made a navmesh obstacle appear under them, which helps with avoidance. However, this only works if they are stationary - moving tanks can still be pushed around by others.
Any ideas or suggestions for how to solve this would be greatly appreciated!
Though not an expert at either Unity or NavMeshAgents, I have also recently been struggling with a similar issue of agents unrealistically shoving each other around. In my case it's people lining up to scan boarding passes at an airport, but it looks no less ridiculous than tanks I assure you.
Having spent several hours scouring the internet and several more hours in trial and error, I regret to say that there is no quick or simple solution. Frankly put, Unity's inbuilt pathfinding AI system is both crude and twitchy. Remember how way back in 2006's "Company of Heroes" the tanks would back up rather than turn around if only going a short distance? Yeah, 15 years later Unity's NavMeshAgents still can't do that without extensive custom scripting...
A couple of thoughts though!
Thought #1: Before we get into possible suggestions, a different appraoch to this issue would be to have the environment or gameplay discourage tanks from bumping into each other to begin with. I mean, sure it may occasionally happen during the messy heat of a chaotic battle in the center of an urban space, but from my personal understanding of real-life tank warfare they almost never actually physically touch each other... Something has gone terribly wrong if your huge long-range artillery with all-terrain-tread-based mobility has been dented by another tank like some parking lot fender-bender. Come to think of it the bigger issue I see with this NavMeshAgents shoving around issue would be when infantry push the tank around. They would, in a real-life scenario, be vastly more likely to run right next to the treads, or lean out of cover behind the tank, or duck under the main turret barrel. So if your RTS game has both tanks and infantry, and all of them have the pathfinding dealt with via NavMesh and NavMeshAgents, you have several other reasons to be concerned.
Anyhows, my point is perhaps you could implement some sort of script that makes tanks on the same side keep formation? Try as best they can to maintain a minimum distance from allied tanks? Maybe have the script lower their forward speed to zero when too close to another one, or some other form of hard/soft check to keep allied tanks from even attempting to get within bumping distance of each other. As to enemy tanks, again only in a very cartoony situation would they ever ram into each other when both tanks are in active fighting condition. If one tank is a smoking heap of rubble or has been abandoned by its crew, then disabling the NavMeshAgent and plopping a NavMesh Obstacle in its place would work fine.
Actually have you ever played/seen the 2005 Nintendo game "Battalion Wars"? Now there is a game that I think can be fairly described as following a loose interpretation of tank warfare, let alone the laws of physics... And even in that silly game tanks very rarely collided with one another. Remember the 2003-ish game "Think Tanks"? A very fast-paced rough-and-tumble tank melee, and on the rare occasion a tank bumped into another one somebody got flipped over and everyone had a good chuckle.
If you are making an abstracted game or a light-hearted silly one, nobody is going to care if a tank or two is nudged a little bit. If it's a serious game or a historical simulation type RTS, why are the tanks bumping into each other at all?
I digress. My point is that this issue of tanks unrealistically pushing each other can be minimized by either gameplay strategy or behind-the-scenes code limiting how close tanks even get to other tanks. Then it doesn't matter if they hypothetically would push each other, because it will very rarely come up and when it does come up, it is likely to be in a very active and brief situation when the player is highly unlikely to notice or care.
Thought #2: But what do I know? So here's a few ideas to limit the bumping! I've seen a few forum threads and blog posts that discuss the idea of only using the NavMeshAgent component to determine the path, and using a separate script to make the object with the actual Animator or what-have-you endlessly "chase" the NavMeshAgent. This is usually brought up in the context of cars. But cars and tanks are not so different, in a fundamental movement way. "Chasing" an invisible NavMeshAgent might be a little clunky in tight spaces, but tanks are hardly nimble compared to the humanoids on foot the component was presumably designed for. Perhaps this might be a viable solution for you, depending on the number of tanks you expect to be active at any given time. The RigidBody physics and other collision stuff would be more predictable and easier to control, and the only thing you'd rely on the NavMeshAgent for would be "steering" a tank which moves using some other script.
Thought #3: Completely different idea would be partially decoupling the NavMeshAgent from the root position of the main GameObject. The official online Unity manual even mentions this here, where they give a few simple tricks to minimize foot sliding. Tanks don't have feet, but the entire tank sliding around is basically the same problem right? Perhaps you can knowingly allow the tanks to shove each other a bit, if visually speaking the tank does not actually move because you are resetting its transform location by script.
Thought #4: I found that the Priority setting of the NavMeshAgent component was pretty useless. It only made a practical difference when you were very sure the exact order you wanted agents to move, almost in a pre-scripted way. Not very helpful in a dynamic procedural RTS game. That said, would it be possible to implement some sort of script that changes the set Priority of individual tanks based on a few battlefield criteria? It wouldn't completely stop tanks from shoving each other around of course, but might dynamically limit it. For example, you could have two moving tanks which bump into each other automatically set the tank moving faster to the lower Priority. Or a tank which is larger than any nearby tanks, determined by some tag value perhaps, be set to a Priority lower than the other ones. This would help more than all the tanks having a static default Priority value assigned at the start, because the Priorities of tanks would change depending on which other tanks are physically nearby and relevant variables.
Damaged tanks would thus be less likely to push around fresh ones. Tanks going backwards would be less likely to push other tanks than ones going forwards. Tanks in the middle of a shallow river or whatever would not be able to push tanks sitting on firmer ground up on the bank. If you can implement a dynamic Priority setting in the NavMeshAgent component via script, it might help. Sensible gameplay is ultimately more important than visual realism anyways right?
Thought #5: I don't like telling people to solve their problems by using third-party plugins. Especially ones I don't personally use. That said you could also consider looking into the capabilities of Unity Asset Store items such as A* (Pronounced A-Star) or other plugins designed to either replace or at least improve the in-built Unity system. 100USD or so is expensive and pirating these plugins is unethical, so if you do pursue such a route I'd suggest contacting the people that make them directly and asking about your specific issue before taking that plunge. Again, I don't personally use them but it would be irresponsible of me to not mention them here.
I'll add more thoughts via editing this response if they come to me, but I hope I might have given you a few inklings of what you can do. And please, if you do figure out a solution that works please let us know!!! RTS game developers need all the help they can get and many other people have similar issues with Agents that are not tanks. Good luck.

Particles or Animation

thank you so much for all the fast responses I truly appreciate it. I have another question I've been wondering about, so I am working mobile game and I want to keep the size as small as possible. So I wanted to know does using Unity particle effects, impact performance and game size? I was wondering, if i wanted to make a visual effect of breaking apart a GameObject when destroyed, should I use unity particle system to do so? or should I make an animation of that game object breaking and use that instead?
to summeize should I be making animation for things such as rain effects and confetti and fire effect instead of making them with the particle system? is there any drawback to using one over the other?
As TEEBQNE said it is your choice between animations and the particle system depending on what you need. If your team is small or you are a single developer it is best to opt for the particle system for the flexibility of changes and quick execution.
Optimising the particle system is not hard, just make sure you don't overdo the numbers and avoid some common mistakes. There is a list of the best practices for optimization on mobile games found here
You can also find some pretty good looking particles premade in the unity asset store, which are already optimized well.

Unity: Help needed with rendering voxels and performance

So here is the deal, i have an enemy that is rigged and consists out of quite a few voxels.
When i run the game i get very bad performance overall when its rendering the model because of the amount of objects it needs to render. How can i improve that?
Here's the things i have thought about:
Only rendering the faces we actually can see,
Or maybe using some sort of GPU Instancing?
Anyways, i would like to know how i could resolve such a problem. Any help is much appreciated!
Without knowing how you've actually implemented your voxels in game (i.e what components each voxel consists of and how you're currently managing them) it's hard to offer much specific advice.
In general though there are a few things to consider:
Faces that aren't oriented towards the camera won't be
rendered by default. What you might want to investigate is
Occlusion
Culling, but
since your character is not static within the scene you might not get
much performance improvement from that. The code to
constantly check whether objects are occluded might end up costing
more CPU than not implementing it.
Rendering might not be your actual bottleneck for performance. If each of your voxels is doing some work every update (such as collision detection), then that's going to hit your performance much harder than rendering the objects, particularly for cubic voxels. You'll need to use the Profiler to figure that out.
You need to consider whether you actually REALLY need all those voxels to be in the scene all the time or whether you can replace them with a single GameObject until you need to interact with them, then bring them into the scene as needed. For example, you might replace the upper arm with a mesh that mirrors the shape of the total voxels for that body part. Then when that part is shot, for example, you can detect the point of collision and instantiate the necessary voxels around that point to react as desired, then rebuild the arm mesh to reflect the changed shape.
It might also be worth looking into Unity's Data-oriented Technology Stack (DOTS) features, although that could be overkill for this situation.

Multiple Tilemap Maps Loaded Dynamically

Feel free to close this question if it is deemed too subjective. I realize that it might very well be, as it may focus heavily on best practices, which, if not an industry standard, may be subjective.
The Problem & Idea:
I'm using the tilemap system in unity (2D), and its been working great, but I have a few concerns regarding my particular usage. What I'd like to have is multiple "battle maps" that will get instantiated when the battle scene is switched to. My current idea is to just make each type of battle map a prefab (prefab on the grid, since the tilemaps are just layers), and then instantiate the grid when the scene loads in.
Is this best practice or is there any better way? Does having 10 maps vs 200 maps make a difference?
Other Things I've Considered:
Would it be a better idea to make one huge tilemap with all of the battle maps drawn a distance away from each other and just restrict the camera to moving only within the "current" battle map? The absolute max size I could see a map being is, let's say 30x20 tops, probably closer to half that though.
An earlier idea was to use small pixel map images to render the maps in. This was before I found out about Unity's tilemap system, which, admittedly, I'd rather use because it is so much simpler to visualize, and less work to develop.
The Scenario:
For simplicity's sake, let us assume the game has 2 scenes, the main menu, and a battle scene. Basically, the idea is to enter the battle scene and have a random battle map to be spawned out of what's available. The character(s) get placed, and any additionals also get placed, say, items, or what have you.
Is what I proposed above best practice? And should I consider any other other two systems I've also described? Or is there something I'm not thinking of that would be even better?
I don't believe that any of the above ways wouldn't work, I'm just curious if any of them is the best way to go about doing this.
Your consideration to have all of your battle maps drawn on a single tilemap and restricting the camera to only the region of the current map is an instant red-flag.
In my experience with unity, if I want to have a large level drawn on a grid I will have to break it up into chunks (each chunk is a separate tilemap) for performance reasons in the editor and in the game, so I would not recommend doing that.
If your goal is fast load times, then instancing a prefab as you suggested is not a terrible idea as long as the respective tilemap is fairly small (less than 10000 tiles), otherwise you would almost difinitely notice the map getting loaded in. If you are trying to load large tilemaps seemlessly, it may help to load the tilemap asynchronously before the actual switch occurs.
I would keep only the current map and next map loaded in the scene to ensure a seamless transition and optimal resource usage. Unity's tilemaps are not light.

Best Practice to Increase Frame Per Second for my daydream VR application [duplicate]

I have been building a game for VR using Unity3d. It has only low poly models and the file size is less then 40 mb still the game lags when played on mobile.. Please suggest how to improve the performance..
Thank you in advance..
In order to improve performance in VR for mobile you have to optimize everything as best as you can, you should keep some of these variables in mind:
Graphics Side
- Number of polygons in the scene
- How many source of lighting do you have
Programming Side
- How much work is taking your code, is doing it efficiently?
The programming part can include problems within the physics system, also some logic problems that can probably decrease the overall performance because of higher computation.
My advice is to learn about the Profiler that unity offers, actually you can observe how much work is taking your code and where exactly it is your bottle-neck. This video also can be useful.
Of course a solution could be implement your code following design standards, like design patterns and software architecture (depending on the size of the project).
I hope it can be useful for you!
What I found from developing and launching a vr game is some of the issues below
Number of polygons is usually your first to check even though your models are low poly. For example, I looked at Synty models in the unity store and some of them were over 1k for a bag and 7k for a character model. This seriously reduce the amount of objects you can if you want to target a max of 50000 per eyes.
With some models, you can use blender and the decimate tool to reduce the polygon count pretty easily. From there I would use LOD's to reduce their count further based on distance.
Use occlusion culling (pro version only)
Set your camera distance to maybe a 100 instead of the default
Use mobile shaders and careful using some of the standard shaders as they are expensive. Also transparent shaders will becomes expensive cause overdraw.
Batch your textures and make them static if possible
Don't use dynamic shadows on lighting but instead bake your lights
Try to avoid using physics as this becomes expensive and instead raycast to trigger events or shooting weapons.
Run profiler often and check for any bottlenecks (pro version only)
Reduce the count of Particles effects and their values
Character bones can also cause issue so remove as many as possible
There is also your code to look at as mentioned by Manujamming
Set quality setting to low in the inspector to gain best performance.
Could you provide a screenshot of your game scene?
I hope this makes sense.
Best of luck!