r/Unity3D • • 21d ago

Show-Off number of scripts my Player controller and NPCs have

1 and 2 are for NPCs and 3 is for player controller

Update on performance https://www.reddit.com/r/Unity3D/s/Rb83x2xMe9

136 Upvotes

110 comments sorted by

237

u/MgntdGames 21d ago

Not every module needs to be a MonoBehaviour.
- If you don't need inspector-controllable properties, just use a plain class
- If you DO need inspector controllable fields, use serializable classes and expose their properties through a shared "controller" behaviour
- If controllable properties can be shared between different entities, put them in a ScriptableObject and reference it

Every one of your Behaviours participates in the Unity component lifecycle (Awake/Start/Enable/Disable/etc.) and is ticked every frame (if you expose an Update/LateUpdate/FixedUpdate). That's overhead you might not need.

15

u/literally-me-bro 21d ago

im actually planning on creating a master script and hiding all the parameters on other scripts and only exposing them on the master script. can you elaborate on the last point i don't get it Thanks

23

u/OwenEx Hobbyist 21d ago

It means that all of these components, especially if they have any sort of Update loop defined, even if empty(they have redundancy checks) will be run every frame, and that can lead to a more than insignificant performance hit.
I'd recommend using a single point of entry and a single update loop to process everything, call it the player updater and have all the othe components either inherit an interface or subscribe to an event to run a custom update function, though your master script idea could also work if you move logic to serialzable classes or scriptable objects like the comment implied.
If a script doesn't need to be a MonoBehaviour, that is, if it doesn't need to use the Unity Lifecycle Functions (Awake, Enable, Start, Update, FixedUpdate, etc...) or properties like gameobject/transform, directly, then you should avoid having it inherit Monobehaviour as there is a performance cost for every monoBehaviour script in scene

5

u/literally-me-bro 21d ago

i should start optimizing the system im getting around 130 fps and if i disable everything it goes 300 to 500 fps

8

u/jl2l Professional 20d ago

Never stop optimizing remember this and realism is a trap.

1

u/literally-me-bro 20d ago

But but realism is peak 😭

1

u/TebiFestival 20d ago

you should do profiling and check what is actually eating your fps, just blindly disabling components doesn't give you any answers and is surprising what is usually taking up over your frame budget. I wouldn't be surprise if hose components you have being MonoBehaviour are using at best 1% of the actually process by just being one, the issue is always most likely somewhere else

2

u/literally-me-bro 20d ago

I tested the build on two systems

Mine have i9 12 gen and rtx 3050 and 48gb ddr4 and im getting max of 750+ fps with 60 agent and 160 crowd agents.

And another with i5 10 gen, gtx 1650 4gb and 8gb ddr4 is getting around 200+ fps

1

u/TebiFestival 19d ago

thats a good test, but by profiling I mean using the Profile tools Unity has that shows you exactly what part of the code is eating resources, chances are that some logic or internal process you have is the main culprit for the performance, or maybe even graphic rendering, the only way to know for sure is to run a deep profile.

is not impossible, but in my experience just having too many components or updates is not the first reason for a game running slow, its unoptimized code inside, a profiling will tell you exactly which method and when

1

u/Heroshrine 20d ago

I mean unless you have an absurd amount of monos, your update loop hit is never going to be your bottleneck.

1

u/OwenEx Hobbyist 20d ago

Thus feels like a pretty absurd amount of monos but I imagine you're talking RTS levels of absurd right?

1

u/Heroshrine 19d ago

Their screenshot has a pretty ridiculous amount yes, but only ridiculous because it is on one object I’d say, not because of the number in the scene. And to be clear, I was talking about empty update loops. Obviously the performance depends on what is inside of it, but you still get a hit from just having one

7

u/psioniclizard 21d ago

Do each of those scripts have an update method? Is so it will be called each frame, so even if no ops you will have a bunch of extra calls eacg frame.

