#archived-code-advanced
1 messages · Page 192 of 1
ui observes game state via events
Currently I'm pushing Command objects to a list, and whenever we have even one command in our "queue", I just "dequeue" the first one, call its Execute Task and so on and so on
And the UI's placeholder work is:
Push command to our loop, (hide screen and other fillers), wait until it emits an ActionFinished event, then show X ui screen based on Y condition, but I'm not sure if that would be great/"clean" long-term
you'll probably need something more complex than that, with plenty of edge cases, but at the core, thats basically how it always works, so long as you keep gameplay ignorant of ui, you're pretty safe
Would the currently described implementation work in your opinion or should I do something else? Maybe an extra "wait until THAT specific event finishes" or something else?
that is impossible to say
ui is always messy, overly complicated and takes way too much time, no matter how hard you try, you are going to rewrite lots of it as you learn more about what your game needs
i'd say: avoid overengineering it, make code easy to replace, delete, rewrite
Yeah that's what I found out from previous iterations lmao, the first attempt was a huge mess of messaging and event subscriptions with no way to trace "what connects to what"
ui code is often way less generic that your other code
The ONLY reason I am stumped is because there are cases when I can, for example attack multiple times in the same round, so I can't just do an "if it's our player's turn show regular ui" and done
Handling that is the funny part
you might benefit from inverting your way of thinking about ui
Everything else is cool tho
you do not show ui, you have your ui decide to appear
Which is basically/in codemonkey language: let the ui check/listen/whatev to conditions when it should show itself INSTEAD OF creating custom actions that should "show" our ui? Or did I go in a completely different direction?
yes
geez
if that matters in any way I'm very much against that
Okay that one's a genius idea, I was completely lost in the "oooh commands and stuff are shiny" overengineer mess
And since the background's already there for both attempts, it would be an easy switch too
public NPC : Interactable {
public DialogueData dialogue;
void OnInteract() => DialogueManager.Open(dialogue);
}
public class TurnController : MonoBehaviour {
public void StartGame() => StartCoroutine(GameLoop());
IEnumerator GameLoop() {
while (true) {
PlayerUI.Hide();
while (enemyTurn) { yield return null; }
PlayerUI.Show();
while (playerTurn) { yield return null; }
if (activeEnemies.Count == 0) { break; }
}
VictoryPanel.Show(...); //with some parameter that feeds it what to display
}
}
ofc you can't be asked to reference them all from TurnController
you'd either need a higher-level module to control your UIs, or, if your project is 100% well structured, only access that way the ones that are singletons
The loop code's kind of similar here, plus I panic-added an observable/message publisher/depending on the lib which just emits the action objects back when they've finished, looks like I've been on a "right but somewhat still wrong way" with this one
Thank you for the help guys :)
Or "wrong but a bit right", will check out in the morning
the best you can do is to just build it, keep what works, rewrite what doesn't, do it better next time
eventually you'll have a personal style of doing it that works for you and your kind of game
it also massively depends on the scope of your project
Yeah that's what I'll do, deadlines close and the mp parts of a firebase-only game are already a PITA to worry too much about these parts
But god damn, "proper" game logic/ui separation is a lot more difficult than I originally expected
if you keep UI (i.e. views, not the dialog prompts required to progress gameplay) separate from your gameplay code, you can do a quick & dirty ui now and a clean one later
and keep non-interactive ui 100% separate from gameplay
The views are thankfully already done, those were relatively not-so-difficult to implement compared to this part :D
you mean the designs or the actual controller/presenter code for the views?
But I wanted to connect my score counter to an input/gamestate manager :c jk
The actual controller, so things like main menu/view switching was kind of nice
if you adopt a message bus architecture (which you are already halfway doing) you can put ui into the same message chain as your gameplay actions without coupling them
But this "show this view/dialog/whatev if player can do this, that if player can't, but don't show if x, how to send y data to it without boiling spaghetti" piece is where I've fallen into the pit of overengineering
i bet, there are few people around who have built some impressive solutions to that problem, they might reply if you maybe ask again later
Already using MessagePipe for that, been using Zenject's Signals before but that had some weird issues (can't NOT use it Zenject in current project) with messages declared in subcontainers and stuff
zenject is evil 😄
Plus UniRx only for those blessed "filters" on things like these messagebus "streams" (which was great for things like popups, caller object has a subscriber for popupClosed messages, popup sends one on close, and we can await the first message and so-on and so-forth)
Yeah, idk why someone would voluntarily use it even in smaller projects 
its just way too much code that does nothing
rx is great in theory and powerful but can lead to some pretty nasty messes
Oh yeah I've tried to do most of the combat ui when it was in the only-message-listeners-italianrestaurant phase, it was a nightmare
But for smaller timers and "wait for next emit" things it's good
i can't really speak to it, never used it as an architecture in any project. i'm just too happy with plain async/await
Same with unitask, had to use WaitUntil lines in soooo many places at first because Bar depended on Foo's xyData object, which was taken from a database and stuff like that
yeah,that might not be the best architecture if you need lots of those
way too easy to deadlock your logic
But their asyncenumerable things are great imo
Yeah, still trying to work out "where to use what lib to what extent" without making a huge mess
And then we have
drum roll
Addressables in contexts that should go with a sync-only workflow 
Aka binding some objects in zenject BUT they have to be addressables bc of size limitations (and the async part of that lib calls bind method, twice, on supposed-to-be-singletons)
Can't wait to finish this one
the safest thing you can do is have just a handful of tightly coupled 'threads' that manage the core game loop/modes and make everything else branch off of those main procedures in a fire-and-forget style
That's what I currently do haha, but only with one extra thread, maybe more would really be merrier
have stuff write to a shared state, but rarely depend on certain conditions, just offer choices for the conditions that exist, and curate the "critical path" that has actual dependencies very carefully
by "threads" i just mean semi-overlapping systems that interact, not neccessairly actual threads
you could say, "keep overlap to a minimum", distribute stuff in time and space to become discrete (as a strategy for avoiding complexity)
Yea, I understood that one dw :D It's just that the current systems send everything "visible" as a command to our gameLoop
So things ranging from adding actors, to attacking things, even the "gamefinish" part is an action atm, as an attempt for our game to not do two things at the same time if the connection decides to do weird things
its a good starting point in my opinion
So like
Firestore listeners? Pushing to our main loop if its data looks like an action
And some actions also push actions to our loop if they have a one-way connection
Aka "B always happens after A but we can occasionally get into a situation where we only need B to happen"
i've once build a turn-based game that was essentially one huge coroutine and a modal dialog that i would push a prompt and decision options to... and it would always be this swap-chain of modal dialog, execute command, modal dialog, execute command... built an entire menu structure and 2D grid combat into that modal dialog
And since it's just a while+await action/await WaitUntil(hasAction), it doesn't really have a chance to crap out unless we literally forget to write the code responsible for pushing events
Ooof, yea I'm trying to avoid the "whole menu in one dialog" thing :D but that sounds like a great but painful solution
it was a text based game, so that seemed like a natural fit
wasn't actually too painful, except for the limitations of coroutines
Ah, yeah in that case it makes sense to put everything into that dialog and just switch out the currently visible one
Mostly the "no return values" limit I assume?
And handling cancellation of those nested coroutines sounds
Fun
That one has some smaller quirks too
E.g. Don't pass the same cancellationToken to a WaitUntil and any other task that you'd use afterwards
thats just how tokens work
Was too lazy to check the implementation at ~2am but I guess it just cancels the task instead of finishing it
Oh damn I really have to do my homework on tasks then
a token is a disposable that can be canceled only once
That was a part that I kinda "rushed" into
Yes, but I tHoUgHt that the cancellationToken wouldn't be used/consumed on a task like that
ic
Like
The task would just "finish" and not "cancel"
ic.
But that's just a personal issue with not enough knowledge about the topic
cancellation tokens aren't the end all for task lifecycle management, so yeah, quirks
still better than nothing
Yeah, it also saved my bum a lot of times
and you are free to use all regular sync primitves
I'll look up on some of those, I'm sure that there are still a few "no-brainers" I haven't used yet
Thank you for your help btw :) gtg now, have a nice day
cya
i've been using unitask for years, in almost a dozen production unity games and experiences, and have never used a WaitUntil
i think what you've been missing is TaskCompletionSource
which is, in other words, a future
your ui should be reactive to game state. you can do it with unirx. otherwise, you can await TaskCompletionSources that represent events in the game
uh oh, i've got a bunch of those 😮
WaitUntil is pretty useful fwiw, it's not worth using TaskCompletionSource for everything
Oh yea for sure, i'm not really that worried about it
How do I load a scene, run all awakes, but not run any starts
Then run my function, and only then run the starts
Make all start ienumerator, yield until you run the function
Yeah sorry not the starts
The first updates
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(sceneName);
while (!asyncLoad.isDone)
{
loadingSlider.fillAmount = asyncLoad.progress;
slider.value = asyncLoad.progress;
await Task.Yield();
}
var scene = SceneManager.GetSceneByName(sceneName);
await sceneInitializationProcedure?.Invoke(scene);
This thing runs my sceneInitializationProcedure after the first round of updates
(Scene scene) =>
{
// Pass down the garage context.
var rootObjects = scene.GetRootGameObjects();
foreach (var rootObject in rootObjects)
{
if (rootObject.name == "Initialization")
{
var garageInitialization = rootObject.GetComponentInChildren<GarageInitialization>();
Assert.IsNotNull(garageInitialization, "The initialization object did not have the initialization component.");
return garageInitialization.Initialize(_garageSharedInitializationContext);
}
}
AssertHelper.Fail("Not found a root Initialization object in Garage.");
return Task.CompletedTask;
});
Maybe make a static boolean somewhere and in every update you do:
if (MyStaticClass.LoadNotDone)
return;
This is accepting defeat
Moreover, it's just stupid
not stupid if it (might be) work 😉
but not effective either
It is stupid tho, it doesn't solve the actual problem, it introduces noise, it makes you place boilerplate in every update, it's fragile
the other way is disabling all scripts
iirc there is not a "good" way to stop Update from running
There's got to be a way
Disabling all scripts is too much complexity and noise, it's a terrible solution
Well, if you don't want the boilerplate of if in every update, or disable all scripts and re enable them when done... You can write your own custom Update function, subscribe that to a single script, and either use if or disable that single script until done
Another way I could think of is passing the context via some object in the hierarchy, then making the initilaization script take the context from that object... but that's so much complexity where you could just pass it down the function
Yeah, or that
Make all start ienumerator, yield until you run the function, start coroutine 'customupdate'
I'm initializing the scripts manually from the outside, not with starts
That's the thing
That's why Update happens before they are initilaized in the first place
After a bit of reading: Note that for objects added to the scene, the Awake and OnEnable functions for all scripts will be called before Start, Update, etc are called for any of them. Naturally, this cannot be enforced when you instantiate an object during gameplay. (src: https://docs.unity3d.com/Manual/ExecutionOrder.html)
There might be a way with combining execution order and awake calls. Have your final load function be called in awake in the last script in the execution order 🤔
also:
For objects that are part of a scene asset, the Start function is called on all scripts before Update, etc is called for any of them. Naturally, this cannot be enforced when you instantiate an object during gameplay.
Awakes are called in a random order
with using execution order? https://docs.unity3d.com/Manual/class-MonoManager.html
I don't know, I haven't used that, but that looks super terrible imo. I'd much rather do everything manually in a script
I imagine it would be a nightmare to manage in which order they executed with that thing
Like it's assigning some priority numbers rather than just calling them in order with code
My thought was just have that single function you need before Update() call all your initialization code set in a script set as last in the execution order list
It's ok to call that in Start, that works too, it's just that I need to pass a parameter to it, which contains context from the previous scene
Which I cannot do if Unity calls it rather than me
Unless I pass it via statics or as an object in the scene
Which is way more noise than just passing it in as a parameter
It's always like that in Unity: the simplest and most logical thing is discouraged because of some weird quirk
Also, scenes are kind of useless
I was previouly able to not run any updates by instantiating a prefab containing the stuff of the scene, rather than a scene
At this point it feels more like fighting the engine rather than working with it 😅
It lacks too much stuff, I always end up reimplementing almost everything myself
If you need more callbacks than the ones provided, then make your own. Generally it smells like bad architecture or useless arbitrary constraints you impose on yourself if you disregarded all the options offered to you. https://docs.unity3d.com/ScriptReference/LowLevel.PlayerLoop.html
mybe rethink if the solution fits the problem you want to solve
Guys, I just want it not to run any Updates until I initialize it manually
Literally by calling a function before the first frame happens
How is it not the simplest thing?
I disabled the scripts that use updates in a start of that initialization object, then I enable them back at the end of the intialization procedure
That seems like the simplest and the most sane solution without too much extra complexity
if (!_isInit) return;
you are gonna make they check in one way or other. Explicitly, implicitly, doesn’t matter. It will be somewhere. Just derive all your mono behavior scripts from an abstract base class that does this check in its update and calls an abstract OnUpdateAfterInit()
Gotta be careful about that return if inheriting though. It won't cause a derived method to return
The order is not directly random. It is said that the order is arbitrary,
though from my observations it is by order of instantiation.
However, it is not recommended to be relied upon during system design.
Might become unpredictable at some point, since it is not sorting them in any other way.
The pattern is to make update private and call into a protected abstract second onUpdate method that you override
Hello. Im trying to fire a event with a callback when collecting items. onInventoryStackAdded. But it doesent seem to run. Im not sure if I'm even on the correct path here:)
You need to invoke the event when an item was added to/removed from the inventory
Like this ? if (onInventoryStackAdded != null) onInventoryStackAdded.Invoke(this, new InventoryEventArg(newItem));
No
You can just use onInventoryStackAdded?.Invoke(this, new InventoryEventArg(newItem)); btw, it's shorthand for that nullcheck
Your inventory class needs to implement add/remove methods that add/remove to the dictionary and invoke the corresponding events
#854851968446365696 on how to post code
My inventory class already have that. But then I want to notify a "displayer" that a specific item was added.
That should be handled in a callback
Btw have you heard of ObservableCollection? https://docs.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.observablecollection-1?view=net-6.0
I have not. This looks intriguing!
Seems like it could be helpful, seems to cover what you're wanting to do
before you get into observables, make sure you 100% understand how to implement the pattern yourself. Else stuff will get painful
and don’t even try RX without understanding it 110% plus everything about IEnumerable
Nope, I'm doing an assert(_isInit) sort of thing instead
If it's not been inited, it should've been disabled, is my logic
You can do both. It’s a choice.
Is it possible to use LINQ in 2d arrays? The autocomplete is not giving me the Where
This looks relevant https://stackoverflow.com/questions/3150678/using-linq-with-2d-array-select-not-found
tldr: No but there's a workaround
hello guys i made a working inventory system , but just wondering if it's a bad idea to pick up item based on sprite image name, so i have a code so when the player and the item collides, if the sprite image name equals to one of the enum element , then it will add the item to the inventory, but this method has to change the sprite name, which is kinda terrible, just wanna know if there are other methods to identify items and add them to inventory
yes it's a bad idea 😛
public class ItemData : ScriptableObject { ... } // Your item's data
public class ItemPickup : MonoBehaviour { // Your item's representation in your scene
public ItemData itemData;
void OnTriggerEnter2D(..) => PlayerInventory.instance.Add(itemData);
}
alright thanks
scriptableobject does work with lists right?
It works with lists
why can't i find the option to create a new scriptable object asset tho, so im following a youtube turtorial of how scriptable object works and he got the choice to create a new asset of scriptable object called cards but i can't, it doesn't show up for me
There's code required in the scriptable object class definition to make it show up in the menu
You may have missed or not got to that part yet
[CreateAssetMenu] iirc
yea i have this code
Make sure you saved and have no errors in console
If you have errors, unity can't get around to checking for that code
Also #💻┃code-beginner next time, this is not advanced
Yeah that might've been it, I just blindly used the same "getCancellationTokenOnDestroy" in every waituntil, then even the first one threw a cancellation exception on "completion", and so did every other unitask that followed it, it was an extra-rookie mistake though
This looks sketchy af
If you're asking for someone to open your project and convert it, lol no
Look up some tutorials on the new input system and do it yourself, or ask a specific question
I'm not even clicking that. Nobody wants to download a random file
<@&502884371011731486> please deal with this either sketchy or legit file
i can just send the files, you're completely right
i mean, the code in a text file even
#854851968446365696 for posting guidelines. And make sure you have a question. Nobody's gonna just convert it for you
@deep coyote there's more to switching input systems than just code. Just check out some tutorials, there are plenty online
Yep, just saying the kind of help we offer is answering specific questions
okay I'll go back to it and make a list
For some extra context, there's been scams that are "Here I made this game, please give your feedback" with a virus in the download
The new input system requires very different choices architecturally, it's not just a syntax change
Hence why we're being so careful
yeh the thing is, i never used the new input system so i have no idea where to even start
Yep, you're gonna need a tutorial. Also, #💻┃code-beginner next time
Then find a tutorial and follow it
Was a unitypackage, but yes can sneak in malicious code as well
thanks for clarifying!
Thanks for checking
That's for sacrificing your pc nvm
xD too far
I also posted here, cuz the code is definitely not beginner friendly in these files
only looked at file type :)
Alright thank you guys for the warning, my bad in the first place for posting a link yeh. I'll try to spend some time looking into this, although I tried yesterday and failed
Hi guys, I have a problem to connect to my ipad to debug my application. I didn't find it on my debugger ( visual studio , vs code or rider ) . Where do i should ask for help on this discord for this purpose ?
Technical problems are usually covered in forum posts and Unity Answers site, etc. waiting to be found, if you have a unique issue would also be better served making a long term post where you can get an official support.
Unity also has a device emulator that can be used to test on variety devices.
Device Emulator is great. Easy to use and I had no issues. Can recommend
@frozen imp @unkempt nova i can't use emulator because it's a AR app. But thanks for your help.
Ah
I posted my question on the Unity Forum but i thinks a debugging channel should be great on this forum. I saw a lot a people who struggling on debugging
Yeah, this is for code though. That's more of an issue with the connection between the debugger and your ipad. Nobody's really equipped to help with that around here
You use XCode to get the console output from an iOS device
yeah i know i can get the output console but i want to use breakpoint to be honest^^
breakpoints won't work on device ..?
my player don't show up on any IDE i use ( VS code, Visual studio , JetBrains rider )
Think he's talking about remote debugging
breakpoints will work on device, I use rider and can debug il2cpp on ios. Make sure you have script debugging enabled when you build, look in xcode for the ip/port to connect to if device doesn't appear on the debuggable process list in rider and connect manually if you have to
I'm doing random room generation and I need some way to find the largest room I can fit in the space available. I'm going from the blue door and I need to find the biggest room (green) I can fit amongst the other rooms (the red ones). For now we can assume that blue door is at origin and everything is axis-aligned. I have list of the red rooms including their positions and x and y sizes. Maybe the solution is very easy but I'm not able to figure it out (I'm not looking for ready code, any rough idea of the algorithm would be appreciated)
maybe just do raycasts up left and right fromt he blue door
the points you hit will give you the boundaries
or rather - a raycast up, then two boxcasts left and right? 🤔
I don't want to use raycasting or anything like that (so only math). something similiar could be done mathematically tho
raycasts are just math
yeah
Another I approach I think would perhaps be to use an interval tree (or two interval trees, one for x and one for y)
that will let you find the nearest occupied intervals in the space (left and right red squares) and fill that out
and same for the vertical interval
thanks. I'll take a look at those two methods 👍 I may not need to most optimal solution (so it doesn't always need to give the largest area for example) but I need to make sure I never spawn two rooms overlapping each other
Arent you looking for some line intersections? E.g. where does the line from 1..2 intersect with an imaginary line from the door to the left.
Get the closest intersection, with all other shapes
Which, imo, sounds a lot like raycast 🙂
sure that's what I mentioned above. But imagine if there's an object between your arrow and the 2 and to the right a bit
a raycast won't see that
actually I guess that's fine
you'll just have a short box
Hello, how i can get references from gameobject? I'm trying to make a large scene split to segments based on renderers and after splitting it moves object to another segment but it's references is staying on other segment
people represent their regions as discrete grids
to make this simpler
it is also better gameplay
it also frees you from having to know the most efficient way to do things, because exhaustively querying every node of a small grid is fast
does that help?
building these things in the real space (i.e. floats) is way harder, and the impact on gameplay is small or possibly negative
so it's very low ROI
make a grid. then, if you want to see the largest rectangle you can put in the grid, you can usually ad-hoc make a "algorithm" that, while it requires visiting every node, will be correct
for example, to find the largest contiguous rectangular area in a rectangular grid at a certain point, create four corner points at the start point and move each one tile at a time, checking if the move would cause there to be a filled grid point in between the corners.
is that optimal? nah
but i could spend like 30s thinking about it and get something that works because it's grids
heyo 👋 im trying to fit a plane to a collection of points (4 points) and was trying to use this as a guide https://www.geometrictools.com/Documentation/LeastSquaresFitting.pdf
I was following section 3.2.1 but am a bit confused on the pseudo code as I am fairly new to linear algebra
i am trying to get the "best" plane to fit my procedural characters legs to adjust body position acordingly
the pseudo code gives a forumla which gives height based on x,y, does anyone know how I could adapt this ?
find the normals of all planes defined by a combination of 3 points, average those normals, the result will be the normal of your closest fit plane. you can square the normals to emphasise outliers (true vs. geometric mean), i'd suspect least squares is too computationally expensive.
bless you, ive been staring at this damn shit all day, i really should have tried harder in school
Is one able to use a .NET 6 class library in Unity? Isn't really using any .NET 6 specific features other than file-scoped namespaces.
I asked this in #💻┃code-beginner but maybe this is a better channel as more will be familiar with the ecosystem.
you need to use libraries that are compatible with framework 4.8 or standard 2.1 depending on your scripting backend (unity 2021)
not currently
Well it's my own library.
and please only use .net standard 2.1 compatible libraries going forward
well, just target it to .net standard 2.1
yes, libraries are still best off targeting 2.0 or 2.1
well, .net standard 2.1 doesn't feature MethodImplOptions.AggressiveOptimization?
then don't use it
well then comment out that attribute
either, don't use your library, or use .netstandard 2.1 compatible layer. or wait another 2 years for .net 6 support
The attribute is there for a reason lol. It isn't just there to be there.
this^^ @weary stag
.net standard 2.1 - why are we still in past? can we move on to .net 6, .net 7 is legit on the horizon.
we are. but it will still take about 2 years. we've been working on getting there for the last 3 years
who is we?
1 - unity's community
2 - unity's devs
i for one have done zero work to make unity ready for .net 6
well, some people have
are Unity's vector structs at least SIMD accelerated?
no
wow
there was no such thing in .net at that time
yes^^ if you use burst
There legit is.
NOW there is
What's burst?
you may want to read this: https://blog.unity.com/technology/unity-and-net-whats-next
compiles your code into highly optimized native machine code
thats what all compilers do
burst just knows a bit more about unity than "regular" compilers
nope. untrue
no. it's aot
aot?
roslyn only compiles to IL
ahead of time
Unity has bitops, just they do it their weird way in the burst compiler
and idk if this uses intrinsic or not
if it doesn't, it'll slow my program down by like 40x
burst tries it's best to use the most performant things.
if you want to absolutely make sure to use intrinsics, use Burst.Intrinsics.[...] and write them out youself
well ye but what bout the Mathematics namespace?
just add the package and look at the source
why are you at the same time writing super low level code and asking such trivial questions?
I'm not asking trivial questions. Reason for writing low-level code is because I'm developing a chess engine. Wanted to make a GUI for it with Unity but it seems that's impossible.
def not impossible
Impossible with the current state of Unity. It's in the trashcan literally in terms of the .NET ecosystem. I would have to port a decent chunk of my code to likely not as performance capable .NET Standard 2.1 code.
just keep your low level code in a native DLL written in C for max performance and all the intrinsics you could ever want to use
Well it isn't in C to begin with.
It's in C#.
and it's quite performance capable.
c++ please, ok
you could just run it in a separate process
yeah im aware but that feels so shit
that's pretty much making a UCI compatible GUI.
and then I would have to make it UCI compatible on engine side too
you could also compile it with NativeAOT to dll and add it to unity
oh?
probably
links please ❤️
google it
guess what that means
yeah NativeAOT is only really available for .net 7 iirc. but just upgrade. that's no issue
— idk about whatever performance regression comes along with .NET 7 yet. It's still in preview.
isnt that a feature of upcomming unity version to load the dll files easier ?
? that's completely unrelated
no
yeah it is. in what way is 'loading external dlls easier' related to 'my code is written in c#, not c' ?
is it normal the allocation of a renderTexture is taking moree than 150MB of RAM ?
no
that may or may not get to 150mb, but make sure you are releasing the non-used ones on the next frame
There's GetTemporary to help you with releasing etc
GetTemporary?
im getiting the texture by setting it as a target on a secondary camera
maybe thats a bad practice?
and after that i render()
No not really. But determine if you need a single texture that you re-use, or get a new temporary copy that you release.
temporary, thanks thousands, ill check the link
How do you know they are 150mb? With the memory profiler?
yes
the texture itself... should not bemore than 4MB
I didnt undderstand why that inccreasement
with a 4k texture, 4 mb is kinda unrealistic
but then i've read about the renderview memory allocations
4k ?
why you assume is 4k?
But do you see one single RT of 150mb, or do you see a lot of them adding up to 150mb? E.g. are you leaking textures
this
Its a sinngle one
RenderTextureSat
That is quite chunky
but it isnt 128 too much ?
well i will try what you suggested
i'm not quite sure on that with a depth of 24, but it does sound somewhat extreme
okay ill play too with the depth
the high resolution has a purpose
we have a city builder game
and when you move up
you want to see the whole city right?
but rendering all the 3d objects
would notbe possible (mobile)
so what we do is to take a render of a satellite camera we have
and show it as a texture in a plane
kinda google maps
the result is pretty good
but.....you still have to render the objects?
Whats on the texture?
a picture of all the map with the buildings
how do you show a texture with all the objects if you don't render the objects in the first place???
i have a disabled camera called SatCam
oh of course, i enable it for 1 frame
then i render()
and create the texture
then i enable* another camera that moves around the plane where i've set that texture
so i have 3 cams, just 1 enabled at the time
What is thw render texture format we can do some math to figure out if the size is realistic
to be honest, im very inexperienced o this field and im simply creating like
renderTexture=new RenderTexture(resWidth, resHeight, 24);
then
i assign to the targeet of a camera that has;:
i dont understand a single thing of those settings to be honest, except the size
this is the camera that creates the snapshot:
as you see i've set the renderTexture as targetTexture, saw it like that in a tutorial
wait so you created a RT in the project and then you new it in code or ?
So, the 128MB of that texture is exactly 4096*4096 * 8 bytes/pixel
With that R8G8B8A8 format + depth buffer, that does sound about right
do you even need a depth on that texture? (i'm no expert either, but i don't think you need depth)
I see, so the problem is the quality
okay
any other settinngs you think are unnecessary ?
like the R8G8xxx format
maybe, but i have no idea there either. anything else is pretty irrelevant. although, you may want to change to point filter
I saw it like that in a tutorial to be honest i dont know how to do better
okay ill try
thanks a lot everyone for your suggestions 🙏
Hello! Any idea what this error might mean? It's coming from my update manager class. I register all the classes with update methods on it and it runs all the updates. On enable and disable tyhe classes are registered and unresgistered on the manager
i'm getting this after an unregister I think
you cannot modify a collection inside foreach
try adding System.Linq then add .ToList() after defining updatable
that solved, huge thanks
btw is it possible to change unity's scale units to fit my cell size
basically i'm doing a fake 3d grid with cells and i wanted each cell to measure exactly 1 unit
Hai guys, i have the problem with the unity script, when i drag the script into the character i make, my unity crash, i search the solution in youtube and google and i cant find it, the crash is like this : https://youtu.be/1fq1K88nqQw , you guys know how to fix this problem?, thank you
Yeah I found this weird bug and I have no idea why this crashes the editor please help
use unity's units (1)?
What do you mean with Unity scale units?
well transform.position allows for whole numbers
I dont understand what you are saying, rotations and scale are also whole numbers
so what's the problem
lol. you're not the person who asked
XD
ahaha the problem is that each of my gameobjects don't measure that
i didn't want to have to scale down every gameobject
scale them up
yeah xD
well they have to be the same size eventually....
they are the same size it's just not one unit
if it was possible it would be easier to access each cell position
just scale them down then
well yeah, it's pretty much the same though
if we modify a material like this:
meshRenderer.material.SetTexture("_MainTex",texture2D);````
are we creating a clone of the material which needs to be destroyed afterwards?
or by destroying texture2D we are releasing the memory that material is using?
Yes you are doing that simply by accessing Renderer.material
what's the good practice inn this case then? destroy thematerial afterwards?
because i guess i cannot set the texture without accessing one or another way the material
Yes read the note here : https://docs.unity3d.com/ScriptReference/Renderer-material.html
thanks a lot
yeah that's what i've read but i was wondering if that was the normal todo or there was any other way to modify the material that didnt need this
but its ok
If you use sharedMaterial you don't need it but it will affect the shared material
Anyone else having issues with the latest mono versoin making VSCode not able to load omnisharp?
stack overflow has this 10 hour old comment
so... seems like a thing
idk if it's relevant but i was able to get things working with an early mono version, a restart, and some vs settings tweaks
@drifting galleon
Why did you @ Mindslayer...?
@drifting galleon You mentioned yesterday about NativeAOT - I've switched to .NET 7 and want to know how to go about compiling it to native code?
Could you take a fast look to my script for rendering on a material what the satCamera renders?
Im having memory leaks
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
are you disposing any disposable objects?
goes to 1.6GB once i enter this satview, stays there, but when i leave i destroy the textures and the materials being used but they are still allocated
usually memory leaks happen when you don't dispose stuff correctly.
well I think so
i destroy the textures in use... the material i set the texture too.....
whatelse could i be missing?
SetTexture should edit the material as far as i know no?
do a memory analysis of the project.
using dotMemory or something.
it will show what's being allocated.
dotMemory?
You can use other memory debuggers but I prefer this.
JetBrains ❤️
Anyone aware of how to use the .NET 7 NativeAOT compiler?
I can't really find any docs about using it to compile libraries.
I was wondering, what's my best option for writing float values to an array that all gpu threads can both read and write?
Is this something I should initialize in C# and send to the GPU, since I need the array to be a user-chosen length between 8 and 255?
I'm wondering if this is a computebuffer job
Your only option is ComputeBuffer/GraphicsBuffer
Any ideas on the best way to have permanent blood spatter? (3D) So the most obvious way is decals but over time that would become horribly inefficient, then there’s texture painting, but doesn’t that mean I need a unique texture for every single object?
Are there other ways?
You could use vertex painting (texture painting) along with triplaner mapping the blood texture, and add some noise to the edges. It wouldn't look quite as nice as decals. But I can't really think of any other way to do it.
Maybe you could do a intersection shader along with GPU instancing. But that will result is stretched textures, and I don't know how performant that would be compared to a decal, or how resource intensive interaction shaders are.
Particles might be an option too
It really depends on the look of the game, how much blood, camera angle, etc.
Well I'm thinking of essentially a 2D platformer but in 3D
So the camera is at your side still and you run right/left etc
But if you hit an object, blood is sprayed on the objects around you, the back wall, floor, pipes etc
Oh well you can use decals then. Just store their position and when they go off screen you deactivate them and reuse them.
how permanent is permanent?
well I've never used them before so this might be very simple but can you still reuse them even if they're wrapped around an object? Like if blood hits a pipe it should probably wrap around etc
All they do is project an image on to geometry.
They are not tied to any object
think of a hard fast paced platformer
so if you keep dying it'll keep spraying blood
I could just make it so that if there's x amount of decals in one specific area, they start despawning the old ones
but it would be nice to have it so, if you've died at the beginning of the level a bunch, you still see it no matter how many times you die at the end
so I guess just reusing them will probably be fine to a point
Well an area can only be so blood before you don't notice a difference.
like I said how permanent? Like I quit the game and come back and it's still there?
naw
exiting a level in any way will remove it
wonder if you could hack something into the scene's lightmap https://docs.unity3d.com/ScriptReference/LightmapData.html
but otherwise I expect you need to use decals or texture painting
A typical strategy is to use decals with object pooling
basically once you reach a preset decal limit you start recycling the oldest ones
yeah yeah for bullet holes etc
I was really just doing some research to see if there were any very overengineered ways I could do since it's a big part of the game (vs bullet holes being a small part of an FPS)
So I'm not the first one to thing of the lightmap approach it seems:
https://www.youtube.com/watch?v=z0ELnimWo0k
There's also the splatoon texture painting approach: https://www.youtube.com/watch?v=YUWfHX_ZNCw
splatoon just looks like texture painting so far
yep
alright thanks @sly grove @urban warren I'll have a look at this stuff and figure something out
.material / .materials are very common sources for memory leaks, as they are not automatically destroyed at any point, so you will need to manually destroy them at some point.
and idk if this will be enough Destroy(meshRenderer.material);
i think you may need to have a cached reference
im not sure about that part tho
yeah im already doing that but still theres some leak
DESPERATE mode
try caching the meshRenderer.material to some variable and just use that, and then destroy that?
is there a reason you can't use .sharedMaterial?
both
don't use sharedmaterial if you're gonna set properties on it, it's a very bad idea
sometimes it happens that the changes get serialized changing your asset
property blocks are very good for perf, use thise
Should i be worried about the performance of Vector3.Distance ? i know it gets exponentially more costly, the longer range the distance is checking. i have doors in my game, potentially 100's. and i was going to have a function on my player loop through all these doors, and if the distance is less than some threshhold, open the door.
is there a faster approach to this, that doesnt involve trigger colliders? i currently have this, and not very often, but enough to be a problem, the triggers stop working, i am using a Character Controller for my player. Which im sure is the root cause.
Anyway, is it ok to use distance checking, or some other approach?
if you're just doing a distance check you could check (a - b).sqrMagnitude < threshold * threshold
that way you don't have the sqrt
how would that help me?
does shared material gets deallocated?
distance is just the sqiare root of the difference between the points
But its expenive
.
whats the sqrt for then
the length of the vector
- it's not
- you can just not compute the sqrt then it's faster
do as Tecci said above, with sqrMagnitude
it's just gonna be 3 multiplies
very cheap
and essentially gives the same result?
yes
it's essentially the same as Vector3.Distance(a, b) < threshold but without the sqrt
sharedMaterial is the asset itself essentially
so I think it always exists
but i dont want it to exist always, the texture im setting is heavy and i just wanted for a specific view
now seems im releasing more memory
but some texture wasnt deallocated,
if the texture is not an assetreference (not dynamically loaded) it's going to stay in memory as long as it's referenced anywhere
I'm trying to read the pixels from a rendertexture and use them to set the color of a light source, but I'm getting weird results...
The quad on the right has a camera pointed at it which is capturing one pixel of the texture and is writing it to the spotlight's color value. but as you can see the spotlight's color is very dark in comparison and more saturated to boot.
public Light lt;
void Start()
{
}
void OnPostRender()
{
tex.ReadPixels(new Rect(0, 0, 1, 1), 0, 0, false); // Read pixel from the 1x1 rendertexture that is the target for the camera on this object into a 1x1 texture.
tex.Apply(); // Copy the texture we wrote the pixel to from the GPU to the CPU.
Color[] pixels = tex.GetPixels(0, 0, 1, 1); // Read the pixel color from the texture.
lt.color = pixels[0]; // Set the light color to the pixel color. If the light is too dim, adjust its intensity. Don't multiply the pixel color as it may be clamped and not treated as an HDR color.
}```
{
Properties
{
_MainTex ("Render Texture", 2D) = "white" {}
_Mip ("Mip Level", Float) = 9
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
UNITY_VERTEX_INPUT_INSTANCE_ID
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
UNITY_VERTEX_OUTPUT_STEREO
};
sampler2D _MainTex;
float4 _MainTex_ST;
float _Mip;
v2f vert (appdata v)
{
v2f o;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_INITIALIZE_OUTPUT(v2f, o);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
return o;
}
float4 frag (v2f i) : SV_Target
{
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
float4 col = tex2D(_MainTex, float2(0.5, 0.5));
// Some kind of gamma transformation? Makes colors brighter.
//col /= 2.55;
//col *= 1.5 - col * col * 0.5;
//col = pow(col, 1.15);
return col;
}
ENDCG
}
}
}```
So basically that code is taking a 1024x1024 rendertexture from a video player, using a special shader and the generated mipmaps to color the whole quad with the smallest mip level, capturing the quad with a 1x1 isometric camera, and then copying that color to a spotlight to simulate light from a TV.
what i mean is, if that texture is a serialized field on some script, it's going to stay in memory forever
I'm pretty sure
how i can use mesh from so (i has so that contains mesh) and create world from that mesh like minecraft. i saw many vids where coder just code it itself. but how to made simmilar thing but with ready mesh?
well, you need a mesh renderer and amesh filter on an object. then you set that mesh on the mesh filter
i dont need to set mesh. i wanna generate new mesh using one from SO
like MC world. where you has many cubes
yeah, you can just write vertex data to a new mesh
so i has mesh of cube. but how i can copy/paste it and combine for optimisation?
will it works like this
input
combined & optimized
so i wanna get second one after generation done
there's no built-in way of doing that, I'm pretty sure
Yeah you'll have to write that yourself.
crap
there are algorithms tho
if it's just a one dimensional line of cubes shouldn't be that hard
if it's arbitrary voxels, I wish you luck
I saw some papers being referenced on an efficient algo for this
google it
bc its much complicated to create it from scratch
I don't have links
In my inspector, the 1x1 texture tex which this is writing to seems to be capturing the right color from the quad. But it's when pixels[0] is copied to the light's color that the color on the light doesn't match at all.
it must be the shader then?
No, the shader is what is causing the quad to be the color it is on the screen, which is the average color of the render texture for the video.
The color seems to be correct when pulled from that and written to the 1x1 texture. But when it's copied from the 1x1 texture to the spotlight, the resulting color on the spotlight is much darker. Much darker than even a linear to srgb color conversion could account for.
I picked the color off the screen and these are the values I get.
But... both the color read from tex and the color the spotlight is set to are much smaller values:
At least I know now that it's not the conversion from pixel[0] to spotlight color where things are going wrong. It's pixel[0] which is wrong.
But that doesn't make sense because this is tex:
And if we zoom way in on it we can see it's the right color too:
So this seems to be working:
tex.ReadPixels(new Rect(0, 0, 1, 1), 0, 0, false); // Read pixel from the 1x1 rendertexture that is the target for the camera on this object into a 1x1 texture.
But something is broken here:
Color[] pixels = tex.GetPixels(0, 0, 1, 1); // Read the pixel color from the texture.```
Does it take longer and longer for packtextures to run the smaller the desired atlas size is?
also why does packtextures create a texture of the size of maxsize, when I thought it was supposed to create a max size texture of that size instead of defaulting to it
Your best bet is to profile this yourself.
fair enough
what is your creative objective?
rendering to a 1x1 texture doesn't do what you think it does
a 1x1 pixel screen rendered through a unity camera will not be the "Average color" of a 320x320 pixel screen
My objective is to set the color of a spotlight to the average color of a video feed. And to calculate that average color without reading every pixel because that would be too slow, and in any case, I don't think VRChat's scripting language Udon, would be up to the task. So I'm having the graphics card calculate the mipmaps for the render texture, then using a shader that blits the pixel color of the smallest mipmap to a quad, and a 1x1 pixel camera with another rendertexture grabs the color, and then it's grabbed to a 2D texture which is copied to the CPU and from that I grab the single pixel color to write to my spotlight.
average color of a video feed
what do you mean, video feed?
so you want to set a light to be the "Average color" of a frame from a video?
the average color of most video feeds of natural/imitation of reality scenes is going to be very close to gray. are you sure you want the average color?
That quad has a material on it. The material's shader grabs mip level 12 from the rendertexture that the video player is writing to. That's where the average color is coming from. Then the 1x1 camera that writes to a 1x1 render texture is pointer at that quad and grabs a pixel. No averaging done in that step.
it sounds like, creatively, you probably want a key color or a hue or something
the mip maps don't mean what you think they mean
I want the light to look like the light is coming from the TV screen, which would be the average color of the screen, which would be the average color of the texture. And the video feed isn't of natural scenes, its of video games. And mainly I'm concerned about how bright it is or isn't so when the screen goes black, the TV isn't still emitting light. But it picks up some color too.
the light from a tv screen isn't hte average color... i'm telling you, the average color is gray
Have you considered using a compute shader to calculate the average?
you are saying average, do you mean statistical mean?
the light from the tv screen is going to be the sum of the colors
on real life tvs that do this, they use a key color, a hue
and some creative interpretation of the overall lightness
anyway, if you want to read a video frame, you should read a video frame
it doesn't make sense to go through all this rigamarole
this looks good to me
you can read this texture directly and work with it
if you want to keep it all in the GPU, you can create a shader graph / a material that binds this specific texture and does the thing you want, i would suggest looking up how to find the key color
a filter
essentially
using what you are already doing with blitting
even if it's of video games
most of the time it's going to be gray
i mean, did you try this?
When I said the average I meant the average because that's what you get with a mipmap.
And while you're correct that the light emitted from a screen is additive, the average of a fully white screen is white, and the average of a black screen is black, and the average of a screen which is half white and half black is gray. And if its half red and half green... Well, I will get a yellow, but yes, it won't be the correct brightness, it would be half as bright as it should be.
All that is besides the point though. I need to do this fast in VR. In a scripting language that isn't fast.
And the quad I have on the screen looks good enough. The problem is that when I sample the color from that quad what I end up with is MUCH darker. Like 1/100th the pixel values it should be.
The quad itself is being calculated correctly from the video feed.
you should use decals. if it's too slow, and it's something small, just place a quad.
That's beyond my ability. I'm only a baby when it comes to working with shaders. The shader code I linked to, someone else wrote, and I modified it to sample just one color instead of three from top to bottom on the screen.
Is this the actual shader you are using?
Even if you dont know shaders, you can see that _mip is defined, but never used
It doesnt sample from whatever mip you put in
You could perhaps paint into the lightmaps. Or use a shader which has a texture channel that uses the lightmap UVs, and paint into that. Even if you're not using lightmaps you can generate lightmap UVs on import of your meshes automatically.
That's if you want permanent blood stains though. I don't know of many games that do that. Most will use something like decals that fade out over time.
For that you want tex2dlod:
float4 col = tex2Dlod(_MainTex, float4(0.5, 0.5, _mip, 0));
In VRChat, since I can't calculate decals, I use a triplanar mapping shader to make blood splats. It applies my decals to any surface that a cube overlaps, and the cube is a mesh particle that has animated alpha to make it fade.
I'll give that a shot now, though I can't see how it would fix my issue because even if the color of the quad I'm seeing in my scene view is incorrect, and I fix it, the issue that the spotlight color ends up much darker would remain and the shader stuff happens when the quad is drawn.
Hey so I use packtextures to create atlas's, but it seems that the textures arnt being cleared after I put them in the array, then clear, then trim the array of textures resulting in this:
how do I fix this?
Textures need to be destroyed manually if you create them.
I just put them into an array
Do you have 7 gigs worth of textures in that array?
It's hard to tell if the color is more correct now or not, but here is a brighter scene with a lot of yellow. And you can see that the quad is fairly bright, but the color picked from it and put on the spotlight, is much darker. The spotlight is (.43, .38, .18) while the quad is (.77, .70, .52)...
I suppose I might
Do I need to call dispose on each thing in the array?
I do have a post processing volume on, though. When I disable that the quad is now (.68, .65, .46) But that's still a ways off the spotlight color read from the texture.
If you are no longer using the texture (and no other automatic destruction applies), you Destroy() them.
ok
so call and destroy each instance of the array then
Once you aren't using them anymore, yes
wait no last time I did this it destryoed the orrigional textures in the file
I had to call destroyimmediate cuz it was in editor
It shouldn't destroy assets if you don't pass in true to the method
"Destroying assets is not permitted to avoid data loss.
If you really want to remove an asset use DestroyImmediate (theObject, true);"
They are all native objects?
How can I best assign optional behavior to a scriptable object? I have items in my game defined as scriptable objects. Some of these items are weapons. The most brutal solution I can think of is to assign a string ID field to the items--if this field has contents, (i.e. "Pistol"), then the relevant code can lookup the correct weapon interface implementation in some "WeaponDB" singleton via the string ID.
That would work but it's pretty ugly to write and maintain. Is there a better way? I initially tried to make the itemdata SO contain an optional secondary "Weapon" SO that would have behavior--but it occurred to me I'm not sure how that would work...
I could conceivably have the separate weapons extend the base "Weapon" scriptable object type...? 🤔
btw a weapon is basically an interface, a few methods like OnFireWeapon etc.
Rider seems to allow me to extend a type that extends ScriptableObject... so presumably I could have these things extending the Weapon scriptableobject... but then each descendent type would need its own version of the
CreateAssetMenu attribute and that menu would be pretty ugly... doesn't seem quite right to have only one instance of each... 🤔
Hmmmm from what I can gather from Google it sounds like a "behavior library singleton" might be the most correct way. Doesn't seem like SO's are meant to have variant behavior
It has been a while since I used NewtonsoftJson. I finally managed to read the json data and convert it, but I feel like I am doing it wrong or inefficient. Can someone give me some input on how I can simplify this?
Basic structure: "numtacs" : [{}...], "actions" : [{}...]
Here is code:
if (File.Exists(SAVE_PATH))
{
using (var file = File.OpenText(SAVE_PATH))
using (var reader = new JsonTextReader(file))
{
var data = JToken.ReadFrom(reader);
var numtacsToken = data.SelectToken("numtacs");
var actionsToken = data.SelectToken("actions");
var numtacsData = JsonConvert.DeserializeObject<List<NumTacElement>>(numtacsToken.ToString());
var actionsData = JsonConvert.DeserializeObject<List<GameBoardActionElement>>(actionsToken.ToString());
foreach (var n in numtacsData)
{
Debug.Log($"N Value: {n.Value} | InPlay? {n.InPlay}");
}
foreach (var a in actionsData)
{
Debug.Log($"A Type: {a.Type}");
}
}
}
I'm particularly worried about the part where I convert the JToken to string to deserialize it...
The top one is the render texture. The bottom is the 1x1 Texture2D which is sampled from it that should look identical here but is way too dark. (The bottom one is the one I'm grabbing my spotlight color from.) I've included the settings for the two textures, and for the camera pointed at the center of the top quad which is sampling it and writing to the rendertexture. There seems to be some kind of gamma correction going on here, but I'm in linear color space.
{
tex.ReadPixels(new Rect(0, 0, 1, 1), 0, 0, false); // Read pixel from the 1x1 rendertexture that is the target for the camera on this object into a 1x1 texture.
tex.Apply(); // Copy the texture we wrote the pixel to from the GPU to the CPU.
Color[] pixels = tex.GetPixels(0, 0, 1, 1); // Read the pixel color from the texture.
//Debug.Log("color = " + pixels[0]);
lt.color = pixels[0]; // Set the light color to the pixel color. If the light is too dim, adjust its intensity. Don't multiply the pixel color as it may be clamped and not treated as an HDR color.
//Debug.Log("spot color = " + lt.color);
}```
This is the code used to grab the color from the render texture for the camera pointed at the top quad, put it into the 2d texture for the bottom quad, and then sample it for the spotlight color.
The shader generating the color of the top quad from the video stream doesn't really matter, because whether the color of that quad is right or wrong when its generated, the one on the bottom should still match it.
How can I best assign optional behavior to a scriptable object?
don't. stop while you're ahead
use scriptable objects as immutable data only
if you want to compose behaviors, use a prefab
A prefab has to be a gameobject right? 🤔
The scriptableobject could just reference a prefab, too, though
The scriptableobject itself IS immutable
A given instance of scriptableobject will not change which set of behavior it references
And the behavior set is relatively static also
yes
A better way to phrase my question is "What's the best vehicle/container for variable behavior that a scriptable object can hold a reference to"
a prefab
but then, you might as well use the prefab
Items are rarely gameobjects though
yes, but does it matter
does it hurt that much to pay the price of 1 Transform component?
I was responding to this specifically
You tell me 😛
That was the question
it does not
it doesn't hurt
you can make an empty game object, assemble all your scripts together intuitively
like, a Weapon script
and a RapidFire script, and a BeamRay script
that composes all the behaviors
🤔 So just write the weapon behaviors as a series of components that implement the weapon interface?
And then slap those on prefabs and reference those
That pretty much answers my question. I wasn't sure if gameobjects were too heavy for such a thing
Extending the scriptableobjects definitely felt strange
yes slap them on prefabs
Extending a secondary one I mean
you should retire the scriptableobjects while you're ahead
only a game object instanced in the scene will have runnable code
this makes sense to me - if you want to "equip a weapon" instantiate the prefab and put it in the hierarchy of something that equipped it
Like I said the original question implied something different about what I'm doing with the SO. It's just a proper immutable data container
yeah but it's redundant to have a scriptableobject reference a prefab
Most items are just some basic numbers and strings
you might as well just use the prefab
It's not because a tiny portion of items will have to do so
the prefab can have a weapon component that references the scriptable object
that generally makes more sense to me
99% of items will not need any behavior at all
i see
Think of like, a piece of wood in minecraft or something
QWuest items etc.
But yeah if it was only weapons then that would make sense
The prefab thing is good because it also makes it easier to have somewhere to put the weapon model and such

how to remove blurry imported textures at runtime
i am working on modding support and am using relative small textures, i want to remove this stupid blur
runtime
not import settings
wow
an hour for this?
thanks
How do you get all gameobjects that are at the top of hierarchy(aka have no parents in the hierarchy) from an editorscript(basically meaning I dont have access to the children)?
OHHHh thank you!!!
Okay so I've solved the problem. Though I'm not entirely sure what I did. I think I got the bottom quad looking like the top one by turning off SRGB on the 2D texture. However, that was only half the problem, the color sampled from it was still way too dark. But I found the solution:
lt.color = pixels[0].gamma;
That does a gamma transform on a linear color. Which the color for lights seems to need? I don't know for sure, but the color the light is set to is now identical to the color of the quads onscreen, and the brightness doesn't like, stay mostly dark and spike really bright when eveything on the screen is bright, which was also preventing me from just solving the issue by turning up the spotlight intensity.
so small question I have a list with light Objects, I want to flicker the lights but it happens in sync. how can I change this I use a foreach statement.
foreach (var Light_ in LightList) Light_.intensity = _startingIntensity + Mathf.Sin(_time * _flickerPerSecond) * _flickerIntexity;```
this what i do now it looks like a mess tho'
I'm not sure if that's the best way to do light flickering, but your issue is that you're only calculating one random value to add to the lights and then adding that same value to them all each frame.
foreach (var Light_ in LightList) Light_.intensity = _startingIntensity + Mathf.Sin((Time.deltaTime * (1 - Random.Range(-_speedRandomness, _speedRandomness)) * Mathf.PI) * _flickerPerSecond) * _flickerIntexity;
That I think would make them all individually random?
Keep getting the error that object reference is required for non-static field, method or property GetRootGameObjects?
yeah you need to call it on a scene
ohhh so I need the scene name, Icant just do Scene.GetRootGameObjects
how do I automatically get the scene name then?
ohhhh thanks! illtr y
what would be another way to do it?
then a list
I'm not saying you did it wrong. There's a million different ways to write code that does the same thing. For example, you've got sin() in there. I probably wouldn't have used sin() myself. Flames just change brightness at random, and you don't need sin() to increase or decrease the brightness at random.
But another way I can think of that you could do it would be to have a 1D lookup texture with some perlin noise in it. You just step through the noise based on the time step, like scrolling a texture, and loop around when you get to the end. The perlin noise would naturally have hills and valleys to create variation. But the size of the texture would dictate how often the light pattern repeats, so perhaps this is not an ideal method.
At the same time, just changing the brightness at random your flame might get stuck being pretty dark for a long time. So perhaps some kind of inverse function that makes it more likely to increase in brightness the darker it gets and vice versa would keep it around the middle like you want.
I just don't know off the top of my head what what you did with the sine wave would look like is all.
But beyond the math here, there's also the issue of why you're using a list to keep track of your lights at all...
Unless you are doing that for a specific reason... That seems like an old school way of handling things. In Unity, one would typically just create a script that you put on each torch that handles only that torch's own animation. And then all the torches would run their own scripts and naturally be pulling their own random variables. And the code ends up being simpler that way because unity handles the "list" which contains all your objects in the scene.
Is there a way to access a lights shadow map as a texture?
but isn't that unoptimized to have a Update functions for each light?
Computers are so fast these days, that's not something I'd be concerned about. Especially for a simple light flicker animation that changes one variable.
I run a web browser with 100 tabs open, a video capture application, and play VR Chat all at the same time. Whatever game you're making will not be slowed by a few torches. 🙂
xD
And that really is how games are made these days. You'll know when something needs optimization. You shouldn't worry too much about optimization early on when writing your game, it's easy to get stuck worrying about that and wasting time on stuff that isn't actually going to increase performance by any appreciable amount.
I just did what you said i just added individual script and it works fine
its all random
So. How i can generate mesh from prefab?
Rn im just pushing vertex + triangles with uv to reult list and trying to display it. And get wiered result. (Pushing with offset)
If I want to open a door or a chest when the player is pressing a key and also is looking at it, does it only work with a raycast?
When you say "looking at" it always raycast
When you say "near" its collider (triger)
dot product would work too (cam viewing dir * dir to target)
i think you can look at the hdrp or urp package source to see where it can be retrieved
yeah, i personally like the dot product approach way more
it's a much smoother experience than the raycast approach
where would i find those?
How can I enable C#8 in unity 2021.3.2?
it uses c# 8 by default
Ah, I see. I guess it doesn't support the body-less using statement?
I thought that was an 8 feature
it does
Hmm....
Oh, that's right. I need to return the varaible.
I forgot
using (HashSetPool<BaseNode>.Get(out var nodeDependenciesGathered));
using (HashSetPool<BaseNode>.Get(out var skipConditionalHandling));
No, still complaining
What am I doing wrong here?
get rid of the outher brackets
Ah yes. Nice.
using var _1 = HashSetPool<BaseNode>.Get(out var nodeDependenciesGathered);
using var _2 = HashSetPool<BaseNode>.Get(out var skipConditionalHandling);
guess this is what it gotta be
correct
if you don't use the variables, please just use the discard operator
You can't
is there any reason i cant find this built-in shader by code using Shader.Find("UI/Unlit/Detail")
?
Is the shader included on build
oh sorry i thought it was a custom one, it should be included yeah
even built-in shaders can be removed in build if nothing is referencing
It isn't unless you're explicitly using it
ooh, ok
You can reference it explicitly in Project Settings / Graphics / Always Included Shaders
oh thanks a lot!
[ RequireComponent(typeof(AudioListener)) ]
public class Buddha : MonoBehaviour {
private void OnAudioFilterRead( float[] buf, int channels )
{
Debug.Log("OOFR");
circularBuf.DrainTo( buf );
}
Upon opening Unity, even without hitting the Play button, my console is filling up with these OOFR log messages.
How come the code is executing even when I haven't pressed play?
I've spun up an old (2014) Unity project, and I'm getting NullReferenceException on that .DrainTo line.
Trying to figure out what's going on.
There must have been some change in the way Unity executes code attached to objects, i.e. now it's executing prior to running and in 2014 it wasn't.
The documentation for the method has a boolean that they set on start, so I would do that.
@austere jewel That wasn't for me, was it?
ah I see. Thanks!
Hey guys, I need some design help. I have these scripts for each GameObject type in my game: Physics, Renderer and Movement. Now, when Physics detects a collision, it will call an event called OnCollide, which will then handled by the Movement script to move the object. But I want Renderer to be able to interfere with that behaviour, so it could say e.g. "object is not being rendered, so don’t move it". But how can I make it listen to that event and then cancel it?
Outside of Unity, more precisely in WPF Windows apps we have something like that: routed events.
When raised, they pass a class instance as an argument, that contains a boolean value whether to route the event further (usually up the UI tree). You could have that too:
Renderer
public void OnCollideHandler(RoutedEventArgs e)
{
e.Cancel = !isVisible;
}
Movement
public void OnCollideHandler(RoutedEventArgs e)
{
if (e.Cancel)
return;
// rest of logic here
}
This works because RoutedEventArgs is a class, ie. passed by reference.
As long as you subscribe in the right order of course, so the routed event travels the right direction (here renderer then movement)
How i can create collision between cloth with mesh collider object ?. In documentation cloth only work for sphere and capsule collider.
That sounds good, but I don’t know if this is a good way to do it, since all events are subscribed in Awake()
Am I just overthinking this? Maybe there is a much easier way to achieve the same result?
Hm, so maybe another layer on top of this that defines the "priority" of a handler, which handler gets called first?
And no, you're not overthinking this, as events don't know about the sender you can't know about the state of the sender, unless you pass a reference to it, which could be another solution
Oh, and the cancellation could be handled by the class that raises the event, like that
// proxy a method that raise the event for you
RoutedEventArgs e = new();
foreach (YourDelegate handler in yourEvent.GetInvocationList())
{
if (e.Cancel)
break;
handler.Invoke(e);
}
With this, no more checking in your handlers if the event got cancelled, they won't get called at all.
Hmm, I don't really know if this would scale well
invocation list order is undefined, you are trying to solve a profound coupling problem by modifying event payload, with more subs and undef order this will become unmanageable mess
this is game code, not ui code, order and precision, verbosity here is paramount
couple the systems, best way here, if renderer somehow has the power to dictate movement logic, they are coupled and no amount of hiding it will fix the issue
also each call to getinvocationlist allocates new array
Hello everyone,
I'm working on a game where i need to have anything like 2 or 3 thousands enemies. Each enemies will moove toward the player (and specific enemy can have specific pattern, but but well). Actually my main problem is when i have like 1500 enemies on the map (without animation) i begin to have a big drop of fps (300 to 140). I already implemented an update manager in order to manage the update frame of each enemy gameobject but i'm still having some issue with performance. Actually i have only one type of ennemy and i want to have an optimize base before do other ennemy, so if anyone have some experience with that i accept his help with greeat pleasure. (I can add some screenshot of profiler / statistics if it should help)
skinned meshes?
to optimize graphics you can use some plugins to bake the animation into a texture so that the shader animates vertices based on positional data in the texture, this way you dont need skinning at all
you can also use impostors for enemies far away, basically billboards
for pathfinding use flow field, cheapest pathfinding fitting your scenario
oh you said no animation, what are they capsules?
(300 to 140) is not a big drop
in reality it should not even be considered as valuable data
Mmm i don't have any pathfinding i think because i don't have any obstacle on the map. They just run to the player so actually i rotate the object toward the player and just forward.
For the impostors yes i think it's a good idea
Actually i have some drops without any complex mesh (i have the same behavior if all enemies are just a spher)
My fear is on batches, i don't really understand why but when all my ennemies are spawn the number are batches never stop to increase
(more than 3k)
probably because they arent gpu instanced
MMm maybe ! What i understand about it it's : i can just change check the box for GPU instancing on my material right ?
Or i can do anything else for that ?
Because i don't see anything about GPU instancing on my prefab
yeah its the only native way you can do it without coding or plugins
So if it's the only point, i have the gpu instanced active on my enemy material :/
first thing to do is to profile it, see what is causing the drop, script/logic or rendering?
Let me take a screenshot
you are overthinking it, as i said 300 to 140 is nothing
Yes but after that i can be block to 100 fps
with a 3080 a 6800x and 32gb ram. And this is only my first pattern of enemy. So if i can optimize the base that can be cool 😄
before you proceed - clear profiler and close it, switch unity to release mode, and show fps in release mode
As you can see i have 2 points with high usage :
- moovement of enemy (rigidbody calcul in unity)
- update function with manager which tick for all enemy (calcul of rotation and go forward with deltaTime and speed)
OK let me try it
dont forget to maximize game view when you are measuring anything
Yes already done 🙂
If I did my math right, it's a 3.8ms difference.
For turning unity to release mode i just need to change the code optimization on startup right ?
Oh yes so i'm in release mode 😄
Yes but when all enemies here, my player moovement are freezing / more slow than the normal
alright, if there are no batches saved by instancing, read the doc page on it, it must have specific cases where it fails, like maybe object scale or something like that
it means you coded your movement incorrectly
If it's freezing, it's because you have spikes. If it's slower, it's because your code isn't written to be framerate independent.
Have both 😄 but my standard enemy are pretty simple :
//Rotation
dir = player.transform.position - transform.position;
Quaternion lookRotation = Quaternion.LookRotation(dir);
Vector3 rotation = Quaternion.Lerp(transform.rotation, lookRotation, Time.deltaTime).eulerAngles;
transform.rotation = Quaternion.Euler(0f, rotation.y, 0f);
// Forward moove
transform.Translate(dir.normalized * (enemy.speed * Time.deltaTime), Space.World);
But i still don't understand why the number of batches never stop to increase
Enabling GPU Instancing on materials won't do anything if you're using URP or HDRP and have the SRP Batcher enabled.
You can't really trust the batch count in the Stats window if you're using the SRP Batcher.
even if the number of enemies stop increasing?
Yes it's my problem. On stats it's not increasing during the spawn of ennemies but when ennemies begin to be visible on the player screen the number increase without limit (and the saved by batching value still 0). i'm looking about the Srp batcher option like said MentallyStable (thank you all for your help btw)
So i have checked and yes i'm in urp mode with srp batcher enable, so the batch count is wrong ? do i need to disable it in order to improve performance ?
The batch count in the Stats isn't a good indicator of performance because it's counting each separate draw call in SRP batches. The SRP Batcher makes each individual draw call in a batch much cheaper than normal, similar to GPU instancing.
You should use the Frame Debugger to see how well it's managing to batch
and you should not enable gpu instancing on any srp batcher compatible material
Oh ok i understand what you mean now
Ok i disable it now
Mm i loose lot of performance if i disable it :/
you should gain a lot of performance if you disable it
Are you testing with a sphere mesh for enemies like you said before?
Yes
Are you eventually going to replace those with animated skinned meshes?
Yes this is the goal, a skinned mesh with little animation, like rotation
Actually if i put my mesh what my scene look like is :
You can't do that with GPU instancing without doing the animation in a custom vertex shader. I'm not sure how well SRP Batcher handles skinned meshes, but you're going to want to do something custom for a large amount of meshes anyway.
Ok noted 🙂
what im i doinng wrong here? the textture is nnot being assigned 😦
aftter the last line, im debugging and the meshRender has the new material butnot the texture
Is this a bad performance?
What exactly does running on editor means?
You mean if I run it inside Unity? and not build?
is the profiler conneccted to the unity player or to your phone / app
yep
I just run it on Unity. I'll later make a build for my Phone.
I dont use Unity Remote 5 because its super laggy
i think it doesnt perform bad but not an expert on profiling
Alrighty 🙂 Thank you
You're getting consistently 150-200 FPS. Is that bad to you?
Would this create memory leaks? I just want to change the the material of a meshRenderer keeping the same texture in one method and changing back in the other one
i tried to do it with MaterialPropertyBlock but the texturewas not being saved for some reason
Im not familiar with Profiler, just found out of it. So from your tone of irony I get that everything goes smooth with my 200 fps
heheh
yes, ffps= frames per second... thats quiet a lot
a normal tv shows frames at 24fps
well at least when i was younng
im not sure nowadays
I mean
you can just look at the game
if it goes smoothly then it goes smoothly, you don't need to look at numbers to confirm that
could someone check those fuctions?
i tried for hours make a version of them with MaterialPropertyBlock but i failed
building now to see if they memory leak
why i get this?
var verticies = new List<Vector3>();
var triangles = new List<int>();
var uv = new List<Vector2>();
var staticOffset = Voxel.Mesh.vertices.Count();
for (int x = 0; x < X; x++)
{
for (int y = 0; y < Y; y++)
{
for (int z = 0; z < Z; z++)
{
verticies.AddRange(Voxel.Mesh.vertices.Select(v => new Vector3(v.x + x, v.y + y, v.z + z)));
triangles.AddRange(Voxel.Mesh.triangles.Select(v => v + (x*staticOffset) + (y * staticOffset) + (z * staticOffset)));
////mesh.uv = Voxel.Mesh.uv;
uv.AddRange(Voxel.Mesh.uv);
}
}
}
var mesh = new Mesh();
mesh.vertices = verticies.ToArray();
mesh.triangles = triangles.ToArray();
mesh.uv = uv.ToArray();
mesh.RecalculateNormals();
foreach (var item in verticies)
{
var t = Object.Instantiate(Prefab);
t.transform.position = item;
Object.Destroy(t, 1);
}
MeshFilter.mesh = mesh;
X 5 Y 2 Z 2
so basically im creating mesh there. and vertexes on correct positions (bc prefabs was spawned where it must be)
but it seems smth wrong with triangles. any ideas?
also when im generating 1d (in one direction) all works fine
ok so i found it. problem in triangles code
var staticOffset = Voxel.Mesh.vertices.Count();
var counter = 0;
for (int x = 0; x < X; x++)
{
for (int y = 0; y < Y; y++)
{
for (int z = 0; z < Z; z++)
{
verticies.AddRange(Voxel.Mesh.vertices.Select(v => new Vector3(v.x + x, v.y + y, v.z + z)));
triangles.AddRange(Voxel.Mesh.triangles.Select(v => v + counter));
counter += staticOffset;
////mesh.uv = Voxel.Mesh.uv;
uv.AddRange(Voxel.Mesh.uv);
}
}
}
but how i can do it without external counter?
how can I create a collider that turns on and of a GO parts depending if it enemy or player Tag and also let the projectiles passthrough it.? my code works but the projectiles cant pass trough the collider.
need a collider that is invisible to specific tags but visible to other tags.
for example when player shoot it set active is true and when enemy shoot set active is false but when it is false the projectiles won't hit it. I created a GO with a nested brick that toggle on of but the projectiles hits the GO and not passing trough just on and of without the disappearing option but if i will set active false the GO the player projectiles will not find the GO to reactive the brick any solutions for this scenario?
Yes I know but I test it on a Mac but it will be build on a phone. So..
It works fine.
But some times the fact that it seems to work fine doesn't mean that there is not room for improvement.
The profiler can't tell you how well it'll run on another device
what is the point of that condition in the default case? it's literally the case directly above it. if you don't want it to do anything if the tag doesn't match any of those then just leave the default case empty with only a break statement. (also not an advanced issue whatever the issue is)
Hi, how do you use CustomAttributes to do something similar to [CreateAssetMenu] or [MenuName] in Unity? I have a custom editor window in which I would like to retrieve each class tagged with a certain Attribute
or better: source generator
Thanks, exactly what I was looking for!
do they support them now?
it looks alright to me
it should probably be at 100fps all the time, but i think ti may be that way when you actually try it on your phone
how it combines it? can i generate "chunk" using that?
or it will be not optimized mesh?
Meshes are arrays of vertices, triangles and uvs (and other stuff), so I am assuming it simply appends arrays one after the other and does some other stuff in the background
ok so. if i want greedy mesh i need to do it myself?
no
it will be in one batch call as i know
Mesh.Combine takes the data from mesh A and concatenates it with mesh B
the net amount of tris will be mesh A tri count + mesh B tri count
You can try that one, or maybe try to find some external libraries that may help with greedy meshing
whether or not you get a performance improvement from Mesh.Combine is circumstantial
have you tried checking Static on the game object?
for example, you will not gain anything from static on many copies of the same object. it's better to use instanced geometry instead
is this helpful? @copper nexus what's your gameplay objective?
basically what i want to create is thing like stormworks building. + add extra features like in game scripts.
rn im trying to craete mesh generator. that will take mesh from prefab (so i dont need to manully set all mesh data...)
- remove/add blocks
i suggest you don't overthink it
you should use mesh instancing
and do not try to mesh-combine
just tightly pack your cubes
?
make sure the material has GPU instancing checked
then you're good to go
it will perform better than anything else
i wanna get rid of GO