Unity3D GameObject Code Structure - unity3d

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.

Related

Unity: persistence between scenes practical advice

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.

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

Best practices for implementing levels in cocos2d games

I'm making a simple cocos2d adventure game, but have no clue how to implement any sort of levels. I've searched for tutorials, but can't find any.
Is there anything I can use to figure out levels in cocos2D?
Thanks
There are so many ways to implement levels in a cocos2d game. I think a straightforward way is to:
Modeling your levels first. Decide what should be stored in a level's data model. I think typically you will have at least two kinds of data:
Player data (Run-time generated, e.g. score, character's current location, etc.)
Level data (e.g. what's on the screen in this level, the rule to pass this level, etc.) This data could be either fixed or dynamic. If the levels are designed by developer, like Angry Birds, you can store this part of data in external configuration files and load them on demand; if the levels are dynamically generated according to some rules, then the rules should be stored in the data model.)
Design a general game-play layer which can be initialized according to an instance of the data model above. The layer class controls the presentation of the level, and is responsible for user input handling.
If your levels shares some global data, you can make another shared data model to manage these things (e.g. total score, achievements, player's name, etc.). Create a shared instance of this class and manage the data in it via your game-play layer.
You could also consider more advanced way like using scripts (such as Lua) to implement the levels.
You mentioned not being about to find any tutorials. I agree that finding free online tutorials for cocos2d can be challenging. I ran into the same problem when I started learning it. I recommend grabbing a book on cocos2d such as Learning cocos2d. There is so much to the API that you will have a very hard time creating even a rudimentary game without any tutorials or guidance, unless you have a lot of prior programming experience.

OpenGL render state management

I'm currently working on a small iPhone game, and am porting the 3d engine I've started to develop for the Mac to the iPhone. This is all going very well, and all functionality of the Mac engine is now present on the iPhone. The engine was by no means finished, but now at least I have basic resource management, a scene graph and a construction to easily animate and move objects around.
A screenshot of what I have now: http://emle.nl/forumpics/site/planes_grid.png. The little plane is a test object I've made several years ago for a game I was making then. It's not related to the game I'm developing now, but the 3d engine and its facilities are, of course.
Now, I've come to the topic of materials, the description of which textures, lights, etc belong to a renderable object. This means a lot of OpenGL clientstate and glEnable/glDisable calls for every object. What way would you suggest to minimise these state changes?
Currently I'm sorting by material, since objects with the same material don't need any changes at all. I've created a class called RenderState that caches the current OpenGL state and only applies the members that are different when a different material is selected. Is this a workable solution, or will it grow beyond control when the engine matures and more and more state needs to be cached?
A bit of advice. Just write the code you need for your game. Don't spend time writing a generalised rendering engine because it's more than likely you won't need it. If you end writing another game then extract the useful bits out into an engine at that point. This will be way quicker.
If the number of states in OpenGL ES as high as the standard version, it will be difficult to manage at some point.
Also, if you really want to minimize state changes you might need some kind of state-sorting concept, so that drawables with similar states are rendered together w/o needing a lot of glEnable/glDisable's between them. However, this might be sort of difficult to manage even on the PC hardware (imagine state-sorting thousands of drawables) and blindly changing the state might actually be cheaper, depending on the OpenGL implementation.
For a comparison, here's the approach taken by OpenSceneGraph:
Basically, every node in the scene graph has its own stateset which stores the material properties, states etc. The nice thing is that statesets can be shared by multiple nodes. This way, the rendering backend can just sort the drawables with respect to their stateset pointers (not the contents of the stateset!) and render nodes with same stateset together. This offers a nice trade-off since the backend is not bothered with managing individual opengl states, yet can achieve nearly minimal state changing, if the scenegraph is generated accordingly.
What I suggest, in your case is that you should do a lot of testing before sticking with a solution. Whatever you do, I'm sure that you will need some kind of abstraction to OpenGL states.