Unity: persistence between scenes practical advice - unity3d

So I did a lot of research, and long story short decided to go with making a game manager with dontdestroyonload for persistence.
There are many tutorials, but I'm new and I have many questions in my head when it comes to actually implementing this. It's easy when you just have one player character, but my game has a party of players, their prefabs only need to be spawned in battle, then when the battle is over, I don't need their models...just their stats.
So if I attach all my party members to the game manager, it will keep their stats but also keep everything else:model, battle scripts, etc. I just need to keep their stats. So how do others do it in practice?
I was thinking of adding code to destroy the scripts and components I don't need, then reattach them when a battle is triggered, but I just feel like it's hacky and I'm missing a better established solution out there. I've looked at professional packages and never saw anyone do that, it's like they store the stats somewhere else and just spawn a prefab in battle.

Why does this code need to be attached to a game object at all?
There is no reason to extend MonoBehaviour for things that "store data" and attach it to a GameObject (which is then never destroyed). This is the result of being new to Unity and every time you create a script, Unity automatically has it extend MonoBehaviour and you get into the thinking that EVERYTHING has to be attached to a game object and treated like one. You don't have to do this. Here's a class that doesn't extend anything (it implements ISerializable, but that's not relevant here).
Instead, you might want to look into scriptable objects, or have some other method of storing the player data (e.g. your GameManager class could be a singleton with a static instance reference). What works best for your project is mostly up to you: you know the most about your goals, you need to evaluate your options and figure out what works for you.

Related

How can i add custom behavior using pure ECS (Entity Component System) in Unity?

We are currently making our dream game with thousands fast dying zombies.
Problem is - we are making it for mobile devices.
Hybrid ECS is not enough, cuz even 100-200 low poly zombies is to heavy for render even after ultimate optimization.
Solution is use only pure ECS. Followed this tutorial i can spawn now 2-3k zombies on 40-50fps on low end devices.
But, im stuck on adding behavior. I just cant add it on each entity. By getting this tutorial as example - how to add custom behavior like AI scripts/systems for each cube?
I tried to add "system" on it, but it applies only on GameObject that u use for getting copy's.
P.S. I dont want to use external ECS frameworks, cuz im sure in future Unity built-in ECS will be the ultimate "from box" solution.
You don't. With Unity ECS you register systems. Systems work on entities that have certain components attached. E.g. you can create a system that processes all Zombies (e.g. all entities with a "Zombie" component) and execute some logic for them in each tick. The trick with ECS is that you do not handle each entity separately but you run logic for all entities that share certain criteria. This is why it is so fast, but it requires to let go of the Monobehaviour approach, mentally. I found this tutorial helpful in getting some start of actually implementing logic: http://infalliblecode.com/unity-ecs-survival-shooter-part-1/
It's not 100% up-to-date but it should be enough to get you an idea how things roll with ECS.

Unity3D how to support 'modding' (allowing players to add their own game objects)?

I'd like users to be able to design their own GameObjects in unity, and somehow import them at runtime into a game I'm making.
That means maintaining the hierarchy (there may be child objects), and any scripts, components, models, and materials used.
After looking around, I haven't seen any cookie-cutter solutions to this problem, but I also have a hard time believing I'm the first person to attempt to write a moddable game with Unity's engine. Are there any best practices for adding prefabs/assets at runtime?
AssetBundles are the way to go.
Basically you can create one or multiple assetbundle files from scenes or specific objects which pack everything into them.
Assetbundles contain everything you want, except new scripts. You can reference scripts but not create them per default.
If you want to bundle new scripts you need to create a ddl file and load that during runtime.

Unity3D HLAPI networking single player overhead

Using the Unity3D engine's high-level networking API (HLAPI) seems to be an all-or-nothing approach. For any game objects expected to be used in multiplayer, (most) behaviors need to be implemented as NetworkBehaviours, and Network components are required. Additionally, a Network Manager is required in all scenes. I'd rather not have duplicate network-enabled versions of all single-player assets, and it seems that the expected practice is for a single-player game to be realized as a LAN Host-based network game with only the single (localhost) client.
My concern is that the HLAPI stuff riding on top of absolutely everything will result in substantial overhead in single-player mode, which is the main focus of the game. Is this a valid concern?
I have considered a couple mitigation techniques, but they pose their own problems for maintainability and code complexity:
Prefabs needed in both modes will be duplicated (violates DRY: changes to one prefab need to be manually mirrored in the other)
Dynamically modify or replace single-player assets with multiplayer ones, or vice versa (complex and potentially error-prone)
What are some better mitigation techniques? Or are they even needed?
This is kind of an old question, but I figure I'd take run at it anyway. Could you detect when you're in single player mode, and in that case use Destroy to remove the components you don't need? For example:
http://answers.unity3d.com/questions/378930/how-delete-or-remove-a-component-of-an-gameobject.html

Where to start with GKMinmaxStrategist?

