#archived-code-advanced

1 messages · Page 192 of 1

inner dome
#

Hey guys, I've been working on a turn-based multiplayer game, using a Task/UniTask-based loop+Command pattern for handling how the game should go, and I've been stumped on the UI part

Question is: how should I handle the "which UI screen/state should I show after this action" part?

compact ingot
inner dome
#

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

compact ingot
#

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

inner dome
compact ingot
#

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

inner dome
#

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"

compact ingot
#

ui code is often way less generic that your other code

inner dome
#

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

compact ingot
#

you might benefit from inverting your way of thinking about ui

inner dome
#

Everything else is cool tho

compact ingot
#

you do not show ui, you have your ui decide to appear

inner dome
#

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?

compact ingot
#

yes

hardy sentinel
#

geez

hardy sentinel
inner dome
#

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

hardy sentinel
#
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

inner dome
#

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

compact ingot
#

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

inner dome
#

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

compact ingot
#

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

inner dome
#

The views are thankfully already done, those were relatively not-so-difficult to implement compared to this part :D

compact ingot
#

you mean the designs or the actual controller/presenter code for the views?

inner dome
inner dome
compact ingot
#

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

inner dome
#

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

compact ingot
#

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

inner dome
compact ingot
#

zenject is evil 😄

inner dome
#

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 joyyy

compact ingot
#

its just way too much code that does nothing

#

rx is great in theory and powerful but can lead to some pretty nasty messes

inner dome
#

But for smaller timers and "wait for next emit" things it's good

compact ingot
#

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

inner dome
#

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

compact ingot
#

yeah,that might not be the best architecture if you need lots of those

#

way too easy to deadlock your logic

inner dome
#

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 joyyy

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

compact ingot
#

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

inner dome
compact ingot
#

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

compact ingot
#

you could say, "keep overlap to a minimum", distribute stuff in time and space to become discrete (as a strategy for avoiding complexity)

inner dome
compact ingot
inner dome
#

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"

compact ingot
#

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

inner dome
#

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

compact ingot
#

it was a text based game, so that seemed like a natural fit

#

wasn't actually too painful, except for the limitations of coroutines

inner dome
#

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?

compact ingot
#

yes

#

and nesting

#

no detailed cancellation control

inner dome
#

And handling cancellation of those nested coroutines sounds
Fun

compact ingot
#

so would have been much easier with unitask

inner dome
#

E.g. Don't pass the same cancellationToken to a WaitUntil and any other task that you'd use afterwards

compact ingot
#

thats just how tokens work

inner dome
#

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

compact ingot
#

a token is a disposable that can be canceled only once

inner dome
#

That was a part that I kinda "rushed" into

inner dome
compact ingot
#

ic

inner dome
#

Like
The task would just "finish" and not "cancel"

compact ingot
#

ic.

inner dome
#

But that's just a personal issue with not enough knowledge about the topic

compact ingot
#

cancellation tokens aren't the end all for task lifecycle management, so yeah, quirks

#

still better than nothing

inner dome
#

Yeah, it also saved my bum a lot of times

compact ingot
#

and you are free to use all regular sync primitves

inner dome
#

Thank you for your help btw :) gtg now, have a nice day

compact ingot
#

cya

undone coral
#

i think what you've been missing is TaskCompletionSource

#

which is, in other words, a future

undone coral
soft hawk
flint sage
#

WaitUntil is pretty useful fwiw, it's not worth using TaskCompletionSource for everything

soft hawk
#

Oh yea for sure, i'm not really that worried about it

maiden turtle
#

How do I load a scene, run all awakes, but not run any starts

#

Then run my function, and only then run the starts

somber tendon
#

Make all start ienumerator, yield until you run the function

maiden turtle
#

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;
});
lucid girder
maiden turtle
#

Moreover, it's just stupid

somber tendon
#

not stupid if it (might be) work 😉
but not effective either

maiden turtle
#

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

lucid girder
#

the other way is disabling all scripts

#

iirc there is not a "good" way to stop Update from running

maiden turtle
#

There's got to be a way

#

Disabling all scripts is too much complexity and noise, it's a terrible solution

lucid girder
#

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

maiden turtle
#

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

somber tendon
#

Make all start ienumerator, yield until you run the function, start coroutine 'customupdate'

maiden turtle
#

