Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Discussion Dependency Injection in Unity - Vampire Survivors uses Zenject!

Discussion in 'General Discussion' started by TheNullReference, Apr 11, 2023.

  1. DragonCoder

    DragonCoder

    Joined:
    Jul 3, 2015
    Posts:
    1,459
    The irony is that, as it has been mentioned, Unity's "drag and drop" functionality for MonoBehaviors and GameObjects is effectively DI.
    Of course one could discus that it could be made even more versatile by supporting interfaces and some form of scene-bound prefab-variants (which would allow to drag a scene object into a field of the prefab). Those two features would reduce the occurence of Singletons/Managers further.

    Have opened a thread on this second suggestion!
    https://forum.unity.com/threads/idea-scene-bound-prefabs.1425693/
     
    Last edited: Apr 15, 2023
    SisusCo and TheNullReference like this.
  2. TheNullReference

    TheNullReference

    Joined:
    Nov 30, 2018
    Posts:
    222
    -
     
    Last edited: May 4, 2023
  3. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    13,321
    I would recommend to never use those sort of answers from a chatbot as a base of your judgement.

    The machine cannot truly think. Also, if you regenerate the answer enough times, you can get different response.
     
    angrypenguin, xVergilx and Ryiah like this.
  4. PanthenEye

    PanthenEye

    Joined:
    Oct 14, 2013
    Posts:
    1,763
    Event driven programming with manually passed around context objects is where I'm at right now. I've yet to reach the limits of this approach but I've also never worked on a large scale project by industry standards.
     
  5. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,124
    You're happy that you're too dumb to comfortably code boilerplate? Your initial posts came across as an enterprise developer with experience but between these statements and your being easily swayed by a blog post I'm starting to draw different conclusions which is making it difficult to take your statements about large projects seriously.

    Different prompts will give wildly different results too. I asked it to "rate the various ECS frameworks for Unity" and it gave scores for three of them (DOTS was scored an 85). Afterwards I asked "what about Zenject" and it pointed out that it wouldn't appropriate to rate it since it's not an ECS.

    upload_2023-4-16_10-41-52.png
     
    Last edited: Apr 16, 2023
  6. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,575
    Because you are starting from the middle, instead from the beginning.
    Your whole workflow is flowed. From how to address the problem, to how to learn about different solutions. It looks like you are trying to skip learning steps. As the result, causing your focus to be very narrowed down and as the result rage quit in the process.

    There are plenty sample to introduce you into DOTS paradigm. But if you start with boids algorithm, which chances are you never worked with before, you will be overwhelmed in the entry stage.

    Unity has HelloCube DOTS samples, for the entry level. Start there, instead from advance scripts samples. Then you will realise, it is not that complex at all.

    Also as I have pointed out in the past, you don't need to work with ECS straight away. You can start with DOD paradigm using jobs and burst. Learn these first, then look into ECS if you feel comfortable enough.
     
    Rewaken, The_Island, Luxxuor and 2 others like this.
  7. BIGTIMEMASTER

    BIGTIMEMASTER

    Joined:
    Jun 1, 2017
    Posts:
    5,181
    A better question to ask would be to define a project and then ask for example frameworks. And then run scenarios of various theoretical stages of project and see what the work would be like given each framework. As in, "creative director wants to change enemy types in our live service game - he wants to change model, animations, and behavior from X to Y".

    Even that is a lot of guessing but at least seems more constructive than "what are the top ten".
     
  8. Murgilod

    Murgilod

    Joined:
    Nov 12, 2013
    Posts:
    9,745
    You know that LLMs aren't actually intelligent and can't do evaluations like this, right?
     
    Ryiah and angrypenguin like this.
  9. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    15,509
    I was just writing something similar, and then realised you'd already said it in different words. It's all well and fun to be enthusiastic about the internal technical details or the high-level concept of clean code or whatever, but where the rubber meets the road only one question matters: how can you ship and maintain the project with the minimum overall effort?

    That's a deceptively simple question, e.g. "ship" and "maintain" often have competing priorities. Still, I find that asking that question helps to get things a bit more concrete. If I ask someone "how will this thing help us ship the project?" and they can't give me an actionable response (with a bit of guidance - it's not a trap!) then I have no reason to allocate resources to it. As far as I'm concerned, "actionable" almost always comes down to "we can put numbers on how it will impact people".

    "It will save dozens of hours of wrangling test wrappers" is very actionable, because when combined with project-specific info it can directly be used to make informed decisions. Does the project need testing? If yes, saving dozens of hours on it is probably pretty good! If no, then it'd be silly to spend resources on it.

    "It will reduce coupling" is not actionable because a manager can't estimate the impact that will have on the specific project in question. The best they could go with is generic theory answers ("coupling is bad"), but it's pot luck as to whether that'll apply in a particular case (i.e. it's probably a decent rule of thumb for something huge, but could be counter-productive in a throwaway prototype).
     
    Noisecrime and Ryiah like this.
  10. TheNullReference

    TheNullReference

    Joined:
    Nov 30, 2018
    Posts:
    222
    -
     
    Last edited: May 4, 2023
    Rewaken and DragonCoder like this.
  11. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,575
    I tell you a little real life anecdote.

    In the small team, one small dev loved looking into low level optimization's etc. Had some software engineering, but no real game dev experience. Yet was able to write quite complex, clever systems and whats not. However, often overengineered.

    One upon time little dev has been hit by one bug, from other dev. So the first little dev get quite upset on the bug, instead spending 5 min on the fix, as it was simple enough, decided that need automation tools to auto solve the problem and bug catcher. Little dev spend "just" few weeks writing and testing automation tool, so it functions for multiple existing systems. While one bug type was now able ot get couth faster, whole application become unstable, and difficult to debug. Problem was, such issue wasn't apparent at first, but it came to light quite a time later during more extensive tests, down the line in dev, which made reverting changes quite complex. In the end, relevant systems had to be redesigned few months later.
     
  12. The_Island

    The_Island

    Unity Technologies

    Joined:
    Jun 1, 2021
    Posts:
    502
    Lets me ask a question. You said:
    What do you expect from Unity? You want DI in Unity. It already exists. It is VContainer. So what do you want more?

    Here is my personal opinion, not Unity's opinion. I really wish we focus more on improving what already exists. I don't want more options but better ones. Through all these discussions, we seem to agree that you can solve the same issue with existing tools (SOAP, Event-driven, VContainer, etc.) So I am unsure how adding another way to do the same thing would improve the engine.

    And maybe this is a hot take, but I think ECS would be a good solution in all 4 cases. I would argue someone who knows how to use ECS could be as fast to prototype as someone using simple Singleton. The main issue is that DOD is an entirely different way of thinking for most, so it is not just about relearning a library but relearning how to think about the problems. And even today, where we still don't have an animator solution for ECS, I found the hybrid way quite good. I don't know if you watched the talk at GDC but it goes more on the topic of how they made it friendly to artists.

    Also as you mention, you can get surprises along the way. Something that starts as simple that doesn't need performance can become a vital part of your game. Then you are f*ck. For example, I am doing a turn-based game. At first, I thought performance was not critical to the project. But then I realized further that getting a good and interesting AI is expensive since you probably want to consider future moves.
     
    SisusCo, Rewaken, NotaNaN and 6 others like this.
  13. PanthenEye

    PanthenEye

    Joined:
    Oct 14, 2013
    Posts:
    1,763
    No framework will save you from bad management.
     
  14. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    13,321
    Once again, not a good idea.
    upload_2023-4-17_9-28-12.png
    If it suggested using VContainer for an asteroids game, it is incompetent. A human response would be "why the hell would you need DI for something like that?"

    The "AI overlord" is instructed to tell you things you find pleasing, that's the first problem. It is also instructed to be encouraging, supportive, and friendly, meaning if you're suggesting something downright insane or a bad idea, ChatGPT will waste a page of text sugarcoating it, only to leave a subtle hint that maybe you should try something else.

    The second problem is that the "AI overlord" creates an INCREDIBLY convincing illusion of being a person (takes about a month to to start seeing through it). As a result some people has used ChatGPT to generate texts that agree with their opinion and attempted to use that as an argument. "The robot agrees with me, therefore I'm right". Kinda does not work like that, it is like using a magic 8 ball to support your statements.

    The best way to use ChatGPT is learning new topic, summarizing things, and performing some grunt work on text. Even in this case you'd need to watch out for hallucinations and insanity. When you start asking it to rate stuff, that's the job you should be doing.
     
    Ryiah, xVergilx and Noisecrime like this.
  15. xVergilx

    xVergilx

    Joined:
    Dec 22, 2014
    Posts:
    3,292
    Nothing will help you in this case. As mentioned, poor management cannot be band-aid fixed by better frameworks.

    Something that is written as singleplayer app won't run out of the box as multiplayer one, because that's more than programming problem. That's game design problem. And game design problems tend to have quite devastating results on the codebase.

    This.

    While it may look daunting, actual Entities package is quite simple to understand.
    Try using it without multithreading and you would quickly realize how simple it is, and how much it actually works like DI (actually better).

    As for the work speed - Once you've got experience with ECS and have a bunch of projects - generic system logic can be transferred from one project to another. Pretty much Copy&Paste with test coverage. Minor changes may be required but this speeds up work on anything drastically. Adding or removing features is pretty fast as well.


    Also, I have a feeling that OP tries to sit on the two chairs simultaneously.
    Skills & frameworks that apply to business apps does not work with game development:

    - C# for Unity is not the same .Net C# as in default business apps;
    - H[igh]P[erformance]C# is not the same as .Net C#;
    - Mono internals work differently;
    - Translated code into C++ via IL2CPP is not the same as you would expect.
    E.g. interfaces have actual overhead.
    - Patterns that you've used in business apps are actually anti-paterns that will ruin your application and productivity because they're slow. In both cases.

    Also:
    - ScriptableObjects aren't optional.
    Those are immutable read only data storages. Building architecture on them by passing logic via them is a mistake though. Using them for anything else is going to be a costly refactoring later on.
    - Using ChatGPT instead of common sense will bring you only pain & suffering.
     
    Last edited: Apr 17, 2023
    Luxxuor, Ryiah, ippdev and 2 others like this.
  16. koirat

    koirat

    Joined:
    Jul 7, 2012
    Posts:
    2,008
    Can you give me the link to common sense ?
     
    Rewaken, Ryiah, DragonCoder and 2 others like this.
  17. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    13,321
    When facing a problem in a specific domain, if you gather around a dozen of people who worked with that domain for a decade, their combined opinion will be common sense. For that domain. Because "common sense" is a "thing everybody knows" (again, in that domain).

    ChatGPT does not represent such groups, because it hallucinates, cannot think, and it is unknown what it was really trained on.

    In OPs case it appears that he is new to the problem domain, so the right idea would be to gather information from other humans, and learn what common sense for this domain is.
     
    Ryiah and xVergilx like this.
  18. xVergilx

    xVergilx

    Joined:
    Dec 22, 2014
    Posts:
    3,292
    Neuralink moment :D

    My point is - think, try out & test first.
    Do not rely upon some pre-alpha tech to make opinions & judgement for you.
     
  19. TheNullReference

    TheNullReference

    Joined:
    Nov 30, 2018
    Posts:
    222
    That's fair. It would be great if Unity was able to hyper focus on polishing ECS. It seems like the codebase is starting to stabilize, but I'm not sure it's ready as a full solution.

    However there's also blog posts like this:
    https://blog.unity.com/engine-platform/unity-and-net-whats-next

    I'm not sure what implications moving Unity to .NET has for ECS. I'm also a little worried about how long it will take ECS to mature. I still use the built in render pipeline despite URP being released 5 years ago. We've coded a certain way in Unity for the last 10 years, it might take another 10 years for the paradigm to shift to ECS.

    Veteran programmers need to retire, new students need to learn ECS, that means the popular Youtube and Udemy courses need to cycle out and make room for new ECS, the majority of the third party packages need to be ECS, Legacy projects need to die off. There's so much momentum behind Classic Unity I think it will be very hard to shift the dynamic.

    That's encouraging to hear, that ECS is suitable for prototypes. It would be cool to see more ECS gamejams, or ECS micro games. I might give it another look.
     
  20. Agoxandr

    Agoxandr

    Joined:
    Aug 16, 2014
    Posts:
    44
    Nice thread. I would like to add my 5 cents if no one minds.
    I tend to write managers a lot. Sometimes they are singletons. Sometimes I have managers that manage a few GameObjects with custom components.

    While I really don't care about SOLID that much in principle, I have an EventManager that works a lot like other .NET based game engines.

    Code (CSharp):
    1. public delegate void UpdateAction();
    2. public static event UpdateAction Updated;
    This is invoked in Update() once by the EventManager.
    Then I can subscribe to Updated as my times as I want (with different conditions) in a single MonoBehaviour to do "single responsibility". The only problems that I face is that I need to remember to unsubscribe, because otherwise really weird stuff starts to happen.

    Combining this with polymorphic ScriptableObjects and data structs adds enough structure for me.
     
  21. Murgilod

    Murgilod

    Joined:
    Nov 12, 2013
    Posts:
    9,745
     
    angrypenguin and Ryiah like this.
  22. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    13,321
    Regarding this example:
    This situation is what I call "Model Collapse". It happens when you start with initial requirements, create a system of classes for it (worst case scenario - an elegant system of elegant classes), then client submits new requirements, and eventually reach the point where your next feature cannot be fit in, because it is incompatible with the very foundation of the model.

    Here's the thing. Such scenario should not occur with an experienced dev. "We have to rebuild 80%" is an indication that something is terribly wrong. Another indication that something is wrong is "you explicitly SAID". This part should be agreed upon in writing and documented, as verbal agreements are not reliable.

    In my experience, this sort of scenario happens in cases where developers overuse OOP. When you start designing class hierarchies you put yourself in position, where a change at the bottom level can wreck your codebase, because everything is affected. Avoiding this situation is a rationale behind KISS and YAGNI principles. Because ruthlessly reducing complexity and exterminating all that is not immediately necessary reduces chances that a model collapse is going to occur. If it occurs, you do not "rewrite 80%", you refactor. While maintaining version control. There was an article about it, written 23 years ago:
    https://www.joelonsoftware.com/2000/04/06/things-you-should-never-do-part-i/
    Because while you're rewriting 80% and replace tested code with brand new untested code full of bugs, your competitors keep improving their product.

    Obviously, in your example, there's another guilty party. The "Product Owner". They decided "To boldly go where they haven't set foot before", while not understanding the target market. This is a recipe for a disaster. Typically you'd want to try spot and avoid such projects.
     
    xVergilx, Ryiah and ippdev like this.
  23. BIGTIMEMASTER

    BIGTIMEMASTER

    Joined:
    Jun 1, 2017
    Posts:
    5,181
    Well, that is a start, but it's nothing I'd base any real decisions on. Next step would be actually testing the theories.

    The chatbot can help a bit with blocking in the frameworks and understanding basic principles of them. That can be a big speed boost to build some simple test environments. Then can actually get practice implementing the ideas and get a little closer to understanding what implications would be in real life scenario.
     
    angrypenguin likes this.
  24. andyz

    andyz

    Joined:
    Jan 5, 2010
    Posts:
    2,132
    Come on, just listen to your new AI masters:
    Should I use dependency injection in Unity development?

    ChatGPT: Yes, you should use dependency injection in Unity development. Dependency injection (DI) is a software design pattern that helps to create loosely coupled and more testable code. It is a way of providing the necessary dependencies to a class, instead of creating them inside the class.

    In Unity development, DI can be particularly useful when creating complex game objects with multiple components. It allows you to easily swap out components and services without having to change the code of the game object. This can be helpful during development, as it can make it easier to iterate on your game without having to re-write large sections of code.

    There are several DI frameworks available for Unity development, including Zenject, StrangeIoC, and Unity's built-in dependency injection framework. These frameworks provide a way to manage dependencies and create object graphs automatically. They can also help with object pooling, memory management, and other performance optimizations.

    Overall, using dependency injection in Unity development can help you write cleaner, more modular code that is easier to maintain and test.


    "Unity's built-in dependency injection framework" - yep got it already so no problems!!
     
  25. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    15,509
    Aye, with one possible exception none of them contain information I'd base those decisions on. I don't care if it's an "indie game" or a "business application". What I care about for my code architecture is what kind of problems my code has to solve. The one scenario which has a bit of useful info in there is the RTS with thousands of entities - that's one bit of information which will significantly influence a significant part of my architecture.

    Indeed. After I got a bit of experience designing software for clients I started to deliberately "design for flexibility". I would purposely design so that we could change things without wrecking other things. It mostly came down to a good balance of the various trendy acronyms people throw around, without any of them being treated dogmatically.
     
    ippdev likes this.
  26. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,575
    @Simon_Nordon and why you delete the OP post with its title?
    This is unwelcome behaviour on the forum. And in fact against the rules.
     
  27. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,124
    Almost all of their posts were deleted too.
     
    Last edited: Apr 18, 2023
    Antypodish likes this.
  28. DragonCoder

    DragonCoder

    Joined:
    Jul 3, 2015
    Posts:
    1,459
    He deleted all his posts too q_q

    Good way to destroy a meaningful thread that might otherwise be referenced when the topic DI for Unity comes up again...

    @Simon_Nordon
    If you are somehow ashamed for having had an opinion that wasn't 100% supported (- very silly to be ashamed of that-), rather start a new account instead of digging a grave this way.


    Maybe @zombiegorilla can restore the posts?
     
    Antypodish likes this.
  29. BIGTIMEMASTER

    BIGTIMEMASTER

    Joined:
    Jun 1, 2017
    Posts:
    5,181
    could maybe change the username if by chance they were worried about having some post come back to bite them or something like that, rather than nuke an interesting thread

    yeah it's weird. I thought for sure any professional teams doing this sort of work go through phase of preproduction first where you have methods specifically for answering these sorts of questions. Am I wrong about that? Certainly companies building "big" projects aren't just winging it?
     
    Last edited: Apr 18, 2023
  30. zombiegorilla

    zombiegorilla

    Moderator

    Joined:
    May 8, 2012
    Posts:
    8,967
    Yes. Done.

    As a reminder, this kind of behaviour is unacceptable. The edit button to is to edit for clarification/spelling/etc or add, not to remove. A conversation on these forums belongs to the community,
     
  31. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    15,509
    That depends very much on the team! Yes, the good ones aren't winging it, though there's always some level of uncertainty about at least some parts of the project, which usually leaves some things to be answered later, via experimentation, prototyping, research, etc.
     
    spiney199 likes this.
  32. TheNullReference

    TheNullReference

    Joined:
    Nov 30, 2018
    Posts:
    222
    Apologies I didn't know it was against the rules. There's usually no benefit to leaving a digital footprint.

    I'm going to continue using VContainer for now and will post updates on where I get to with that. If I do hit a wall, my last option will be to switch to ECS.

    I acknowledge that IoC built for business applications is going to be difficult to insert into a gaming framework. Perhaps there's some ideas / or benefits that can be taken from it.

    One example might be the idea of Scopes, allowing people to use Singleton Pattern in a safer way.
     
    NotaNaN and angrypenguin like this.
  33. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    13,321
    The whole point of forums is to leave the footprint for future users.

    The idea is that you face a problem, you solve the problem, then the solution remains for those who face similar problems in the future or have similar questions. So everybody benefits and nobody will have to reinvent the wheel. The knowledge accumulates and future users can "stand on the shoulders of giants". The information is supposed to stay her forever.

    When you wipe out your discussion, you destroy work of people who helped you for free. And deny those who will come next with the questions the knowledge you received. That's why it is frowned upon.

    Having said that, it wouldn't surprise me if younger people who are into discord and the services like that are unaware of the whole thing about accumulating knowledge. Because all information in services like discord is not shared with others and evaporates without a trace.

    If you fear being tracked, then that's what your nickname is for. It acts as a proxy between you and the internet. Having said that a modern internet user usually leaves so many footprints that they'll be trackable whether they want it or not. The only true way to stay truly anonymous is to stay offline.
     
  34. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,575
    And yet you we ere using AI tools to generate suggestions for your wokflow. How you think such AI tools were trained? If discord would be only thing in the world, it would be extremely difficult to get into current AI and knowladge advancement. In fact, current discord design is leading into degradation of human knowledge. Hard to be searchable and crawled.

    So yes, each digital footprint has extreme massive inpact on the knowledge access, as well as the opportunity for generative tools progress.

    You are most likely been informed by an admin already, but please read Unity forum rules again, if you not familiar with them.
     
    neginfinity and DragonCoder like this.
  35. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    15,509
    Even before this bit, you're the only person (I've noticed) who started up a topic about DI and then listened to people and looked up other approaches.

    That aside, games need editors, and back-end services, and distribution systems, and all sorts of other stuff that doesn't necessarily have to run with a real-time renderer at 60hz, but might have to be maintained for a long time on various platforms and with a shifting stack of underlying services. While it's not strictly "games", tools such as Unity are finding their way into other industries where they're increasingly likely to be integrated with other existing systems and pipelines, too. So this stuff all definitely has its place.
     
    NotaNaN and Ryiah like this.
  36. frosted

    frosted

    Joined:
    Jan 17, 2014
    Posts:
    4,044
    @Simon_Nordon - I'm not a fan of DI in unity, but I'd take this thread with a grain of salt.

    There are definitely serviceable projects that have used DI and been released successfully. Using DI will add some complication but won't break the project or turn it into a disaster.

    If your team is mostly coming from an enterprise background, it can make sense to use tooling they're deeply familiar with, even if it isn't optimized for this specific environment.

    People are way too obsessed with tooling decisions or 'architecture'. Almost anything will be at least ok if executed well, and anything will be a trainwreck if executed poorly.

    Almost all projects are executed poorly and the design decisions will only slightly alter the flavor of trainwreck you make.
     
    SisusCo, Rewaken, spacefrog and 2 others like this.
  37. BIGTIMEMASTER

    BIGTIMEMASTER

    Joined:
    Jun 1, 2017
    Posts:
    5,181
    Personally I've found massive time/energy savings after having tried out a few paradigms and finally settling on something that makes sense for me. The difference is like, thrutching through code and then having something totally unmaintainable a month later, compared to being able to code intuitively and having a code base that doesn't require me to remember any specifics when I have to debug or extend later.

    I think its probably one of the most important things to get right. Which is why I wouldn't want to rely on any group consensus, but rather test thoroughly.

    Its been mentioned already but no architecture will save from extreme changes in games design. No matter what you have to redo ton of work if the game dramatically changes. That's probably the number one problem is that people don't know exactly what the end product is meant to be, and they do too much high-effort work before nailing down the plan - much of which can be thoroughly iterated on in low effort ways.
     
    SisusCo and Ryiah like this.
  38. TheNullReference

    TheNullReference

    Joined:
    Nov 30, 2018
    Posts:
    222
    Yea I agree. My last job I was unfamiliar with creating BIG projects. I started how I normally do, trying to adhere to GameObject - Component Architecture with a sprinkling of scene bound managers, events, callbacks, coroutines just to tidy up the edges. They where extremely happy with the speed of the development, I think in 3 months we went from nothing to showing over 100 people in a live multiplayer demo. I was the only developer, 3D modeler and UI designer at the time. We brought on 4x 3D modelers and 2x developers and after maybe 12 - 15 months the project became very hard to maintain, push builds and had hundreds of bugs.

    I understand this is mostly my fault, I was only focused on the experience and naively thought I'd only be working on the app for a maximum of 12 months. I think that was 2.5 years ago now. However, even if I could go back in time and do it all again, I'm not confident I know enough to have avoided the same thing happening. i.e. I'm not sure I know of a pattern / framework that wouldn't inevitably lead to the same place, while maintaining the speed of development. I left that place and the remaining programmers spent a lot of time fixing it and have done a really good job, but took 3-6 months of refactoring.

    I'd like to know (from experience) that I could work and maintain a large project for an extended period of time, that's what I'm trying to do in my personal projects.
     
  39. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,124
    Were you told that this project would be long time? If you look back at the project and the requirements you were provided by the employer at the start would you say that the project would have been long term had you more experience?

    I'm asking because the company I'm contracted through had an employer that started off with requirements that seemed very reasonable only to keep shifting requirements as the project progressed. I'm not talking minor shifts either. I can't remember everything they kept pivoting to but it had no chance of success with those pivots.
     
    Last edited: Apr 19, 2023
    angrypenguin likes this.
  40. CodeKiwi

    CodeKiwi

    Joined:
    Oct 27, 2016
    Posts:
    119
    Just thought I’d give my personal opinion on this. One thing I’ve found with larger projects that are maintained over a long period of time is that they tend to focus on Unit tests. So I’d say that the main purpose of a DI framework tends to be supporting Unit tests. I also find that some design patterns and principles that seem like a waste of time make a lot of sense when Unit testing.

    graph2.png
    Every new line of code has the possibility of breaking any of the existing code. As the code base increase it starts getting to the point that each bug fix creates multiple new bugs. This would also still be the same issue even if I used a DI framework without Unit tests. With Unit testing you can ideally get a more linear level of progress. Any new code shouldn't break the existing code and if it does I can catch the error before giving it to QA.

    Personally I don’t tend to use Unit testing much in games mainly because:
    • I probably wouldn't reach the break even point on the graph. Smaller mobile games would generally be far to the left of the graph so I’d probably end up spending 90% of my time dealing with tests / frameworks and only 10% on the game.
    • Games requirements tend to rapidly change. So it would be quite common to spend a lot of time writing tests that are thrown away.
    • You can't Unit test a MonoBehaviour, ScriptableObject etc.
    If it was a very large project with a long life (maybe an MMO) then it might be worth doing more Unit tests. If I don’t plan on doing Unit tests then I normally find that a DI framework isn’t worth the effort and stick with standard Unity.
     
    Last edited: Apr 19, 2023
  41. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    15,509
    Sure you can, I've done it. Why not?
     
    SisusCo likes this.
  42. CodeKiwi

    CodeKiwi

    Joined:
    Oct 27, 2016
    Posts:
    119
    Interesting, I haven’t tried Unit testing a MonoBehaviour in ages so maybe it’s changed recently. I’ll have to do some extra research later. Originally I based it on this blog post which suggests that it isn’t possible.

    Let’s say I have the following MonoBehaviour
    Code (CSharp):
    1. public class Ship : MonoBehaviour
    2. {
    3.     public Ammo ammo;
    4.     public PrefabSpawner projectileSpawner;
    5.  
    6.     public void Fire()
    7.     {
    8.         if (ammo.IsReloading)
    9.         {
    10.             return;
    11.         }
    12.         else if (ammo.HasAmmo)
    13.         {
    14.             projectileSpawner.Spawn();
    15.             ammo.ConsumeAmmo();
    16.         }
    17.     }
    18. }
    I now want to create some tests e.g. not IsReloading and HasAmmo then it should spawn a projectile and consume ammo. So I'd like to mock the ammo and projectileSpawner dependencies. I can’t use interfaces (IAmmo) and I can’t instantiate a MonoBehaviour with the new operator. So as far as I know I can’t use a mocking framework. The blog post uses the Humble Object Pattern but at that point I'm testing a standard class.
     
    Last edited: Apr 19, 2023
  43. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    13,321
    Why not just spawn it with AddComponent? And why even rely on that blog post in the first place?
     
  44. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    15,509
    This was ages ago. We didn't use a mocking framework. We just configured (or loaded) scenes with content as required to test what we needed and ran them as required.

    Though do note that the post you're referencing is from 2014, approaching a decade old. I didn't read it, but wouldn't be surprised if it's no longer correct.
     
    Last edited: Apr 19, 2023
  45. Luxxuor

    Luxxuor

    Joined:
    Jul 18, 2019
    Posts:
    89
    That is a great point that has not been touched on in this thread: Even if you think you need DI for testing it's most likely easier and better maintainable to instead setup the test as scenes, prefabs or some other asset form, load it and then check the output (can also be contained as data or could be reference screenshots).
    It also opens up the possibility for non programmers to create tests by adding new scenes etc.
     
  46. xVergilx

    xVergilx

    Joined:
    Dec 22, 2014
    Posts:
    3,292
    Testing with ECS is even simpler than using DI. No need to mock system logic, only data.
    Using testing as pro-DI thing is kinda wrong.

    As mentioned, you can setup tests for any approach.
    Real question is how viable they are and how much time it takes to set them up & maintain.
     
    CodeKiwi likes this.
  47. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,124
    Unity released their own testing framework a few years ago. Here's an example that functions along the lines of what @angrypenguin described.

    https://docs.unity3d.com/Packages/com.unity.test-framework@2.0/manual/index.html

    Code (csharp):
    1. using System.Collections;
    2. using NUnit.Framework;
    3. using UnityEngine;
    4. using UnityEngine.TestTools;
    5. using UnityEngine.SceneManagement;
    6.  
    7. public class ShipTests
    8. {
    9.     private string originalSceneName;
    10.  
    11.     [SetUp]
    12.     public void SetUp()
    13.     {
    14.         originalSceneName = SceneManager.GetActiveScene().name;
    15.         SceneManager.LoadScene("TestScene");
    16.     }
    17.  
    18.     [TearDown]
    19.     public void TearDown()
    20.     {
    21.         SceneManager.LoadScene(originalSceneName);
    22.     }
    23.  
    24.     [UnityTest]
    25.     public IEnumerator Fire_WithAmmoAndNotReloading_ProjectileSpawnedAndAmmoConsumed()
    26.     {
    27.         // Arrange
    28.         var ship = GameObject.FindObjectOfType<Ship>();
    29.         ship.ammo.IsReloading = false;
    30.         ship.ammo.HasAmmo = true;
    31.  
    32.         var initialAmmo = ship.ammo.CurrentAmmo;
    33.         var initialProjectileCount = ship.projectileSpawner.spawnedObjects.Count;
    34.  
    35.         // Act
    36.         ship.Fire();
    37.         yield return new WaitForSeconds(0.1f);
    38.  
    39.         // Assert
    40.         Assert.AreEqual(initialAmmo - 1, ship.ammo.CurrentAmmo, "Ammo not consumed correctly.");
    41.         Assert.AreEqual(initialProjectileCount + 1, ship.projectileSpawner.spawnedObjects.Count, "Projectile not spawned.");
    42.     }
    43.  
    44.     [UnityTest]
    45.     public IEnumerator Fire_WithoutAmmo_DoesNotFire()
    46.     {
    47.         // Arrange
    48.         var ship = GameObject.FindObjectOfType<Ship>();
    49.         ship.ammo.IsReloading = false;
    50.         ship.ammo.HasAmmo = false;
    51.  
    52.         var initialProjectileCount = ship.projectileSpawner.spawnedObjects.Count;
    53.  
    54.         // Act
    55.         ship.Fire();
    56.         yield return new WaitForSeconds(0.1f);
    57.  
    58.         // Assert
    59.         Assert.AreEqual(initialProjectileCount, ship.projectileSpawner.spawnedObjects.Count, "Projectile should not be spawned.");
    60.     }
    61.  
    62.     [UnityTest]
    63.     public IEnumerator Fire_WhileReloading_DoesNotFire()
    64.     {
    65.         // Arrange
    66.         var ship = GameObject.FindObjectOfType<Ship>();
    67.         ship.ammo.IsReloading = true;
    68.         ship.ammo.HasAmmo = true;
    69.  
    70.         var initialProjectileCount = ship.projectileSpawner.spawnedObjects.Count;
    71.  
    72.         // Act
    73.         ship.Fire();
    74.         yield return new WaitForSeconds(0.1f);
    75.  
    76.         // Assert
    77.         Assert.AreEqual(initialProjectileCount, ship.projectileSpawner.spawnedObjects.Count, "Projectile should not be spawned.");
    78.     }
    79. }
     
    Last edited: Apr 19, 2023
  48. TheNullReference

    TheNullReference

    Joined:
    Nov 30, 2018
    Posts:
    222
    Originally the project was going to be for use inside a physical studio, so maybe 1000 users per year, but with COVID the requirements changed and quickly turned into an online SaaS product, with ideally millions of users. I had never built a backend, authentication our cloud content delivery system so was mostly winging it. All the usual fun of a startup, a good way to jump into the deep end.

    I think this is a motivator to use some kind of IoC Container. I'm particularly interested in play mode integration tests. I agree with you that Unit tests start to lose their value, but integration test might have some validity. Like loading up a character, making it sure they can move to a location, making sure they can fire their weapon, if they get hit to they lose health etc.

    I did managed to get memory pooled scope prefabs working in VContainer yesterday. It was painful. Here's how I have to register a pool of scoped game objects.

    Code (CSharp):
    1.        
    2. builder.RegisterEntryPoint<ScopePool<EnemyFacade>>(Lifetime.Scoped)
    3.    .WithParameter(builder)
    4.    .WithParameter(enemyPrefab)
    5.    .WithParameter(10)
    6.    .WithParameter(new GameObject("Enemies").transform)
    7.    .WithParameter("Enemy")
    8.    .AsSelf()
    9.  
    With scope pool just being a generic monobehaviour pool. Although I could have just registered an already constructed instance, but that's manual dependency injection which defeats the purpose. I should be able to wrap this up into an extension method, but now I'm extending the framework.

    My biggest resistance to ECS at the moment is that in my professional work I'm doing exclusively VR/AR Content with a heavy emphasis on Timelines. I heard it's quite difficult to use ECS with VR and I'd also essentially be stealing for my employer if I used my time to teach myself how to do something I already know how to do in a new framework. I'm also not using IoC at work for the same reason.

    I know ECS is inevitable, if I don't experiment with IoC now then I'll never know.
     
    Last edited: Apr 20, 2023
  49. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,124
    Yeah I would never consider that to be your fault. Who is hired, what skills they have, etc is vastly different between those two sets of requirements.
     
    Last edited: Apr 20, 2023
    xVergilx likes this.
  50. xVergilx

    xVergilx

    Joined:
    Dec 22, 2014
    Posts:
    3,292
    Managed systems (SystemBase) can operate on managed objects by adding them via EntityManager.AddComponentObject();

    Then you can query those in the system & work with them just like any other behaviour.

    As for the hard for VR - nah. That's Entities Graphics that may be not suited for the rendering. But the actual Entities work with anything pretty much. Packages like Entities Graphics, or [even] subscene baking are optional as long as you've got a replacement for it.

    Surely not worth changing tech stack while product in the production, but definitely worth exploring in free time.

    Just be aware that parented objects to the same root cannot be processed by Unity's default transform system in parallel. Meaning you're loosing on performance just by doing that.
     
    ippdev, Ryiah and angrypenguin like this.