I was wondering if anyone here has had any luck using GKMinmaxStrategist. This class/feature was showed off at the WWDC, but most of the sample code was in Objective-C, which was a disappointment.
The WWDC videos for GameplayKit featured another game, Stone Flipper (Reversi/Othello), but they haven't published the code (yet?).
Has anyone had any luck with this? I was hoping to try this out with just a simple tic-tac-toe game, but am not at all sure how to start.
I agree that it's a tricky framework to learn – I just finished writing a tutorial about GameplayKit and GKMinmaxStrategist and it was no mean feat. If you follow the tutorial it builds a complete game from scratch, explaining how it all fits together. You might find it useful as a starting point, at the very least.
I'm hopeful that Apple will improve its documentation before iOS 9 is final!
If you want to dive straight in, here's the least you need to know:
Ensure your game model (data) and view (layouts) are kept separate.
Make your model implement the NSCopying protocol, because it will be copied many times as the AI runs.
You should also make it implement the GKGameModel protocol, which requires that you be able to enumerate the available moves, apply a move on a board copy (virtually, not for real), then judge the players scores afterwards.
Each "move" (for whatever that means in your game) needs to conform to the GKGameModelUpdate protocol, so it'll be a class you create that defines a particular move. You'll be given this back when you the best move has been chosen, so it will contain something like "move the knight to E4".
If your game does not have a score (in my tutorial I used Four in a Row, which has exactly this problem) then you need to come up with a heuristic estimating roughly how good a move was.
Run the AI on a background thread to ensure your UI remains responsive, then push the result back to the foreground thread when you're ready to make UI changes.
If you find the AI is running slowly, either restrict the number of moves it can make or reduce its look ahead depth.
Here's the GKMinmaxStrategist TicTacToe tutorial in Swift.
This should explain how things work and gives some pointers on how to make a good AI. The strategist surely isn't a template to create any kind of board game AI, it just provides a framework. 95% of the work still rests on your shoulders. ;)
The code is available here. Note that it not only requires Xcode 7 but also OS X 10.11. Though it should be straightforward to adapt to iOS 9.

Unity3D GameObject Code Structure

I am messing around in a Unity3D, making a 2D project. I want to create my own code architecture for Unity's component based system.
As I don't want to create God-Controller scripts, and being more into code resposibilities separation solutions ( having MVC, MVVM in mind ), I am trying to find some good solution.
My first take looks like this:
GameObject is created from:
Unity Components - for ex. SpriteRenderer, Animator, Rigidbody2D
Controller - The only resposibility of this component is to handle Unity functions ( like
Update, FixedUpdate, OnCollision ), and executes functions from model.
Models|Proxies - this components contains data, functions to manipulate game object unity components, and dispatching events to outer world.
I am wondering what do you think about this aproach, what are your code habbits in Unity3D projects, and what solutions worked for you.
While I have learned and taught MVC and similar approaches, I find that when designing game architectures one usually has to be a bit more flexible. In unity I generally take the following approach.
I will create a few GameObjects to hold the necessary global logic. This would be things like the overarching state machine, networking, and sometimes control input. If anything needs to persist between scenes it will go here. Each object typically has one component script for game logic and one for temp/debugging functions that gets turned off or removed when not needed.
If the project has fixed levels I will make each level a scene and I will store level layout and other level specific information in the scene. If I am doing a more procedural project I will create a "LevelGenerator" object with component scripts that build and populate the level at runtime.
If I am building a system that has lots of mostly independent agents (e.g. enemy creatures) I try to keep the game logic and necessary state information for each agent as close to it in the hierarchy as possible. For example, the agent's position and rotation would be stored in it's transform. I might store the agents health, ammunition, speed, and current status effects along with the functions for moving, shooting, healing, and death in a component script on the agent's GameObject.
While there are countless other approaches that could work, I like this approach for a few reasons:
It saves me from having to manually manage tons of data access in a central script. If I need to know where all the monsters are, I can just keep a list of game objects rather than using custom data types.
When the agent gets destroyed all the local data goes with it. (No complex functions to clean up dead agents.)
From a game logic perspective (on the projects I typically work on) it usually makes sense that each agent would "know" about itself and not about everyone else.
I can still use all the OO goodies like polymorphism etc. when necessary.
This response likely says more about how I approach game design and software architecture than general best practices but it might be useful.
One note on encapsulation in Unity. Every component script you add to a game object has a bit of overhead. If your scene has a couple of dozen agents in it, than this is not a big deal and I would recommend trying to keep things as OO and modular as possible. If you are building a system with hundreds or thousands of active agents, cutting the components per agent from two to one can mean quite a bit of saved frame time.
I use another approach.
I don't use many controllers attached to game objects. I just have some kind of GameController which creates other structures.
I have separate project shared between other games. This project contain design patterns and is built before main project did. I widely use State, Observer, Builder, ObjectPool etc. patterns to make my code clear and simple.
Another reason I use such approach is performance optimization. I create objects once and then reuse them. Also I do once such things as gameObject.GetComponent etc. When I need to create many objects using the same prefab I use ObjectPool to avoid CreateInstance/Destroy.
My logical game objects (actors) communicate each other using Observer pattern. My only one GameController just send events like Awake, Update to actors. Some objects have StateController which retranslate events like Awake and Update to current object state. This is useful to separate behavior of each object state.
I have component system architecture similar to Unity. And I also have services like InputService that can be accessed via ServiceLocator in any object.
I have also points, but the idea is clear and easy maintainable code. This is difficult with standard Unity controllers and SendMessage approach.