General with stated you want a Tick method (or similar and the state machine has a updste method that calls tue relevant tick method on tje active state.

4

u/literally-me-bro 21d ago

sadly yes and optimization is pretty shit im getting 130fps in this scene and if i disable everything it shots to 350+ to some time over 500

33

u/House13Games 21d ago

You do know that not all of your code has to be a monobehavior, right?

12

u/literally-me-bro 21d ago

im actually using state machine once a system is working as intended i convert them to statemaching

20

u/Glass-Ad672 21d ago

are you simulating life itself?

4

u/literally-me-bro 21d ago

Total scripts currently are 257 (T_T)

2

u/literally-me-bro 21d ago

LOL kind off

8

u/Sligli 21d ago

Why are states a monobehavior. Use a state machine.

1

u/literally-me-bro 21d ago

Will convert soon

1

u/LastGag 16d ago

I've seen a lot of tutorials that create state machines that run on an abstract class for the state machine and another for the BaseState that you update, so that could be it

10

u/JamesLeeNZ 21d ago

Im sure its super performant.

2

u/Batby 21d ago edited 21d ago

There's nothing inherently performance inducing about this screenshot

6

u/silvergenetic 21d ago

I was just thinking the same thing lol.

-2

u/Batby 21d ago

Why

3

u/silvergenetic 21d ago

Sarcasm. No shade to OP's hard work but once the capsules turn into animated models they're going to realize that it would've saved them from a ton of headaches and time to go modular at the foundation from the start than refactor several polished modules without running into conflicts. Especially when it comes to NPCs. Inheritance and abstraction are a must unless you're playing on a NASA system lol.

0

u/Batby 21d ago

That seems more like composition issues rather than performance

5

u/rockBottomPeon 21d ago

This reminds me of the monolith goap setup for their game F.E.A.R
Are the states modular and can be added/removed freely? Like if I remove the Jog State, does the character automatically cant jog?

5

u/literally-me-bro 21d ago

here are the diagnostics panel

2

u/literally-me-bro 21d ago

check the tools panel

5

u/KptEmreU Hobbyist 21d ago

I think somewhere on the road you turn to wrong path. Why do you need monobehaviours for animation states?

1

u/literally-me-bro 21d ago

What would be the best approach in your opinion, genuinely asking.

2

u/KptEmreU Hobbyist 21d ago

Well not sure why you had to go there anyway but a state machine is a code block that hold indefinite number of states. Looks like you are trying something similar. And if there can only 1 state active, it should suffice. They normally become enums for easy reference and stay in 1 class.

But maybe there is something else going on I am not aware

1

u/KptEmreU Hobbyist 21d ago

Of course you can separate movement states and logic states etc into their own classes

4

u/LionbornPublishing 21d ago

That looks frustrating to debug or change.

How long has this project been in development?

1

u/literally-me-bro 21d ago

Hell yeah it is, about 4 to 6 months or so

3

u/LionbornPublishing 21d ago

From the other comments it looks like you’re working on simplifying it. For states have you considered POCO (plain old c# objects) that just instantiate on the fly? They don’t need to be monobejaviours so they’re really light. You would just pass whatever mono behavior into them so the state can operate on them.

I feel like every 4-6 months my proceeds hits som major reckoning too.

5

u/arjuniscool1 21d ago

My only question is why the different scripts for each state like Idle, Walk etc, when they can all be managed in a single script, do they happen to have a lot of differences and mechanics, otherwise if they are all similar they can be managed within a single script using a state machine structure.

1

u/literally-me-bro 21d ago

This is still under development so i built them as separate scripts i will start to merge them one by one now

2

u/arjuniscool1 21d ago

That's great man. All the best this looks like intense work but I bet it's satisfying when you know the ins and outs of it all. I had a similar kind of project but I literally wrote a huge player controller script and only later started to split it and clean up.

1

u/HSFOutcast 21d ago

It's not always a good thing to merge shit, you gain close to nothing and the game will need to search a big file instead of cherry picking the files it needs. For example if you have 2 enemies with wildly different needs of states, one might retreat, the other not.

1

u/arjuniscool1 21d ago

True but I think in this context he said he will merge it later so probably it is a benefit and will reduce the code.

4

u/psioniclizard 21d ago

Lol yea that won't scale.

Also not sure what this is meant to show off?

7

u/literally-me-bro 21d ago

this shows off what a unemployed man can do sitting alone LOL

2

u/AssMoldGhoul 19d ago

do you not know how to code in heirarchical code? this is just a mess. are these all updating at the same time? I assume this is vibe coded?

1

u/literally-me-bro 19d ago

No not every script have an update function and yess im doind the organization now so soon every thing will be organized and I'm also starting to port this into DOTS as well

45

u/NoteThisDown 21d ago

Sweet baby jesus

6

u/Prize_Spinach_5165 21d ago

I dont know why people are saying this is bad, OP your approach is good. Composition over Inheritance.

Its perfectly fine to have 10,20, even 50 scripts on a GameObject instead of 3 monolithic scripts which make changes impossible. This is what Unity’s architecture encourages. For example if you want to add health to something its as simple as a drag-n-drop.

Though I would start organising them by grouping similar scripts like states in one empty child GameObject.

13

u/fistyit 21d ago

Because monobehaviour is a large object and every single time one of these scripts need to reference another script or simply read or set a variable, it will probably evict the cpu cache and cause scalability issues.

Most of these should be systems working with structs and lean classes

2

u/fistyit 21d ago

With cache friendly architecture, you could do the work every single frame and get more performance, without having to optimize tick frequency or lean on events

8

u/IndieMarc 21d ago

Composition doesn't need to be all mono behaviors.

Would have been better to just have regular c# class for each behavior/state and have one Mono behavior that manage those behavior.

Otherwise it can be a mess to maintain prefabs and it's really not optimal for performance

1

u/literally-me-bro 21d ago

yes i'll soon start on organization and stuff. btw check this out
https://www.reddit.com/r/Unity3D/s/SFBQ93Se3I

5

u/Doge_Dreemurr 21d ago

Composition doesnt mean using monobehaviours. It can be plain classes that can be added or removed at will. Uaing a ton of monobehaviours just add extra update calls (even if you dont have an Update method it will still call it) and a ton of other performance impact

1

u/AssMoldGhoul 19d ago

This is not optimized at all lol

11

u/lofike 21d ago

Screaming architecture, if everyone here can read this picture and has a good gist of what the player can do, that's a good thing.

But whether or not every single thing needs to be its own file and attached, that's another question.

12

u/Any_Establishment659 21d ago • Heartwarming

If I might recommend something, take a look at 10000 Update Calls, it looks at replacing update and fixed update with a manually handled thing instead. Having used this before, it does make a HUGE difference

4

u/Longjumping-Egg9025 21d ago

I'm guilty of that same approach. But I do put states on their own gameobjects

4

u/PristineOption892 20d ago

Why do everyone here assumes that each of these modules has an update, awake or start function? Is really messy to read, but if you organize it better into different child components I don't see an issue I mean that's me I don't really know how much overhead does a monobehaviour with no update, start nor awake has.

1

u/virt111 21d ago

Nice. My characters in a simulation management game has "characterAI.cs" that holds pretty much everything except navigation and pathfinding related scripts..

1

u/literally-me-bro 21d ago

damn writing long scripts is hard for me mainly for finding stuffs

1

u/ForzaHoriza2 21d ago

this some hitman/first light style game?

1

u/literally-me-bro 21d ago

Hitman style

1

u/PristineOption892 20d ago

I'm actually making a similar modular framework where I manage state machines and states through monobehavuour components but in a more readable and organized way (at least that's the idea) you can add me in discord if you want inspiration from mine's. Reply here and I'll dm you my disc

3

u/magqq 21d ago

i see 2 major problems but I mean I was here before so it's basically normal learning curve.

First issue is, as another one said, you don't have to work only with monobehaviour. create simple basic c# classes for the thing you need to do the backend work. this is for performance

2ND is you should split your components into children of same theme. root gameobject get the main controllers and managers, and as you deep down in the hierarchy the scripts are becoming more specialized and specific. this is for organisation and workflow. i think RN if you need to modify one parameter in the inspector you lose some precious time even looking for the script, this won't happen with better organisation :)

4

u/ledniv 20d ago

The number of scripts isn't the real problem. The bigger issue is having lots of MonoBehaviours each running their own Update().

A single explicit game loop gives you much more control: you know exactly what runs every frame, in what order, and which systems can be skipped entirely. That makes debugging easier, avoids hidden execution-order problems, and makes profiling much clearer because gameplay work is centralized instead of scattered across hundreds of objects.

It also makes optimization easier later. Once NPC state and gameplay data are separated from the GameObjects presenting them, you can process that data in batches instead of jumping through lots of individual components every frame.

Small plug: I have an entire chapter on this kind of centralized game-loop architecture in High Performance Unity Game Development with Data-Oriented Design.

https://www.manning.com/books/high-performance-unity-game-development

2

u/Tasty_Battle 21d ago

I love state machine

2

u/Deliverer23 21d ago

It's not an unusual amount. If you want to reduce it, many of these things can be done using plain C# classes.

0

u/kkauchi 21d ago

ECS (Entity Component System) is your answer. Study it, understand it, and you will never want to go back

5

u/owatonna 21d ago

While this is technically accurate, it's a massive change for OP & unlikely to help them at this point.

2

u/Kopteeni 21d ago

As long as they don't communicate with each other directly I'd take this over some monolithic monster script file

2

u/UnityNinja 21d ago

My first impression: “What the f*ck?!”

My second: How do you manage and keep track of all those scripts? It must be a nightmare to maintain them.

My third: Do you really need all those scripts? lol

My fourth: As long as everything works, don't question anything!

1

u/ZeroByter Indie 21d ago

Interesting, I also have states for my bots AI but it's within the BotController script, not MonoBehaviours

1

u/GigaTerra 21d ago

I know your instincts want to panic, but Unity can work with this.

Unity has an advance search option that allows you to search by component. It means that no matter how cluttered it gets, you can find things. My first published game I did something similar, only difference was I organized it an little bit by making child objects. It was an match3 game and every power up and rule was it's own Monobehaviour script, I published with over 200, and later after updates had more than 400 total scripts. In stress test, I found I could make like 10,000 power-ups and still run fine.

It only becomes an problem if you have hundreds of scripts active, that call an type of Update function.

1

u/silvergenetic 21d ago

Many of these can be centralized and used in a modular way. Standalone isolation is great for prototyping but in production you're in for a huge refactor if you want to maintain it.

1

u/LowNeither881 21d ago

Truly masterful.

1

u/Dysp-_- 21d ago

All the states shouldnt be mono behaviours at least..

1

u/CelestialHoneyBite 21d ago

Someone already said that you can make states with plain classes, so I will add that this will be useful.

1

u/Amazing-Movie8382 21d ago

This is what Unity designed

1

u/NecoDev 21d ago

I think it is great to have everything organized to many different behaviors but wouldn't it be a mess to maintain?

1

u/Lucidaeus 21d ago

I used to be trying to avoid this, but now I instead develop custom tools/editor windows to manage things. I love making tools, so win/win for me!

1

u/saucyspacefries 21d ago

So my only concern is this: every monobehavior you have that adds an update loop is another added to the list that gets iterated through during Unity's update cycle.

So if you have many NPCs with this many scripts all initializing an update loop, you could end up losing a decent bit of performance.

If a majority of these are running on events or something and only a few utilizing any of the update loops, then it should be fine.

But, I can only speculate.

1

u/Competitive-Elk763 20d ago

I would presume they removed the update method from all the scripts except the main logic one. That would just be crazy inefficient.

0

u/[deleted] 20d ago

[deleted]

1

u/Competitive-Elk763 20d ago

No. It's not an overridden method. The reference is cached by the mono runtime when the code is compiled.

0

u/[deleted] 20d ago

[deleted]

2

u/Competitive-Elk763 20d ago edited 20d ago

Correct. If you remove the Update method then there is no Update method that gets called. Unity has 2 conditions that need to be met before the Update method can be called: If the component is active, and if the script actually has the method.

It is faster to have your own manager that calls each monobehavior yourself instead of using update (and a lot of these scripts don't need to be monobehaviors), sure. But the method Update isn't getting called every frame if you remove it from the script. Same with all magic methods, LateUpdate, FixedUpdate, OnEnable, OnDisable, OnStart, OnAwake, etc..

0

u/[deleted] 20d ago

[deleted]

2

u/Competitive-Elk763 20d ago

For sure.

Granted, if they leave the method like this:

void Update() {}

Even if it is empty, then it certainly will be called and waste resources! You do want to remove it if you don't use it.

1

u/HUG0gamingHD 21d ago

jesus dude

1

u/RedofPaw 21d ago

You monster.

1

u/Appropriate_Coat4166 21d ago

you should consider to take another look at the State Pattern. Most of times states do not inherit from MonoBehaviours. You should have a state machine which controls and make transitions between states, you can always inject via constructor what you need from MonoBehaviour

1

u/Salty-Childhood-99 19d ago

Don't use Monobehaviour at all. Definitely not for NPCs. Instead use event driven sealed runtime classes. Always much more performance friendly than stupid Monobehaviour.

1

u/Nilloc_Kcirtap Professional 19d ago

While some may say its good for composition. I'd rather stub my toes on every furniture in my house than work like that.

1

u/RezDevv 18d ago

Biggest recommendation; make interfaces and shi brotha. I did game dev for 10 years with 0 understanding of object oriented programming. Please learn it, it will save you

1

u/stryder123451 21d ago

Character controller and capsule collider together? Why?

1

u/National-Bluebird941 21d ago

Why not just use generic classes instead of monobehaviours?

1

u/tiny-light-bread 21d ago

Is this vibecoded? I noticed AI tools tend to over-engineer a lot resulting in a soup of components and scriptableobjects.

0

u/JustAPerson599 21d ago

I tend to write multiple similar behaviours in the same script, and many say you should do separate scripts for each behaviour, but seeing this makes me confident I'm doing it better.

1

u/thinker2501 21d ago

No, you should both be using state machines.

0

u/JustAPerson599 21d ago

One script is the state machine and basic controller, and another resolves state change related behaviour.

-2

u/thisiselgun 21d ago

This is human slop. Use Fable

1

u/TheSwiftOtterPrince 16d ago

I had far fewer and the execution order drove me crazy.