That's the thing

#

That's why Update happens before they are initilaized in the first place

lucid girder
# maiden turtle I'm initializing the scripts manually from the outside, not with starts

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.

maiden turtle
#

Awakes are called in a random order

lucid girder
maiden turtle
#

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

lucid girder
#

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

maiden turtle
#

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

lucid girder
#

At this point it feels more like fighting the engine rather than working with it 😅

maiden turtle
#

It lacks too much stuff, I always end up reimplementing almost everything myself

compact ingot
buoyant vine
maiden turtle
#

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?

maiden turtle
#

That seems like the simplest and the most sane solution without too much extra complexity

compact ingot
#

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()

unkempt nova
#

Gotta be careful about that return if inheriting though. It won't cause a derived method to return

iron pagoda
# maiden turtle Awakes are called in a random order

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.

compact ingot
blissful peak
#

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:)

compact ingot
blissful peak
compact ingot
#

No

unkempt nova
#

You can just use onInventoryStackAdded?.Invoke(this, new InventoryEventArg(newItem)); btw, it's shorthand for that nullcheck

compact ingot
blissful peak
compact ingot
unkempt nova
blissful peak
unkempt nova
#

Seems like it could be helpful, seems to cover what you're wanting to do

compact ingot
#

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

maiden turtle
#

If it's not been inited, it should've been disabled, is my logic

compact ingot
regal olive
#

Is it possible to use LINQ in 2d arrays? The autocomplete is not giving me the Where

unkempt nova
#

tldr: No but there's a workaround

tacit hedge
#

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

hardy sentinel
#
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);
}
tacit hedge
unkempt nova
#

It works with lists

tacit hedge
#

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

unkempt nova
#

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

tacit hedge
#

yea i have this code

unkempt nova
#

Make sure you saved and have no errors in console

#

If you have errors, unity can't get around to checking for that code

inner dome
flint sage
#

This looks sketchy af

unkempt nova
#

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

flint sage
#

<@&502884371011731486> please deal with this either sketchy or legit file

deep coyote
#

i can just send the files, you're completely right

#

i mean, the code in a text file even

unkempt nova
#

#854851968446365696 for posting guidelines. And make sure you have a question. Nobody's gonna just convert it for you

deep coyote
#

i asked for help, not for someone to do it x)

#

ive been struggling with it

quartz stratus
#

@deep coyote there's more to switching input systems than just code. Just check out some tutorials, there are plenty online

unkempt nova
#

Yep, just saying the kind of help we offer is answering specific questions

deep coyote
#

okay I'll go back to it and make a list

flint sage
#

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

unkempt nova
#

The new input system requires very different choices architecturally, it's not just a syntax change

flint sage
#

Hence why we're being so careful

deep coyote
#

yeh the thing is, i never used the new input system so i have no idea where to even start

unkempt nova
flint sage
#

Then find a tutorial and follow it

frozen imp
#

Was a unitypackage, but yes can sneak in malicious code as well

deep coyote
unkempt nova
#

Thanks for checking

flint sage
deep coyote
#

xD too far

#

I also posted here, cuz the code is definitely not beginner friendly in these files

frozen imp
#

only looked at file type :)

deep coyote
#

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

night peak
#

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 ?

frozen imp
unkempt nova
#

Device Emulator is great. Easy to use and I had no issues. Can recommend

night peak
#

@frozen imp @unkempt nova i can't use emulator because it's a AR app. But thanks for your help.

unkempt nova
#

Ah

night peak
#

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

unkempt nova
#

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

craggy spear
night peak
#

yeah i know i can get the output console but i want to use breakpoint to be honest^^

craggy spear
#

breakpoints won't work on device ..?

night peak
#

my player don't show up on any IDE i use ( VS code, Visual studio , JetBrains rider )

unkempt nova
#

Think he's talking about remote debugging

long ivy
#

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

somber swift
#

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)

sly grove
#

the points you hit will give you the boundaries

#

or rather - a raycast up, then two boxcasts left and right? 🤔

somber swift
#

I don't want to use raycasting or anything like that (so only math). something similiar could be done mathematically tho

sly grove
#

raycasts are just math

somber swift
#

yeah

sly grove
#

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

somber swift
#

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

tribal pivot
#

Which, imo, sounds a lot like raycast 🙂

sly grove
#

a raycast won't see that

#

actually I guess that's fine

#

you'll just have a short box

buoyant bronze
#

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

formal lichen
undone coral
#

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

dire remnant
#

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 ?

compact ingot
dire remnant
#

bless you, ive been staring at this damn shit all day, i really should have tried harder in school

weary stag
#

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.

compact ingot
weary stag
#

Well it's my own library.

drifting galleon
#

and please only use .net standard 2.1 compatible libraries going forward

drifting galleon
compact ingot
#

yes, libraries are still best off targeting 2.0 or 2.1

weary stag
#

well, .net standard 2.1 doesn't feature MethodImplOptions.AggressiveOptimization?

compact ingot
#

then don't use it

drifting galleon
#

well then comment out that attribute

weary stag
#

or BitOperations

#

xd?

drifting galleon
#

either, don't use your library, or use .netstandard 2.1 compatible layer. or wait another 2 years for .net 6 support

weary stag
#

The attribute is there for a reason lol. It isn't just there to be there.

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.

drifting galleon
drifting galleon
#

1 - unity's community
2 - unity's devs

compact ingot
#

i for one have done zero work to make unity ready for .net 6

drifting galleon
#

well, some people have

weary stag
#

are Unity's vector structs at least SIMD accelerated?

drifting galleon
#

no

weary stag
#

wow

drifting galleon
#

there was no such thing in .net at that time

compact ingot
#

ofc they are

#

if you use burst

drifting galleon
#

yes^^ if you use burst

weary stag
#

There legit is.

drifting galleon
weary stag
#

What's burst?

drifting galleon
compact ingot
#

burst just knows a bit more about unity than "regular" compilers

weary stag
#

is it a JIT?

#

or a normal to IL compiler?

drifting galleon
drifting galleon
weary stag
#

aot?

drifting galleon
drifting galleon
weary stag
#

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

drifting galleon
#

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

weary stag
#

well ye but what bout the Mathematics namespace?

drifting galleon
#

just add the package and look at the source

compact ingot
#

why are you at the same time writing super low level code and asking such trivial questions?

weary stag
#

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.

drifting galleon
#

def not impossible

weary stag
#

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.

compact ingot
#

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

weary stag
#

Well it isn't in C to begin with.

#

It's in C#.

#

and it's quite performance capable.

compact ingot
#

you could just run it in a separate process

drifting galleon
#

if at all

#

that would also be possible

weary stag
#

that's pretty much making a UCI compatible GUI.

#

and then I would have to make it UCI compatible on engine side too

drifting galleon
#

you could also compile it with NativeAOT to dll and add it to unity

weary stag
#

oh?

drifting galleon
#

probably

weary stag
#

links please ❤️

compact ingot
#

google it

weary stag
#

I tried.

#

Everything is about .NET 7

#

even with .NET 6 as a keyword.

compact ingot
#

guess what that means

drifting galleon
#

yeah NativeAOT is only really available for .net 7 iirc. but just upgrade. that's no issue

weary stag
#

— idk about whatever performance regression comes along with .NET 7 yet. It's still in preview.

drifting galleon
#

none?

#

it even gets faster

buoyant vine
drifting galleon
buoyant vine
#

no

drifting galleon
# buoyant vine no

yeah it is. in what way is 'loading external dlls easier' related to 'my code is written in c#, not c' ?

stuck onyx
#

is it normal the allocation of a renderTexture is taking moree than 150MB of RAM ?

drifting galleon
#

no

stuck onyx
#

its a texture i create based on what the camera renders

#

4096x4096

#

depth 24

drifting galleon
#

that may or may not get to 150mb, but make sure you are releasing the non-used ones on the next frame

stuck onyx
#

yeah, thats what i was tryin to do now

#

thanks ill keep tryin

tribal pivot
#

There's GetTemporary to help you with releasing etc

stuck onyx
#

GetTemporary?

tribal pivot
#

GetTemporary

stuck onyx
#

im getiting the texture by setting it as a target on a secondary camera

#

maybe thats a bad practice?

#

and after that i render()

tribal pivot
#

No not really. But determine if you need a single texture that you re-use, or get a new temporary copy that you release.

stuck onyx
#

temporary, thanks thousands, ill check the link

tribal pivot
#

How do you know they are 150mb? With the memory profiler?

stuck onyx
#

yes

#

the texture itself... should not bemore than 4MB

#

I didnt undderstand why that inccreasement

drifting galleon
stuck onyx
#

but then i've read about the renderview memory allocations

#

4k ?

#

why you assume is 4k?

tribal pivot
#

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

drifting galleon
tribal pivot
#

gege

stuck onyx
#

oh

#

well ill have to check that again 1 sec

stuck onyx
#

RenderTextureSat

tribal pivot
#

That is quite chunky

stuck onyx
#

well i will try what you suggested

drifting galleon
#

i'm not quite sure on that with a depth of 24, but it does sound somewhat extreme

stuck onyx
#

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

drifting galleon
#

but.....you still have to render the objects?

stuck onyx
#

but has this problem right now

#

no

#

just the texture

tribal pivot
#

Whats on the texture?

stuck onyx
#

a picture of all the map with the buildings

drifting galleon
#

how do you show a texture with all the objects if you don't render the objects in the first place???

stuck onyx
#

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

livid kraken
#

What is thw render texture format we can do some math to figure out if the size is realistic

stuck onyx
#

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

livid kraken
#

wait so you created a RT in the project and then you new it in code or ?

agile yoke
#

So, the 128MB of that texture is exactly 4096*4096 * 8 bytes/pixel

#

With that R8G8B8A8 format + depth buffer, that does sound about right

stuck onyx
#

new it?

#

create it again ?

drifting galleon
#

do you even need a depth on that texture? (i'm no expert either, but i don't think you need depth)

stuck onyx
#

I see, so the problem is the quality

#

okay

#

any other settinngs you think are unnecessary ?

#

like the R8G8xxx format

drifting galleon
#

maybe, but i have no idea there either. anything else is pretty irrelevant. although, you may want to change to point filter

stuck onyx
stuck onyx
#

thanks a lot everyone for your suggestions 🙏

regal olive
#

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

drifting galleon
barren scroll
# regal olive

try adding System.Linq then add .ToList() after defining updatable

regal olive
regal olive
#

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

woeful cosmos
tribal pivot
drifting galleon
tribal pivot
#

I dont understand what you are saying, rotations and scale are also whole numbers

drifting galleon
#

XD

regal olive
#

i didn't want to have to scale down every gameobject

drifting galleon
#

scale them up

regal olive
#

yeah xD

drifting galleon
regal olive
#

they are the same size it's just not one unit

#

if it was possible it would be easier to access each cell position

drifting galleon
#

just scale them down then

regal olive
#

I guess this solves my problem

drifting galleon
stuck onyx
#

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?

sly grove
stuck onyx
#

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

sly grove
stuck onyx
#

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

sly grove
#

If you use sharedMaterial you don't need it but it will affect the shared material

green river
#

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

green river
#

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

vagrant magnet
#

@drifting galleon

urban warren
weary stag
#

@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?

stuck onyx
#

Could you take a fast look to my script for rendering on a material what the satCamera renders?

#

Im having memory leaks

weary stag
#

are you disposing any disposable objects?

stuck onyx
#

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

weary stag
#

usually memory leaks happen when you don't dispose stuff correctly.

stuck onyx
#

well I think so

#

i destroy the textures in use... the material i set the texture too.....

#

whatelse could i be missing?

weary stag
#

when you do this, do you override or edit the material?

stuck onyx
#

SetTexture should edit the material as far as i know no?

weary stag
#

do a memory analysis of the project.

#

using dotMemory or something.

#

it will show what's being allocated.

stuck onyx
#

dotMemory?

weary stag
#

You can use other memory debuggers but I prefer this.

stuck onyx
#

JetBrains ❤️

weary stag
#

Anyone aware of how to use the .NET 7 NativeAOT compiler?

#

I can't really find any docs about using it to compile libraries.

hollow veldt
#

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

sly grove
magic acorn
#

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?

lapis arch
#

uhm guys, is this normal?

urban warren
# magic acorn Any ideas on the best way to have permanent blood spatter? (3D) So the most obvi...

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.

magic acorn
urban warren
magic acorn
urban warren
#

They are not tied to any object

magic acorn
# sly grove how permanent is permanent?

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

urban warren
sly grove
magic acorn
#

exiting a level in any way will remove it

sly grove
#

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

magic acorn
#

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)

sly grove
magic acorn
#

splatoon just looks like texture painting so far

sly grove
#

yep

magic acorn
#

alright thanks @sly grove @urban warren I'll have a look at this stuff and figure something out

hollow garden
# stuck onyx https://pastebin.com/KL4j7mzS

.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

stuck onyx
#

DESPERATE mode

hollow garden
#

try caching the meshRenderer.material to some variable and just use that, and then destroy that?

magic acorn
#

is there a reason you can't use .sharedMaterial?

hollow garden
#

yeah you should probably just use that if you can

#

or Material Property Blocks

magic acorn
#

both

maiden turtle
#

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

zenith ginkgo
#

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?

hollow garden
#

if you're just doing a distance check you could check (a - b).sqrMagnitude < threshold * threshold

#

that way you don't have the sqrt

stuck onyx
#

does shared material gets deallocated?

maiden turtle
#

distance is just the sqiare root of the difference between the points

zenith ginkgo
#

But its expenive

zenith ginkgo
hollow garden
#

the length of the vector

maiden turtle
#
  1. it's not
  2. 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

zenith ginkgo
#

and essentially gives the same result?

hollow garden
#

yes

#

it's essentially the same as Vector3.Distance(a, b) < threshold but without the sqrt

maiden turtle
#

so I think it always exists

stuck onyx
#

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,

maiden turtle
#

if the texture is not an assetreference (not dynamically loaded) it's going to stay in memory as long as it's referenced anywhere

silver schooner
#

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.

maiden turtle
#

I'm pretty sure

copper nexus
#

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?

maiden turtle
copper nexus
#

like MC world. where you has many cubes

maiden turtle
#

yeah, you can just write vertex data to a new mesh

copper nexus
#

so i has mesh of cube. but how i can copy/paste it and combine for optimisation?

maiden turtle
#

this too

copper nexus
#

will it works like this

#

combined & optimized

#

so i wanna get second one after generation done

maiden turtle
#

there's no built-in way of doing that, I'm pretty sure

sly grove
#

Yeah you'll have to write that yourself.

copper nexus
#

crap

maiden turtle
#

there are algorithms tho

sly grove
#

if it's just a one dimensional line of cubes shouldn't be that hard

sly grove
#

if it's arbitrary voxels, I wish you luck

maiden turtle
#

I saw some papers being referenced on an efficient algo for this

copper nexus
#

and not only cubes

#

any ready free code ?

maiden turtle
#

google it

copper nexus
#

bc its much complicated to create it from scratch

maiden turtle
#

I don't have links

copper nexus
#

how to name what i want correctly?

maiden turtle
#

voxel mesh optimization

#

or something like taht

silver schooner
silver schooner
# maiden turtle 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.```
honest hull
#

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

tribal pivot
honest hull
#

fair enough

undone coral
#

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

silver schooner
# undone coral what is your creative objective?

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.

undone coral
#

average color of a video feed
what do you mean, video feed?

silver schooner
#

A Unity video player, outputting to a rendertexture.

#

See that quad?

undone coral
#

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?

silver schooner
#

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.

undone coral
#

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

silver schooner
undone coral
tribal pivot
undone coral
#

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?

silver schooner
#

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.

undone coral
#

alright

#

i guess i've helped you as much as i could

silver schooner
#

The quad itself is being calculated correctly from the video feed.

undone coral
silver schooner
tribal pivot
#

It doesnt sample from whatever mip you put in

silver schooner
#

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.

tribal pivot
#

For that you want tex2dlod:

                float4 col = tex2Dlod(_MainTex, float4(0.5, 0.5, _mip, 0));
silver schooner
#

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.

silver schooner
honest hull
#

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?

hushed fable
honest hull
#

I just put them into an array

hushed fable
#

Do you have 7 gigs worth of textures in that array?

silver schooner
honest hull
silver schooner
#

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.

hushed fable
#

If you are no longer using the texture (and no other automatic destruction applies), you Destroy() them.

honest hull
#

ok
so call and destroy each instance of the array then

hushed fable
#

Once you aren't using them anymore, yes

honest hull
#

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

hushed fable
#

It shouldn't destroy assets if you don't pass in true to the method

honest hull
#

"Destroying assets is not permitted to avoid data loss.
If you really want to remove an asset use DestroyImmediate (theObject, true);"

honest hull
#

They are all native objects?

grim oxide
#

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

kind sigil
#

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...

silver schooner
#

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.

undone coral
#

use scriptable objects as immutable data only

#

if you want to compose behaviors, use a prefab

grim oxide
#

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

undone coral
grim oxide
#

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"

undone coral
#

but then, you might as well use the prefab

grim oxide
#

Items are rarely gameobjects though

undone coral
#

yes, but does it matter

#

does it hurt that much to pay the price of 1 Transform component?

grim oxide
#

You tell me 😛

#

That was the question

undone coral
#

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

grim oxide
#

🤔 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

undone coral
#

no

#

game objects are not heavy

grim oxide
#

Extending the scriptableobjects definitely felt strange

undone coral
#

yes slap them on prefabs

grim oxide
#

Extending a secondary one I mean

undone coral
#

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

grim oxide
#

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

undone coral
#

yeah but it's redundant to have a scriptableobject reference a prefab

grim oxide
#

Most items are just some basic numbers and strings

undone coral
#

you might as well just use the prefab

grim oxide
#

It's not because a tiny portion of items will have to do so

undone coral
#

the prefab can have a weapon component that references the scriptable object

#

that generally makes more sense to me

grim oxide
#

99% of items will not need any behavior at all

undone coral
#

i see

grim oxide
#

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

regal olive
#

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

honest hull
#

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)?

honest hull
#

OHHHh thank you!!!

silver schooner
# silver schooner The top one is the render texture. The bottom is the 1x1 Texture2D which is samp...

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.

potent hinge
#

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'

silver schooner
#

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?

honest hull
sly grove
honest hull
#

ohhh so I need the scene name, Icant just do Scene.GetRootGameObjects

#

how do I automatically get the scene name then?

sly grove
#

not the scene name

#

the Scene

#

this perhaps?

honest hull
#

ohhhh thanks! illtr y

potent hinge
#

then a list

silver schooner
# potent hinge what would be another way to do it?

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.

hushed plume
#

Is there a way to access a lights shadow map as a texture?

potent hinge
silver schooner
#

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. 🙂

potent hinge
#

xD

silver schooner
#

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.

potent hinge
#

I just did what you said i just added individual script and it works fine

#

its all random

copper nexus
#

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)

sturdy comet
#

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?

copper nexus
#

When you say "near" its collider (triger)

long ivy
#

dot product would work too (cam viewing dir * dir to target)

undone coral
wary swift
#

yeah, i personally like the dot product approach way more
it's a much smoother experience than the raycast approach

kindred tusk
#

How can I enable C#8 in unity 2021.3.2?

drifting galleon
kindred tusk
#

Ah, I see. I guess it doesn't support the body-less using statement?

#

I thought that was an 8 feature

kindred tusk
#

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?

drifting galleon
#

get rid of the outher brackets

kindred tusk
#

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

drifting galleon
#

correct

drifting galleon
kindred tusk
#

You can't

drifting galleon
#

oh well

#

makes sense

kindred tusk
stuck onyx
#

is there any reason i cant find this built-in shader by code using Shader.Find("UI/Unlit/Detail")

#

?

rocky mica
#

Is the shader included on build

stuck onyx
#

its built-in, so i guess so, no?

#

how do i know this?

rocky mica
#

oh sorry i thought it was a custom one, it should be included yeah

quartz stratus
#

even built-in shaders can be removed in build if nothing is referencing

austere jewel
#

It isn't unless you're explicitly using it

stuck onyx
#

ooh, ok

austere jewel
#

You can reference it explicitly in Project Settings / Graphics / Always Included Shaders

stuck onyx
#

oh thanks a lot!

drowsy moat
#
[ 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.

austere jewel
#

The documentation for the method has a boolean that they set on start, so I would do that.

drowsy moat
#

@austere jewel That wasn't for me, was it?

austere jewel
drowsy moat
#

ah I see. Thanks!

ruby jacinth
#

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?

fresh salmon
# ruby jacinth Hey guys, I need some design help. I have these scripts for each GameObject type...

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)

mortal sleet
#

How i can create collision between cloth with mesh collider object ?. In documentation cloth only work for sphere and capsule collider.

ruby jacinth
#

Am I just overthinking this? Maybe there is a much easier way to achieve the same result?

fresh salmon
#

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.

ruby jacinth
#

Hmm, I don't really know if this would scale well

plucky laurel
#

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

honest grotto
#

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)

plucky laurel
#

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

honest grotto
#

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)

plucky laurel
#

probably because they arent gpu instanced

honest grotto
#

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

plucky laurel
#

yeah its the only native way you can do it without coding or plugins

honest grotto
#

So if it's the only point, i have the gpu instanced active on my enemy material :/

somber tendon
#

first thing to do is to profile it, see what is causing the drop, script/logic or rendering?

honest grotto
#

Let me take a screenshot

plucky laurel
#

you are overthinking it, as i said 300 to 140 is nothing

honest grotto
#

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 😄

plucky laurel
#

before you proceed - clear profiler and close it, switch unity to release mode, and show fps in release mode

honest grotto
#

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)
plucky laurel
#

dont forget to maximize game view when you are measuring anything

honest grotto
sage radish
honest grotto
#

For turning unity to release mode i just need to change the code optimization on startup right ?

plucky laurel
#

bottom right there a bug button

honest grotto
#

Oh yes so i'm in release mode 😄

honest grotto
plucky laurel
#

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

plucky laurel
sage radish
honest grotto
#

//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

sage radish
#

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.

somber tendon
honest grotto
# somber tendon 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)

honest grotto
sage radish
#

You should use the Frame Debugger to see how well it's managing to batch

drifting galleon
#

and you should not enable gpu instancing on any srp batcher compatible material

honest grotto
honest grotto
drifting galleon
#

you should gain a lot of performance if you disable it

sage radish
#

Are you testing with a sphere mesh for enemies like you said before?

sage radish
#

Are you eventually going to replace those with animated skinned meshes?

honest grotto
#

This is my framedebugger when i have a drop and low fps

honest grotto
#

Actually if i put my mesh what my scene look like is :

sage radish
stuck onyx
#

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

hazy hearth
#

Is this a bad performance?

stuck onyx
#

if that's the PONG yes it is

#

unless thats a 386

hazy hearth
#

pong?

#

ohhh

#

thats the game

stuck onyx
#

are you running on editor?

#

i like the character

hazy hearth
#

What exactly does running on editor means?

#

You mean if I run it inside Unity? and not build?

stuck onyx
#

is the profiler conneccted to the unity player or to your phone / app

hazy hearth
#

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

stuck onyx
#

i think it doesnt perform bad but not an expert on profiling

hazy hearth
#

Alrighty 🙂 Thank you

devout hare
#

You're getting consistently 150-200 FPS. Is that bad to you?

stuck onyx
#

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

hazy hearth
stuck onyx
#

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

devout hare
#

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

stuck onyx
#

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

copper nexus
#

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?

fallen veldt
#

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?

hazy hearth
#

It works fine.
But some times the fact that it seems to work fine doesn't mean that there is not room for improvement.

devout hare
#

The profiler can't tell you how well it'll run on another device

fallen veldt
thin mesa
#

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)

mighty latch
#

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

drifting galleon
#

or better: source generator

mighty latch
#

Thanks, exactly what I was looking for!

maiden turtle
undone coral
#

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

copper nexus
#

what is Mesh.Combine() actually doing?

#

will it optimize mesh?

mighty latch
#

It combines multiple meshes into a single one

#

To help make rendering faster

copper nexus
#

or it will be not optimized mesh?

mighty latch
copper nexus
undone coral
undone coral
#

it will not be optimized

copper nexus
#

it will be in one batch call as i know

undone coral
#

Mesh.Combine takes the data from mesh A and concatenates it with mesh B

undone coral
#

the net amount of tris will be mesh A tri count + mesh B tri count

mighty latch
#

You can try that one, or maybe try to find some external libraries that may help with greedy meshing

undone coral
#

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?

copper nexus
undone coral
#

you should use mesh instancing

#

and do not try to mesh-combine

#

just tightly pack your cubes

copper nexus
undone coral
#

make sure the material has GPU instancing checked

#

then you're good to go

#

it will perform better than anything else

copper nexus
#

i wanna get rid of GO

undone coral
#

yes, but why.

#

you will always have many game objects in your unity game

#

that's how unity games work