#archived-code-advanced

1 messages ยท Page 33 of 1

harsh lion
#

It's kind of why the render pipelines were made in the first place

#

I've seen my graphics engineer colleagues doing some crazy stuff with custom RPs in like a couple of days

undone coral
harsh lion
#

That's cool! Runs super smooth

undone coral
#

thank you

#

that scales instantly, there's no VMs ๐Ÿ‘€

#

there's some folks making a big 2 player arcade game - but there's demand for e.g. 10 simultaneous players

#

probably in something immersive, so HDRP quality... the thing is with a ton of players, most of a walking simulator scene is going to be visible by some camera somewhere, and the marginal impact of unculled geometry is small

#

it looks like the single pass stereo rendering is a pretty invasive thing though

harsh lion
#

Yeah there is support for it but it looks like your application needs a lot more flexibility

#

...and there are performance/complexity costs associated with just adding on top of something like HDRP

undone coral
harsh lion
#

I think as we go along we'll make things easier for projects like this. Render Pipelines are still growing

undone coral
jovial totem
#

I still don't quite understand how to talk to render passes from monobehaviours?

harsh lion
#

You can call other functions from the Custom Pass to pass data to your other C# scripts

jovial totem
#

oh, like setting a static member?

undone coral
#

you can get the list of lights from the context

#

it is in the culling results

#

if you need to "add data", add a component next to the object whose culling you want to reproduce

jovial totem
#

yes I am reading up on that, but I'm not sure

  1. how to make a render pass for URP (is it different from a render feature?)
  2. Making it interface with a script so I can get a list of lights in the scene

My goal is to get a list of lights in the scene, so that I can raytrace against them to figure out a rough approximation of the light level at a given point in space. using FindObjectsOfType<Light>() every frame could get really expensive quite quickly

undone coral
undone coral
#

i'm not sure if URP supports custom culling, it probably does.

using FindObjectsOfType<Light>() every frame could get really expensive quite quickly
there are many ways to skin this cat. render features, like custom passes, i believe support a little data you can ship around. you are overthinking this though. you can always add a component to a light that adds it to a set on enable, and removes it on disable

#

i don't think findobjectsoftype is especially slow, and you should try to get things to work first before optimizing it away

jovial totem
#

I see the method Execute() which has a proper context...

harsh lion
#

Yes Execute is the right place to fetch the context

#

(Sorry I'm in-and-out of channels and I missed a few things, thanks @undone coral)

jovial totem
#

okay, i got it working. Thanks!

half trout
#

wow

misty glade
#

Not sure if this is the best place for this question, but.. it's a start.

A few of you know I've got this turn based game going on (gameplay attached). Overall things are working pretty good but sometimes debugging is a bit of a pain in the butt. I'd like to build a system for visualizing the game state and don't know where to start.

The game is essentially a state game with a series of actions that modify the state. I'm currently sending the entire state back and forth from the clients to the server (to compare the client version against the server version) to proactively find desync bugs. Now that that class of bug is gone (hopefully), the harder bugs are the "things don't appear to be working" bugs, which are hard to find because.. well, 65 unique abilities interact in sometimes-surprising ways. The codebase is pretty clean, but it's large. The server side processing of an special ability is around 3200 lines of pretty-dense code by itself.

There are 32 distinct state modifying messages, and the "battle" state is an object graph that's.. fairly big. My efforts at making some readable string "summaries" (shown in Seq) are useful but .. still not super easy to mentally parse.

I'd love to be able to have some sort of .. web based interface that I could, I dunno, plug into my data, navigate forward and backward from turn to turn (and action-to-action within a turn) while viewing the state or maybe changes to state in some sort of side panel.

Any ideas for a tech stack for something like this? Ideally path of least resistance - this obviously isn't AAA tooling but.. I need something a bit better/faster for debugging since the interactions are getting wild.

jolly token
#

Maybe something like that is enough for your use case? Though with Unity I think you could make debug mode of your client

misty glade
#

In debug mode it's about 1kb compressed - but .. obviously it's too noisy for production

jolly token
#

Oh well I meant.. 'visual' console application.. It looked like console tetris ๐Ÿ˜„

misty glade
#

Oh, ha, sorry, I misunderstood

#

I wonder if a standalone unity app is the way to go, actually.. It might be a fair bit of work to carve out just the rendering stuff.. but theoretically I could just replay the server messages to the client, store them in an array and just forward/rewind to the correct turn

#

(and create a JSON "save" file that has the entire state from turn to turn.. it'd be large but for debugging purposes maybe that's fine)

jolly token
#

I represented characters in battle as text rectangles and printed hp, mp etc alongside with them.. basically a console client, and I also used it to replay user's battle data, etc. So it was overall pretty handy

#

But yeah Unity integrated version maybe better (especially if non programmers also need to use), with more effort

misty glade
#

For now it's just me that's debugging... but... I almost wonder if there's any market value in a battle replayer app thingy

#

maybe even integrated in the app, i dunno

#

Might be a shitton of work and ... create it's own bug surface ... but I'm sure it's one of those features I shouldn't tell the designer about because they'll be like "fuck yeah, put it in"

#

๐Ÿ™‚

jolly token
#

Yeah don't tell them until you are ready .. lol
It'd be easier if client can use same data model for gameplay mode and replay mode
I wouldn't really recommend using web for this.. that is more effort and more maintenance ๐Ÿ˜Œ

misty glade
#

Yeah, I think you're right. I mean, if I'm building a "replay mode" from the ground up.. it may as well be embedded in the client in case it's useful or more polished in the future for social gameplay stuff. Technically the infrastructure is all there already, too - I just .. make a non-interactive battle and have it talk to a "fake server" (ie, the json file that unspools the actions)

#

Now the question is should I make the save file {start}->{action}->{action}->{action}->{action} or {start}->{action}->{new state}->{action}->{new state}->{action}->{new state}->{action}->{new state}

jolly token
#

Hmmmm my preference is just having deltas
Latter can be easier to make rewind - but client also can calculate states from deltas ig

#

Because states could be pretty big to store ..

#

Problem with deltas/inputs is replay may not accurate anymore if balance data changed or skill changed etc

west warren
#

heeyyy am back from being 3 eons dead, ehhh quick question, is it posible to make a "piracy screen"?
like to detect where has the game been downloaded from?

misty glade
#

Not easily? arms race, etc.

You could embed a configuration file or some other tag (perhaps a library that literally has a static const string) but as soon as someone figures out what's in it, they can change it.

You could make a login framework where the deviceID is sent to a central server to ask for permission to play, but... that's got it's own problems.. faked DeviceIDs, your central server going down, etc.

west warren
#

is there any easier way to do it?

#

like a pass code or something

#

maybe if i make it able to detect if steam is running (or something idk) i could make it run the game just fine, but make it start on a scene with all the thing needed for the "piracy screen"

misty glade
#

not sure really what you mean by a "piracy screen" but ... your executable doesn't magically know where it's been downloaded from unless you embed something in that download, for that site - which obviously ... has no way of knowing if it's right or not, it's just a file.. downloading/uploading it to however many sites you are worried about doesn't change that file in any way

#

If you want to protect your work - you'll need to establish some sort of DRM which.. again, is a bit of an arms race.. short of making your game multiplayer-only, its' not trivial

#

Probably not worth worrying about TBH.. You'll know when it is. ๐Ÿ™‚

shy willow
#

Hey all, anyone know of a method for changing the code of and recompiling shaders at runtime? I understand it can't be done using HLSL, but it seems this guy managed to do it with GLSL shaders. http://kylehalladay.com/blog/tutorial/bestof/2014/01/12/Runtime-Shader-Compilation-Unity.html I checked around, and it seems other people have attempted his method in more recent years, and it no longer works. Anyone know of any solutions that work with modern editions of Unity?

astral vale
#

Not sure if this is advanced or not. But I'm creating an app that allows players to import 3D files in runtime to the game to create a map to play around online. My question would be, when saving the created map, Is there any way to encrypt these 3D files?

harsh lion
#

Not in Unity (that I know of) but you can probably find some open source dll in C# that can do that. You would just have to compile it into the unity application and make sure you have the rights to distribute it.

real blaze
#

hey. is there any way here to fill the if statement?

if ( /* inside default physics scene? */ ) {
    Physics2D.Raycast(  )
}
else {
    gameObject.scene.GetPhysicsScene2D().Raycast(  )
}```
real blaze
upbeat path
#
PhysicsScene2D myscene=null;
try {
myscene = GetGetPhysicsScene2D(scene);
} catch { }
if (myscene == null)
austere jewel
#

PhysicsScene2D is a struct

#

and also, does it actually throw if t's not in the default physics scene? That code looks like it just throws if it's invalid

upbeat path
#

then use PhysicsScene2D?

real blaze
cerulean scaffold
#

I ll have another look tomorrow

real blaze
#

ok so apparently I'm dumb and it doesn't throw on default PhysicsScene

#

issue closed for good. โœ…

iron pagoda
#

I'm having trouble with reading EXR Texture2D files with a NativeArray.
I have an editor script tool which has functional support for TGA, JPG and PNG.
It can also convert those files into EXR format, but I cannot read any EXR file properly.

I can't seem to get these examples to work.
https://docs.unity3d.com/ScriptReference/ImageConversion.EncodeNativeArrayToEXR.html
https://answers.unity.com/questions/1817392/why-is-nativearray-always-shorter-than-the-number.html

Here is the method: https://gdl.space/ijosipiyuv.cs
Here is the git: https://github.com/yTreeOfLife/Editor-Sprite-Extractor
This is the current output.

runic girder
#

Hello guys, applied to Unity Dev application. They gave me a test task to create a prototype of the game for 3 days. Completed and sent it after 2 days, and even made MUCH more than they asked. I really worked on that, made everything smooth and stuff.

As the result, I got rejected. They just claimed that the game mechanic is badly implemented and look bad, without even mentioning code skills... I wrote really good and solid code. It runs smooth on mobiles. Whole task turned out to be very easy for me, but I failed.

So I am asking some code experts here, did I actually wrote bad code and the game overall?

Github repository: https://github.com/d1msk1y/Pizza-Delivery/tree/main/Assets/Scripts

#

The task doc:

#

I would really appreciate your thoughts about it, cause I am really confused...

runic girder
#

shit

#

try it now

onyx blade
#

404

runic girder
#

now should work

onyx blade
#

its not a visible repo on your account either

runic girder
#

oh no

#

wait

#

yup, now should work

onyx blade
#

yup, works

runic girder
#

I cant see what they didn't like...

onyx blade
#

Was this a big company?

runic girder
#

no

onyx blade
#

it wasnt was it?

runic girder
#

they don't even have a website

#

smol

onyx blade
#

how realistic is the chance they used you as free labor?

#

I don't see anything glaringly wrong

runic girder
#

oh

#

wait, that does make sense

#

NO WAY

#

they're ignoring me btw

runic girder
onyx blade
#

im not saying it is the case, im only suggesting that its possible

runic girder
#

it's just so weird

#

I am really not able to see any way how could I improve the game.

#

gotta ask reddit ig

finite sun
#

Hi guys, I'm looking for a way to inflate a mesh like a balloon, any suggestion where I can start to dig?

#

(I mean in runtime, by dealing with vertices modifications)

runic girder
onyx blade
#

2022 Company

#

their website is filled with placeholder images and lorem ipsum text

runic girder
#

yeah, I see

onyx blade
#

Oh god what is that website

runic girder
#

they don't even have their "Career" page working

#

Do you think this company is legit?

onyx blade
#

I personally don't think they are

#

judging by the mistakes and general negligence on their website I have questions

runic girder
onyx blade
#

I could definitly be wrong tho

#

but from what I am seeing, I dont feel confident they are a well-established company

runic girder
#

I can't actually find any of their games

#

even tho it says "Available on google play"

#

I just wanna know if this is my skill issue or a scam

onyx blade
#

The type of game requested is kinda hard to judge on code quality ngl

#

You worked pretty oganized and I can make sense of it

#

but then again im also used to my own messy code so may not be the best judge

runic girder
#

thanks for the nice words:)

obsidian glade
# runic girder I just wanna know if this is my skill issue or a scam

it seems like your game doesn't quite match the brief of delivering pizza to a customer, nor do the controls match the description of turning right (think pedalling a bike, rotating the joystick clockwise - though this is very ambiguous)

I wouldn't take it as a personal fault though - the task description isn't ideal and you've got a good prototype that I think any decent company would at least want to call you back to discuss. Would write it off as incompetence on their end, or possibly even a scam as suggested, but either way you're doing fine - just keep looking for another position

fringe hedge
#

hey
I just implemented chunks into my game
But now all of the code that finds tiles' neighbors is broken
(sending more context...)

runic girder
fringe hedge
#

I have no idea what could even cause that cause the systems aren't even related

#

I could share code but it would require context of, practically the entire project

#

and I can't debug in VS cause the thing skips all the code instead of executing it

#

and there's no reason in the world this will be like this

#

it worked

#

that's it I give up it's impossible to even debug using unity

#

I can't know what is related to what

#

nothing

#

it takes years just to add a "println" statement

#

and when debugging it just skips code randomly so I can't know if something is a bug w/ my code or w/ the debugger

wooden cedar
#

The important thing is that you tried your best

fringe hedge
#

and the icons

#

and everything

undone coral
crystal parrot
#

Is it possible to get smooth transition between opposite directions in unity blendtree?

undone coral
#

when an ability is executing, does the call stack of the code implementing the ability resemble the call stack of what is logically happening in the game?

crystal parrot
#

for 8way movement

wooden cedar
# runic girder Hello guys, applied to Unity Dev application. They gave me a test task to create...

At my company, we pay people for their coding tests. And as a company, if we don't accept someone, we don't go into the specifics of why, we simply thank them for their time.

There are a lot of questionable practices in the industry unfortunately. And yes I've seen another VR studio in Toronto use people's free code submissions as products on the front of their website claiming deals with companies like Disney when it's just a fabricated code sample from a job applicant.

Always be vigilant and look for companies you want to work at.

runic girder
#

Nobody even invites me for an interview

shy willow
undone coral
shy willow
#

there's really no way about it, i can't do something like that with simple variables

undone coral
#

what is the application?

shy willow
#

rendering fractals

undone coral
#

you mean rendering 3d fractals?

shy willow
#

nah, just 2D for now

undone coral
#

gotchya

#

and the user does what? authors the equation?

shy willow
#

yep

#

there's not really a method I can think of that doesn't involve editing the shader at runtime

undone coral
#

hmm

#

is the idea that the user can keep zooming in infinitely and it Just Works?

shy willow
#

well, yes, i would like it to be real-time

undone coral
#

but the infinite zoom

#

that's different

shy willow
#

it's fully functional atm, but i need to go into the shader file and manually edit the equation to change it

undone coral
#

is that the goal?

shy willow
#

well not infinite

undone coral
#

like it doesn't get blocky like these other things online?

#

okay

shy willow
#

yk there are limitations because its a computer lol

undone coral
#

and whom or what is this for?

shy willow
#

for me, for fun. some friends have been showing interest in it too, and also i'd like to show it to colleges i'm applying to

undone coral
#

okay

#

is there anything else you want to do besides render the fractals?

#

so you have some UI to do this, great

#

which makes sense

#

anything else?

#

if not, you should probably do this in html5 & webgl, because that environment supports modifying shaders at runtime, and there are examples of this fractal generation in github

shy willow
#

well you can take pictures of them too, and i'd really just like to use unity for this because i've already made everything else in the program, and i'm sure i'll find myself wanting to modify shader code at runtime again in the future

#

also i kinda dont have time to learn to write webapps, im literally taking 4 AP classes๐Ÿ’€

undone coral
#

hmm okay well

#

i want you to thrive so this is really hard to do

#

you can hack it together

#

i can help you get to where you want to go right now, or you can listen to my advice for what would better fulfill your goals

#

which would you prefer @shy willow ?

shy willow
#

if "where you want to go right now" means editing shader code at runtime, yeah i'd appreciate that bc that's what my question was originally about

shy willow
shy willow
#

cool, thanks mate

undone coral
#

my only feedback to you is that between the two choices, choosing the first one was the wrong one

#

it happens

shy willow
#

man can you not๐Ÿ’€

#

thank you for your help but i really don't appreciate you saying that lol, i enjoy learning how to use unity, especially if i get to push its boundaries like this

#

and i don't care if it's going to be hard, cuz who knows? maybe i'll use it again in the future. and regardless i'm gonna have fun doing this, that's why im a hobbyist, cuz i enjoy it

undone coral
#

it was a good idea to ask and i think you'll figure everything out, it'll be great

misty glade
# undone coral > Any ideas for a tech stack for something like this? Ideally path of least resi...

I don't but.. I don't think unit tests is going to cover what I'm looking for, which is more .. the hard stuff. Frankly, I'm not even sure if I'm on the unit test or TDD bandwagon yet. I've never actually implemented a complete X% code coverage testing framework but... I dunno, maybe my game is perfect for it, maybe not.

My approach currently is piecewise comparing the complete state across all users (each client sends in their state - 1kb compress - after each turn and the server compares and notifies if there's desyncs).. but when a user says "oh hey, this ability is supposed to do X and is doing Y" - it's really tedious to step through the game to see what happened. Literally using pen and paper to recreate the visual state from JSON "before turn" state, and replaying the server actions one by one and seeing what output is broken - before I even look at the code.

๐Ÿคท

meager kite
#

Hey im trying to randomly distribute resources among several outposts. I have an int which stores the total amount of resources, and a list of the outposts. My current algorithm works as intended, but is insanely slow. How could i refractor it to speed up the process?

https://hastebin.com/udofahidim.php

#

amountOfResourcesTotal is anywhere from 1 to 170

#

I initialize the resource types earlier, but simply distribute it in this loop

misty glade
#

paste code for calculateTotalResourceProbabilityIndex()

meager kite
#

and it takes forever

#
    float calculateTotalResourceProbabilityIndex()
    {
        float toReturn = 0;
        for (int i = 0; i < resourceRegistry.Count; i++)
        {
            toReturn += resourceRegistry[i].rarity;
        }
        return toReturn;
    }```
#

the registry is 3 items

#

so its really quick

#

its this part here that I think is causing the most strain

            for(int i = 0; i < system.outpostsInSystem.Count; i++)
            {
                if(system.outpostsInSystem[i].resourceAtOutpost == resourceToUse)
                {
                    int coinFlip = Random.Range(0, 2);
                    if(coinFlip == 1)
                    {
                        system.outpostsInSystem[i].amountAtOutpost++;
                        amountOfResourcesTotal--;
                    }
                }
            }```
misty glade
#

Is resourceRegistry a POCO or monobehaviour? ie - you don't have any special logic on the get for .rarity?

meager kite
#

the rarity is just a standard float - resourceRegistry is a list of scriptable objects

#

no special gets or sets

misty glade
#

oh

#

that's your problem ๐Ÿ˜›

#

well

#

nevermind, that's maybe OK - but you shouldn't be doing Random.Range (which returns a float) and then casting it to an int and then checking that int for equality to 1.. it works, but ... it's kind of working because of 2 or 3 "wrong" ways of doing it canceling out ๐Ÿ™‚

meager kite
#

calling it with ints returns an int

misty glade
#

Oh, nevermind, there's an (int, int) override

#

Ok, back up then - what's system?

#

And what's outpostsInSystem? A list? array?

meager kite
#

so each of the outposts is related to a central "system" class

meager kite
#
public class StarSystem : MonoBehaviour
{

    public List<ResourceOutpost> outpostsInSystem = new List<ResourceOutpost>();
    public List<GameObject> satelitesInSystem = new List<GameObject>();
    public List<Planet> planetsInSystem = new List<Planet>();
    public GameObject centralStar;
}```
#

a system is just a container

misty glade
#

This could be a lot easier to read using LINQ.. but lemme see if I can find the problem, I haven't so far

#

you could also use my weighted list library to make drawing the random part O(1)

meager kite
#

huh could you send it?

#

sounds useful

misty glade
#

I suspect that you might have a rounding/casting error in your for loop in lines 16-26 that's causing one of the rarities or the sum of the rarities to be close to the total

meager kite
#

no that part happens almost instantly

#

its the loop after

#

where the resources are distributed

#

that takes forever

#
            for(int i = 0; i < system.outpostsInSystem.Count; i++)
            {
                if(system.outpostsInSystem[i].resourceAtOutpost == resourceToUse)
                {
                    int coinFlip = Random.Range(0, 2);
                    if(coinFlip == 1)
                    {
                        system.outpostsInSystem[i].amountAtOutpost++;
                        amountOfResourcesTotal--;
                    }
                }
            }```
#

looking at it again it has a ton of calls

misty glade
#

amount of resources total is like 170, you said?

meager kite
#

yeah

misty glade
#

line 19 is a clusterF

meager kite
#

so 170*outpostsinsystem

meager kite
meager kite
misty glade
#

i see but.. it's super hard to read, standby though i'm still trying to just understand what you're doing

#

i mean you're also doing a ton of awful stuff - you have a while loop with 3 for loops in it, you're declaring a huge number of things inside it, etc

#

can you paste the debug log from a run?

#

Lemme try to refactor this actually, maybe the solution will be obvious once I've gotten into it

meager kite
#

how can i send the whole thing?

#

it just repeats mostly

misty glade
#

yeah that's why..

#

lemme guess

#

tons of !!! lines

meager kite
#

yep

#

its this over and over again

misty glade
#

amount of resources is an int?

meager kite
#

yep

misty glade
#

lemme refactor this, there's nothing "wrong" with your code, no single line that's doing anything wrong, but you've made this severely italian

meager kite
#

thanks, id appreciate it

misty glade
#

what are your first few lines doing? putting 1 resource at every outpost..? but only if it has 0?

#

guaranteeing each outpost gets at least 1 resource?

meager kite
#

yeah

#

i randomly assign outposts to satelites, and each outpost must have at least 1 resource

misty glade
#

here's how you do this in a way that makes more sense imho:

            foreach (ResourceOutpost outpost in system.outpostsInSystem.Where(x => x.amountAtOutpost == 0))
            {
                outpost.amountAtOutpost++;
                amountOfResourcesTotal--;
            }
#

(and you do that outside of the loop instead of every single time you iterate through the while loop)

meager kite
#

isnt that the exact same thing, but simply outside the while loop

misty glade
#

yes, and that's partially the point

#
while (something)
{
 for (something)
}

is almost guaranteed to be bad

#

especially if the for loop literally only does anything the first time through the while loop

#

you're also recalculating the "resourceprobabilityindex" every time through the loop - does it change?

#

i'm refactoring your code using my weighted list to give you a head start on it. ๐Ÿ™‚

misty glade
#

outposts only have one type of resource?

undone coral
# misty glade I don't but.. I don't think unit tests is going to cover what I'm looking for, w...

hard to pin down exactly what kind of test this is - https://github.com/hiddenswitch/Spellsource/blob/master/spellsource-cards-git/src/test/java/com/hiddenswitch/spellsource/tests/cards/RingmasterTests.java - more of an integration test than a unit test, since it covers the real content the player interacts with, but not via the UI.

the server saves every match's trace along with its version, and i use these to reproduce game logic errors, testing automatically here - https://github.com/hiddenswitch/Spellsource/blob/master/spellsource-cards-git/src/test/java/com/hiddenswitch/spellsource/tests/cards/TraceTests.java - example traces here - https://github.com/hiddenswitch/Spellsource/tree/master/spellsource-cards-git/src/test/resources/traces

however randomly playing the game for millions of matches finds the most exceptions. you can see an example of a bugfix based on user reports, then reproduced with mass tracing, here - https://github.com/hiddenswitch/Spellsource/commit/eeaf1ebf322dcaf358ad0d1ef24f88bcfe7fb1e9

imo resolving these issues are complex. if i were you, i'd

  1. try to test exclusively headlessly, in a process that embeds your game logic and nothing more.
  2. the trace work stream:
  3. create a trace format that is solely game actions, and check that the game state is identical when the trace is replayed.
  4. create a test that randomly, mass plays games in this embedded environment. use the emitted traces to start tackling Exception and other programming errors
  5. the integration test work stream:
  6. create a test harness that lets you play out the match in code
  7. test greater and greater amounts of the content you authored, trying to increase code coverage this way
misty glade
#

(thx Dr - will review in a sec after helping this guy)

#

@meager kite - Outposts only hold one type of resource?

meager kite
#

yes

#
public class ResourceOutpost : MonoBehaviour
{

    public Resource resourceAtOutpost;
    public int amountAtOutpost;
    public bool isBeingCollected;
}
#

@misty glade

misty glade
#

and have you implemented Resource.operator== and != and Equals and GetHashCode?

#

(or is Resource a struct?)

#

if not, line 35 fails for you

#

oooooooooooh wait, no, it works, but again, for reasons you aren't expecting ๐Ÿ™‚

meager kite
#

neither to both

misty glade
#

(you're simply comparing pointers here, which is not probably what you want to do - your entire app breaks if you reload the registry)

meager kite
#

oh fun

misty glade
#

don't worry about it, i fix

#

voila

#

note that the while loop doesn't have any "fail" cases

#

you can still make this faster by separating the outposts by resource type, but this will perform just fine for your loop size

#

also pay attention to the comparison of resource to use - it compares against an integer Id, not just against the entire object.. which .. depending on if it's a unity monobehaviour or just plain C# class - is not going to behave like you might think. You have to explicitly tell the system how to compare for equality

#

for example, for one of my classes (trimmed for clarity):

#
    public sealed class BattleEffect : IEquatable<BattleEffect>
    {
        public bool Equals(BattleEffect other)
        {
            if (EffectType != other.EffectType) return false; // 0
            if (TurnsRemaining != other.TurnsRemaining) return false; // 1
            ... etc ...
            return true;
        }
        public override bool Equals(object obj)
        {
            if (obj == null) return false;
            return obj is BattleEffect battle && Equals(battle);
        }
        public static bool operator ==(BattleEffect left, BattleEffect right) => left is null || right is null ? Equals(left, right) : left.Equals(right);
        public static bool operator !=(BattleEffect left, BattleEffect right) => !(left == right);
        public override int GetHashCode() => Guid.GetHashCode();
    }
#

all that code, just to make sure that comparison of one item to another works as you expect, because otherwise what you're getting when you say if (a == b) is "is a the exact OBJECT as b" which is different than "is A the same as B"

meager kite
#

thank you!

#

ill implement .equals in my classes now

#

i really appreciate you sitting down and helping me refractor\

jolly token
#

One additional note - GetHashCode should return same value for same (equal) object, you might encounter issue when using hash based collections with your class

misty glade
# undone coral hard to pin down exactly what kind of test this is - https://github.com/hiddensw...

K - this is really good. I'm sort of on the same path, but without the tests. Essentially I have traces (and state), but it's in a format that's readable to humans (along with the corresponding json/objects that I can compare and get some proactive alerting if anything's busted). I was working on bots to test and play matches en masse, but it's not complete yet. The game is relatively simple in terms of the number of distinct actions you can take (5 + emote + resign) so it seems that headless testing in production or dev is the way to go.

#

essentially your assertEquals(turn, turn-1) and diagnose() are pretty close to what I have now - it's just the human diagnosis is hard

#

i compare the entire state (from all actors - server/player1/player2) ...

#

and if there's any issues, log the summary using my own form of diagnose():

#

It's.. just a lot to digest so I was thinking tooling to visually review this would be worth doing

undone coral
#

it is indeed too tedious to look at printed game states

#

i usually write a bespoke diff i am interested in for the particular bug

misty glade
#

Debugger isn't an option for me currently - since the state is too hard to recreate - and I don't have debugging hooks into production

undone coral
#

once you record traces in production, you will be able to reproduce them locally and hopefully that helps in the long run

misty glade
#

I think what would maybe be good investment is being able to export/import these states and traces and replay them in memory

#

Yeah that's what I basically don't have now - any ability to export and import the state

#

I think that would be the next logical step - robust import/export/replay state functionality so I can debug it (using the debugger locally) and then automated testing to locate any exceptions/desync situations

#

Our game has 65 characters and a match is 3v3 so the permutations of abilties is really wide.. I'm a little fearful of the interactions we didn't think of

#

this is my largest area of concern

undone coral
#

overall these seem fine to me

#

and make sense

misty glade
#

Almost no exceptions at this point (it's been 20 days without a crash)

undone coral
#

if you saw my earlier conversation with someone, you successfully did "every function has the same signature"

misty glade
#

yeah, for the most part, although i changed the signature halfway through implementation .. so much work to refactor ๐Ÿ˜ฆ

undone coral
#

i assume somewhere you have Effect(string name, ...) that delegates to these

misty glade
undone coral
#

or if not, it's easy enough to do with reflection

#

yeah

misty glade
#

So, for a while I was routing a lot of that common stuff through a bottleneck function, but it was just... redirecting one line of code and putting a bunch of parameters into a method

#

so it didn't really have an impact on making it more readable

misty glade
#

using the enums here has huge impacts for networking/storage - especially on the drone effects

#

the networking is quite compact - turns are like 5-20 bytes, actions are 2-10 bytes usually

undone coral
#

yeah these make sense to me

#

i think it's all fine

#

so you will have this random mass play and it will be

misty glade
upbeat path
undone coral
#

game stack == c# stack

#

you're in a really good place

undone coral
misty glade
#

horrible in that it's lots of fun and has lots of cool abilities? ๐Ÿ˜›

upbeat path
misty glade
#

i mean, the abilities need to be delegated somewhere

undone coral
#

zero reflection has many benefits

upbeat path
#

yes, in an array which matches the enums

undone coral
#

@misty glade i wouldn't worry too much about human readable traces. i recall i had that at some point, but i interacted with it by authoring good ToStrings on the BattleAction equivalent class and reading it in the debugger

misty glade
#

what, something like:

Dictionary<ActiveAbilityType, Action> lookup;
...
lookup[type].Invoke();

?

upbeat path
#

could be

misty glade
#

to be fair not all of them are identical - some are async, some aren't, some are passive and so do nothing

undone coral
#

yes - the code that sorts that all out, that glue, has to live somewhere

misty glade
#

but I see your point, the delegation could be a bit more automated

undone coral
#

it can live in the form of a class, a switch statement, etc. it can't necessarily be less.

misty glade
#

๐Ÿคท I'm not super worried about that, really.. it's not really a surface for bugs, is just fine for readability (if a little bit long) and isn't too dynamic or active in terms of changes

undone coral
#

yeah

misty glade
#

in general I lean towards making things simple and resistant to bugs over being clever.. when I try to get clever I get bugs

#

I'm not smart enough to be clever

misty glade
#

but it's still super tedious to pick through the JSON

leaden hinge
#

if one was to move the location of the text mesh pro package in an attempt to make changes to it without it being reverted, how would the package behave to getting actual updates?

lyric dragon
#

hmm, maybe I didn't check it well, I will give it another try
Thanks a lot for the help! @undone coral

plush hare
#

So I'm writing a code generator that automatically creates code inside user scripts. I use the beforeAssemblyReload callback to generate the code.

This works fine HOWEVER, the generated code contains references to user-written code. If a user decides to delete some of his code, it creates errors in the generated code. This prevents my code generator from generating new code in order to fix those errors

#

is there a good way of dealing with this?

misty glade
#

beforeAssemblyReload is still raised, isn't it?

plush hare
misty glade
#

weird.

#

I'd probably just make a menu item or .. some other hacky thing to regenerate it.. i don't know what the best solution would be but.. you know, if you're gonna do a hacky thing, well... you use what you have. ๐Ÿ™‚

plush hare
#

that's a shame

misty glade
#

Maybe something that is called in some onvalidate editor methods, checks for file changes, etc

#

Is this specifically for when files are deleted?

plush hare
#

It's whenever the assemblies are reloaded

#

so generally when they get changed is when I want it firing

misty glade
#

I'm just surprised (still) that onBeforeAssemblyReload isn't fired then

#

that's.. exactly what it's for

jolly token
#

If there is compile error then assembly wouldn't reload

plush hare
#

UnityEditor.Compilation.CompilationPipeline.compilationStarted Tried this as well. Doesn't work

#

Pretty strange that unity doesn't have the callback I'm looking for. This engine has been in development for what, like 20 years?

jolly token
plush hare
#

before I go trying it

misty glade
#

I dunno if this is overkill or if you're gonna need to put in some checks of your own to prevent over-compiling when it's not necessary, but you could also just try EditorApplication.projectChanged

jolly token
misty glade
#

my auto code gen happens outside unity so ๐Ÿคท i gen the code, drop it in a unity folder and unity recompiles happily

plush hare
jolly token
#

You might wanna consider rosyln source generator as well

misty glade
#

uh

#

you don't want to use onpost process for this i think

#

Note: If your code causes any new asset imports during this callback, OnPostProcessAllAssets will be called again once those new imports are complete.

#

you're gonna be stuck in a loop i think

jolly token
#

You can always filter whatever you're interested

misty glade
#

i mean, go nuts, but be prepared to ctrl-alt-delete that sucker ๐Ÿ™‚

plush hare
#

Ok heres another issue. When there's an error, the assemblies don't get rebuilt. So it's just reusing the reflection data from the last successful build

#

which is causing it to try to create code with variables that don't exist

untold moth
#

If you're doing code generation, why not just read the .cs files? Reflection is more for running and compiled code.

plush hare
onyx blade
#

How do you remove an event with a signature like this? primaryButton.Q<Button>().clicked += () => Apply(items, right);
cuz the unity button event "clicked" doesnt accept functions with parameters, but I need those...

compact ingot
onyx blade
#

so I need to store it somewhere then ๐Ÿค”

compact ingot
#

just make it a method

onyx blade
#

Apply is a method?

#

im not sure i understand

compact ingot
#
void ApplyWithArgs() => Apply(items, right);
onyx blade
#

ah, its expecting an object of type action

#
            Action click = () => Apply(items, right);
            primaryButton.Q<Button>().clicked += click;
compact ingot
#

same thing

onyx blade
#

it kinda is, but your method wont allow me to set those parameters locally

compact ingot
#

so long as you can reference the delegate from where you call the unsubscribe, you are good

compact ingot
onyx blade
#

ah fair yea

compact ingot
#

in any case if you are creating a closure (capturing local variables) you need to store the delegate in a field anyway to be able to unsubscribe in a different method

onyx blade
#

yeah

#

now I got it

#
private Action currentClick;

private void foo() 
{
    btn.Q<Button>().clicked += () =>
    {
       currentClick = () => Apply(items, right);
    };

primaryButton.Q<Button>("Apply").clicked += currentClick;
}
#

that worked, ty!

onyx blade
#

Does anyone know how I can fix this ```
Checking the license for package Android SDK Build-Tools 30.0.3 in C:\Program Files\Unity\Hub\Editor\2023.1.0a20\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\licenses
License for package Android SDK Build-Tools 30.0.3 accepted.
Preparing "Install Android SDK Build-Tools 30.0.3 (revision: 30.0.3)".
Warning: Failed to read or create install properties file.

#

I have those build tools installed throuugh Android Studio but doesnt start

flint sage
#

Because unity has it's own install of the SDK that doesn't have those (probably)

#

You can give the path of android studio's SDK to unity to make it use that

onyx blade
#

should I have done it the other way round?

flint sage
#

I would yeah

onyx blade
#

hmm, in taht case do you know what the default installation path is?

flint sage
#

Also not sure in general why you need to manually install extras ๐Ÿค”

onyx blade
#

My assumption is that that error is occurring because of my non-admin access to the pc

#

I have had similiar errors in android studio when its not running in admin mode

#

which leads me to believe unity is trying to download and isntall some sort of SDK but fails to get the write permissions to do so

#

but I cant even test that since I cant get admin privileges at all

tall crag
#

I have created a system where if the player looks at an object it does something but as I get far away looking directly at it doesnt matter as the angle gets bigger. Any ideas on how I can fix this?

obsidian glade
#

at a certain distance away the angle might shrink down to 0

tall crag
#

right okay

#

do you think a lerp could work

obsidian glade
#

yeah

tall crag
#

yea i think i got it working, thanks

flint sage
#

I'm guessing you can't make it async because the request will timeout

#

Instead you should send a different RPC when your action is done

regal olive
#

do c# threads work in unity?

flint sage
#

Sure

#

Unity api isn't threadsafe though generally

regal olive
#

because i'm trying to run discord rpc callbacks on separate thread and nothing happens

#

code doesn't use unity api

flint sage
#

Then it should work so the issue is somewhere else

sly grove
proven blaze
#

Hi all, can anyone recommend an approach to send PointerEvents from one canvas into another (completely separate in space/position/rotation and even not under the same camera)? Meaning - on Main canvas - there will be a script to listen on the desired PointerEvents, and another Canvas will receive all of them and properly trigger sliders/buttons/toggles etc,

clever relic
#

Hey all, I was looking for overloading operators but found out I can't overload them for an enum... Thing is I wanted to get rid of casting my enums to int every single time I wanted to compare them with something else. Is there any way I can achieve such outcome of doing if (whateverInt < MyEnum.WhateverElse)?

fresh salmon
#

No you'll have to cast, as enums are not always backed up by int values, you can provide an integral type when declaring it

#

enum Sample : byte for example

#

If you need to do it a lot, then you can do the casting + comparing logic in an extension method

dapper cave
#

When I'm building, I get error on code that's in an Editor folder, as if the build tried to compile that in.

#

I use asmdef so I'm wondering if that's causing this editor code to be injected in the build

fresh salmon
dapper cave
#

easier if i show you

#

rotaryheart is editor only so that should not have an impact

fresh salmon
#

Yep the second one is good

#

If the first one is only used in Editor, then its checkbox must be checked

#

And nothing else

dapper cave
#

the first one is used in build , one of its subfolder is an Editor folder

#

I think asmdef were going to replace magic folder at one point

jolly token
#

If you use anything that only in editor assembly you'd get error

jolly token
dapper cave
jolly token
#

Yes

dapper cave
#

thanks for the help @jolly token & @fresh salmon

misty glade
#
List<Task> tasks = new();
Task storeTask = _storeManager.InitializeStoreAsync(ssc); // this starts...
tasks.Add(storeTask);
Task cutsceneTask = _cutsceneManager.InitializeCutscenesAsync(ssc.CutsceneVersions); // .. but this doesn't
tasks.Add(cutsceneTask);
await Task.WhenAll(tasks);

I have an async task that.. doesn't appear to be starting.. Any ideas..? I have a log message as the first line of the cutscene init manager, it never gets shown.

sly grove
misty glade
#

main thread, but I was trying to take some long running init stuff off it

sly grove
#

if you put a log before the await line does that print?

misty glade
#

the store async method needs to be run on the main thread unfortunately (unity UGS limitation), but my cutscene manager doesn't.. it was doing some long-running file reading/deserialization

#

in the Init?

sly grove
#

right in the snippet you shared

misty glade
#

oh

#

yeah

#

i suspect there's an exception in the task (since I'm not managing cancellation tokens) but ... the first line of the method (just log output) isn't even getting run

#

(i tried starting it just for laughs because I'm not understanding why the cutscene task doesn't appear to be starting)

sly grove
sly grove
#

e.g. cutsceneVersions is null

misty glade
#

6 runs if i comment out the Start()

#

hm..

#

OK, it's probably worth doing this task exception handling anyway, not just for solving this bug but.. you know, for real world exception handling :p

sly grove
#

yep - maybe confirm with a quick (constant string) log before that line to make sure that's the issue

austere jewel
#

is there a reason you're not just using the debugger and seeing where it gets to on either

misty glade
#

I was, but.. I don't [yet] know how to step into tasks.. the calling method just immediately goes to the next line

austere jewel
#

also, don't use Start, you'll be killing exceptions if you don't properly await a task

#

I'd just put breakpoints down and not step

misty glade
#

Yeah.. the start call I know is incorrect (especially because the async method itseelf is awaiting internally - my understanding is that automatically starts it)

#

Yeah, I tried that too but ... they didn't hit in the async method? not sure why

#

Why is this exception not thrown to the main thread?

try
{
   Task.WhenAll(tasks); // exception in here isn't thrown on the main thread?
}
catch (Exception e)
{
  // this correctly catches
}
#

Do I have to specifically dig into the aggregate exception and throw that?

#

(if I wanted the exception thrown on the main thread - which in general, I don't, but.. still learning how to do async in unity properly)

austere jewel
#

you must await everything that produces a Task for the exceptions to be thrown properly

misty glade
#

so this calling method needs to be awaited? (it's not currently)

austere jewel
#

if you're doing a 'fire and forget' at the root somewhere you should be starting that from an async void:

public async void FireAndForget() => await TaskProducingMethod();
misty glade
#

ok.. i thought that "async void" was improper - one of my analyzers flags it, actually, so I've just always defaulted to async Task

#

but I'm not sure how to go from things like void Update() to async Task properly

#

K, it was a simple NRE. Making the parent async void and awaiting the call here captured the exception on the main thread properly. Thanks.

#

Was checking to see if cache was != null to recreate it. ๐Ÿคฆ

#

(ie - always returning null)

#

Yup

#

๐Ÿ™‚

jolly token
sly grove
misty glade
#

i love ligatures tbh

#

I also dig this new discord font

rancid swift
#

Anyone have experience with Roslyn Analyzers in Unity?
I have diagnostic errors which are displayed in the unity console, but neither in Rider nor Visual Studio at the proper locations ๐Ÿ˜…
How do I get the IDE to recognize the Roslyn Analyzer?

rancid swift
#

uuuh, I wrote the analyzer myself, so I've pretty much ruled out the most basic problems ๐Ÿ˜…

#

it's not even in a MonoBehaviour, just a normal C# file

severe topaz
#

alright, then i have no idea ๐Ÿคทโ€โ™‚๏ธ

rancid swift
#
  • diagnostics are displayed in the unity console and prevent play mode as "compile errors"
  • double clicking on the message jumps to the proper location in the code
  • however neither IDE displays any errors
  • classes generated by source generators work in Rider, but not in VS
scenic forge
#

Have you added the analyzer to csproj?

rancid swift
scenic forge
#

Csproj regenerates, so you need an editor script to modify it rather than doing it manually.

#

Adding the asset label only works for Unity, IDEs aren't aware.

rancid swift
#

oof, that sounds like a horrible hack... but also like sth that would work harold

rancid swift
scenic forge
#

See this, but you just need an editor script that implements OnGeneratedCSProject and add your analyzers in there like you would with a normal csproj, then IDEs should work fine.

rancid swift
#

I'll try the onGeneratedCSProject now, thanks for the hint!

scenic forge
#

I thought that only adds compiler arguments to Unity.

rancid swift
scenic forge
#

Interesting.

#

Well the entire Unity and C# integration feels like a giant hack tbh, nothing surprises me anymore ๐Ÿ˜…

rancid swift
#

Hmm, the generated .csproj files already have an <Analyzer Include="absolute/path/to/analyzer/dll"/> in them

scenic forge
#

That makes sense, Unity probably sees the asset label and adds it for you automatically.

rancid swift
undone coral
#

Rider seems better for this sort of thing

rancid swift
wet burrow
#

So none of you fine lads would happen to know how to open another app on an iOS or Android device, would you? I have a function that takes screenshots and recordings and saves them to the device's camera gallery, and I want to have a button that opens said app with the correct gallery.

#

I thought I'd be able to do it with Application.OpenURL but that doesn't work on Android anymore

undone coral
#

i think there is a prime31 plugin for this

wet burrow
undone coral
#

i think check for a prime31 plugin

wet burrow
regal olive
#

Hi there, how do I convert an .apk or .zip file to a unity project?

thin mesa
#

don't crosspost

wet burrow
# regal olive Hi there, how do I convert an .apk or .zip file to a unity project?

What?
Okay you seem to be a total programming noob.
It doesn't work that way. You can make a Unity project and then export it to an APK so it runs on Android devices, but not the other way around. There are heaps of APK files for Android apps that have nothing to do with Unity, so it's not like you'd be able to just unpick it like that.

#

well okay I believe there are techniques for reverse engineering code like that but they're beyond me

#

What are you trying to do?

thin mesa
#

this was already discussed in another channel

regal olive
#

The owner of the game does not care whatsoever

#

Other people have done it too

thin mesa
#

this is neither advanced code related, nor allowed to be discussed in this server

regal olive
wet burrow
regal olive
#

He even went ahead and let other people do it

#

there's a mediafire copy of it

#

I can send you

#

its an .apk

wet burrow
regal olive
long ivy
#

it's not likely you can upload to the store anyway without a lot of work, even if you could somehow unbake a cake back into its base ingredients

thin mesa
#

android apps made in unity are cross compiled to c++ which includes a lot of code/asset stripping. you will not be able to get a unity project from the apk

regal olive
thin mesa
#

and yet its still not a unity project, funny how that validates exactly what i said, right?

regal olive
#

Yeah, but I can see most of its source through Visual Studio

#

Which is a lot better than an .apk file

#

so it's a start

lyric dragon
#

Hello guys!

I am currently working on UI, and I want to make something similar to this: https://www.pinterest.co.kr/pin/14988611250838373/sent/?invite_code=e95a3917ee15419d94ed20946a9eb1e9&sender=865746865776330201&sfo=1

Button have to move from side to side and they have to get enlarged when user presses them, as they enlarge, they push other buttons away from each other.

In order to implement side-to-side movement I chose a fixed point add random numbers to x,y positions, and smoothly move to that point (using lean tween)
In order to implement repelling buttons, I added rigidbody2d and collider2d components to my button gameobjects.

They both work well when they are separate, but the problem arises when I try to simulate both behavior. When colliders push each other, the code that is responsible for side-to-side movement contradicts the collider push and objects get crazy.

How can I make this work?

obsidian glade
cyan vessel
#

can you load androidlib with resources only (images) at runtime?

upbeat path
proven blaze
#

please, help! any idea if it is possible to combine multiple PhysicsScene into a single one?

cyan vessel
# upbeat path wdym androidlib?

recent Unity changes made it required to store Android-related resources in other package than the game, so I want to load package with image resources at runtime (no code)

deep scaffold
#

I currently have beef with chatgpt so i want someone with deep knowledge of c#
one definition that chat gpt gave me was An array is a fixed-size collection of items that have the same data type, while a list is a dynamically-sized collection of items that can have different data types. and when i asked him to give me example of list with different types he gave me this List<object> myList = new List<object>(); but i can have array of objectss too after 4-5 more questions i still can't get exact answer on what does he mean that list can have different types and array can't, can someone help me here? c# discord servers help channel ic currently disabled so here i am

upbeat path
shadow seal
#

The C# Discord's help channels are also not closed

shadow seal
#

Hmm indeed

flint sage
#

Imagine looking in the archive and expecting to be able to post things in there

shadow seal
#

Help 0 is also open

flint sage
#

Anyways, chatgpt is not to be trusted

deep scaffold
deep scaffold
flint sage
#

No it's not

#

Or help-0 isn't

shadow seal
#

I was just correcting the incorrect information

#

The C# Discord has open help channels

deep scaffold
#

anyway, thanks for help, i think chatgpt is wrong too, i just wanted someone else confirm it too

brave viper
#

ChatGPT is wrong about a lot of things. Do not use it as a source of trusted information, even the devs themselves have said this

devout hare
#

Already dreading that this'll become a trend
"ChatGPT said that 1+1 is 3 but when I did Debug.Log(1+1) it printed 2, why??"

flint sage
#

It already is unfortunately

scenic forge
#

ChatGPT is not only wrong at times, when that happens itโ€™s also wrong very confidently.

regal olive
sly grove
regal olive
#

Okay thanks

obsidian glade
umbral trail
#

has there even been talk about getting unity to support z=up?

sly grove
sage radish
#

y=up is the correct way anyway, don't @ me

random dust
#

It can be incredibly accurate with its answers but when its wrong it's very wrong. No point in "Arguing" with a bot that has been trained to answer in a specific way.

#

For your information, both can bold different data types when it's of type object or dynamic.

midnight venture
#

Arguing with chatgpt is useless, since you can only affect its local short time memory

#

Which is a good choice, since otherwise it would be a right-wing conspiracy troll bot in two hours or so ๐Ÿ˜‚

flint geyser
#

Is there a way to make a generic class which would have a collection of objects of said generic abstract type and methods which correspond to those of said generic abstract type but instead call the corresponding method on all of the stored objects?

new MagicalCollection<IMover>().Move();
new MagicalCollection<IStorer>().Store();
new MagicalCollection<IDefender>().Defend();
scenic forge
#

You can do it with source generators.

#

Might be a bit overkill though unless it's a pattern you use a lot.

compact ingot
#

its a useless pattern

#

you can just do ```cs
public interface IFoo
{
public void Execute();
}

List<IFoo> items;
items.ForEach(it => it.Execute());
scenic forge
#

If you only want to call one action of each generic type then sure that works

#

Not saying anything about the usefulness of the pattern, just saying it's possible.

long ivy
compact ingot
scenic forge
#

Extension methods.

#

You can write a source generator that analyzes the call you want to make, and generate an extension method matching the signature.

flint geyser
#

I have ColliderSubscriptionHandler which basically has all the possibly accessed through collision objects subscribed to it. And it has

public List<T> GetSubscribers<T>()
{
  List<T> resultList = new List<T>();
            
  for (int i = 0; i < _list.Count; i++)
  {
    if (_list[i] is T subscriber)
    {
    resultList.Add(subscriber);
    }
  }

  return resultList;
}```
to get all the subscribed objects. It looks like a pain to manually iterate over them each time, hence my question.
compact ingot
scenic forge
#

Adding that feature to C#?

flint geyser
#
public void CallForEachT<T>(Action<T> action)
{
  foreach (T subscriber in GetSubscribers<T>())
  {
    action(subscriber);
  }
}```
Stopped on it for now
compact ingot
#

you can also do it with reflection but its still a silly idea

scenic forge
#

It's far from a stupid mistake, it's an amazing feature that enables lots of previously impossible patterns.

compact ingot
#

also it makes the answer to all questions "yes"

#

which is not helpful

scenic forge
#

Calling it stupid is very debatable, it may not be used as much specifically in Unity, but it is very much used in the wider C# world.

compact ingot
#

"very much" being debatable

flint geyser
#

You sound like those politicians from TV. It isn't like world collapses because of adding a feature to a programming language. Yeah, some use it improperly, but it also enables things which were impossible before, and it is way more important then code of some people which can't even see where they are overusing a feature

compact ingot
#

anyway, i'm not against source generators i'm against using them for obviously silly ideas

scenic forge
#

Hence why I said it might be an overkill.

#

Source generator isn't the first solution to every problem.

#

But it exists to solve problems that are otherwise unsolvable without it.

compact ingot
flint geyser
#

Every your message sounds toxic to me, I'm out, sorry

scenic forge
#

STJ is the one example of making great use of source generators, its performance is miles ahead of Newtonsoft.Json.

#

It's not just STJ, most serialization libraries look to make use of source generators/already do. Instead of the old way of "writing some metadata specific to this library to describe the shape of data, use their tool chain to generate code, then finally you are able to de/serialize" (which is how things like Protobuf work), now you can just write POCO decorated with a few attributes, and all de/serialization code is generated at compile time, adding zero cost to development pipeline while avoiding the runtime cost of reflection.

#

Comparing to things like C++ templates and Rust macros, C# source generator is probably one of the sanest metaprogramming tools simply due to the fact that you can only add code, not modifying existing code.

wooden cedar
jolly token
#

Sounds like they want a proxy object. In regular .NET program would make it with runtime code generation.. like Moq uses Castle, but it's not possible on AOT platforms

kind sigil
kind sigil
#

When I change Prefab Asset props and mark it as dirty, is that enough to trigger all the changes in all instances of that asset? Or is there another step I must take?

flint geyser
#

Anyway for now I got this, tho name of the lower method looks too long

#

Perhaps I should introduce a metaphor

severe topaz
#

the more important it is, the longer it gets. that way it's easy to find it from a single glance ๐Ÿ˜‚

flint geyser
#

I think it's a little better this way

minor garden
#

where is the source code or how to make update and fixed update method in my console server. I want it to be similar to the client

untold moth
minor garden
tawny bear
#

Then I'd suggest asking in the C# discord

whole quest
#

Guys, I tried to send live notifications from using "Firebase" to my Unity App. ฤฑ dont have any console error or Firebase errors, but I cant send notifications to my android device. Who has an experience about this situation ?

junior nest
#

Hey! Quick Question:
I codegen classes out of templates with Editortools and need those compiled only when i hit play. Everything works fine if i enable Domain Reload in the EnterPlayMode Options. I would like to keep it disabled by default though and only enable Domain Reload if at least one of those classes got codegenerated. Is there a way to flag that unity should reload domain before entering playmode?

junior nest
#

Answering myself here:
Subscribing to EditorApplication.playModeStateChanged allows me to force an AssetDataBase refresh before entering playmode. I can now generate code at any point in time and only load it when im about to enter playmode instead of instantly loading it.

plain abyss
#

I have some runtime generated meshes that are loaded from external data. Right now they're taking up a lot of RAM to keep in memory. They're all set up with simple colliders and have simple shapes so the CPU/GPU usage is manageable, but the RAM requirements having those meshes loaded is apparently the bottleneck. Does disabling an object reduce the RAM burden of keeping the object in the scene, or do I have to remove it entirely?

undone coral
plain abyss
# undone coral i remember this is a complex problem

Yes, the meshes are generated from AutoCAD drawings with an external program. I use that geometry data to construct meshes in 3D space in Unity at runtime. This particular case is a classified site so I don't have the data to test but they have told me it's nearlt 30GB of RAM usage

undone coral
#

if you DestroyImmediate the MeshRenderer, then the Mesh it was referencing, what happens? does the memory profiler say your memory usage goes down on the next frame?

undone coral
#

let's say a sane person designed this. if you Destroy the MeshRenderer, and nothing else is referencing its Mesh, i would expect memory usage to decline at the start of the next frame

#

there's also a big difference between a Mesh that was loaded from the player data versus a mesh that was created at runtime

#

logically, if the runtime-generated Mesh is only referenced by one thing (the MeshRenderer) by the end of a function that resembles

void CreateMesh() {
 var mesh = new Mesh();
 ...
 meshRenderer.mesh = mesh;
}

and unity implemented Mesh similarly to

class Mesh {
 ~Mesh() {
  Free_NativeObjectAndMemory();
 }
}

then the difference between

  1. do nothing (GC will collect mesh and finalize it)
  2. Destroy (ask nicely to destroy something by the start of the next frame)
  3. DestroyImmediate (destroy something right now)
    where destroy/destroyimmediate calls something of the form
class Unity.Object {
 private void OnDestroyNow() {
  ...
  Free_NativeObjectAndMemory();
 }
}

is the amoutn of time you have to wait to get the memory back

#

@plain abyss unfortunately it is not documented how things are implemented in terms of memory management.

plain abyss
#

I'm just about done setting up a test case I can use to see the memory usage in the profiler

undone coral
#

@plain abyss in terms of what it means to "get the memory back," it might be platform specific what really happens. unity has to implement the platform specific way of "giving back" a large block of memory in order for that to happen immediately

plain abyss
#

I had an object call DestroyImmediate on all of the meshrenderers, meshes, and meshfilters on all child objects. It's one such "chunk" of many, but I figured that the expected use case of unloading a single "chunk" would be how I'd solve the memory usage. There's a visible dip in the "Object Count" line but no major changes in any others. Maybe I need a bigger test?

undone coral
#

there are lots of reasons the editor will hold onto something and DestroyImmediate will not free the memory

#

did you create native arrays for the meshes

#

with persistent allocation?

plain abyss
undone coral
#

that will also cause misery. you will have to explicitly free those

plain abyss
undone coral
#

okay good

#

then you did not

#

you might have to Free (or whatever it's called) the native array you used for runtime generation

#

this is just part of the clunkiness of this system they made

#

you can blame people who want more C++ in their C# for it

#

which was one of the biggest blunders unity made...

#

@plain abyss so there are many ways this memory can stick around. in short, because of the way the APIs have accumulated over the years, the way you get the memory back depends a lot on how you runtime generate the mesh and which APIs you use. look carefully if there is a corresponding free / deallocate / something similar API call in the exact approach you have.

plain abyss
#

Standalone process, this time killed every mesh. Again, a drop in objects, but not a big dent overall. I wish I could profile the actual case that is having the issue but I don't have access to that data

#

Dropped by 15-ish percent

undone coral
plain abyss
ember nexus
#

Hey lads, I've made a relatively simple waveform/spectrum visualizer using GetSpectrumData() from an audioClip, and writing onto a RawImage's Texture2D.
As you can imagine, it looks over the float array spectrum output and then draws directly onto the texture with the following code inside FixedUpdate()

// reset the texture to the "blank" screen
texture.SetPixels(blank, 0);

//get textureData
textureData = texture.GetRawTextureData<Color32>();

// get samples from channel 0 (left speaker) 
AudioSource.GetSpectrumData(samples, 0, FFTWindow.BlackmanHarris);

// draw the waveform 
for (int i = 0; i < sampleSize; i++)
{
    int amplitudePixelHeight = (int)(samples[i] * maxScale); //note: maxScale is a const float of arbitrary size used to scale the spectrum data which is otherwise a very tiny number than wont display
    int pixelStartPosition = heightHalved - amplitudePixelHeight / 2;
    for (int j = 0; j < amplitudePixelHeight; j++)
    {
        textureData[width * i / sampleSize + width * Mathf.Clamp(pixelStartPosition + j, 0, height)] = waveformColor;
    }
}

texture.Apply();
#

texture.GetRawTextureData<Color32>(); allows me to directly change pixels (though it is an image represented by a 1D array, which is a bit annoying), but I have heard this is the fastest method.
However, to reset the background to a "black" color with a green line at the middle, I have to set it to my blank array which is just an array of black pixels with a green line at the middle, with the texture.SetPixels(blank, 0) every frame, before drawing the waveform. This has the annoying side effect of frequently deallocating memory that I retrieved texture.GetRawTextureData<Color32>(); in the Start() method, and thus I need to grab a new reference to it inside FixedUpdate().

My question here is - do you guys know the best way to do this? I've been thinking of continuously keeping a buffer of changes in a List of ints (indexes), from the previous FixedUpdate, and then reverting them to a black pixel by looping through the list - since this means I don't have to set ALL the pixels to "blank". I don't think this is neccessarily super efficient either though, but maybe an improvement - so I'm hoping you guys are smarter than me

undone coral
ember nexus
#

audio clip

undone coral
#

okay

long ivy
#

the docs say GetRawTextureData doesn't allocate memory and that you shouldn't store it anyway. Also, I question updating a texture in FixedUpdate

undone coral
#

@ember nexus what is your goal?

ember nexus
undone coral
#

okay... so you want to do this for a microphone?

#

or for the in game audio?

ember nexus
#

No, an audio channel

undone coral
#

what's the objective? what is the game?

ember nexus
#

It's a 3D game where you're on a spaceship, graphics will be high quality so thats why I am doing this on the CPU instead of the GPU since I am guessing the game will be bottlenecked there
The objective is to visualize some sounds from outer space that you're listening to in a telescope minigame. It will be added to an ingame screen mesh's texture

undone coral
#

so help me understand. should the waveform correspond to a specific audio source?

#

or to everything your audio listener hears?

#

or to a specific layer in your audio mixer?

ember nexus
# undone coral so help me understand. should the waveform correspond to a specific audio source...

Sorry, I'm not too familiar with it yet - but I plan on having the telescope minigame have noises from several different audioclips, so I am assuming its from either 1 source or 1 specific layer - the "telescope minigame layer". I plan on playing a sound every time an event fires - this event fires more often the closer the telescopes "crosshair" is to an object of interest in the sky. I hope that makes sense

ember nexus
#

Imagine some background noise playing constantly, and getting louder the depending on your camera's rotation. Then, an interval of a sound similar to a sonar ping that occurs more frequently the closer you are

undone coral
#

you should use an approach like https://github.com/aaronstatic/unity-vfx-extensions/blob/master/Runtime/Utilities/PropertyBinding/Implementation/VFXAudioSpectrumHistoryBinder.cs or WavTexture to write the audio data to a texture, then you can turn that texture into art using Shader Graph

GitHub

Extensions for the Unity Visual Effect Graph. Contribute to aaronstatic/unity-vfx-extensions development by creating an account on GitHub.

#

there are lots of approahces to this but ultimately drawing in a shader is the only practical one

#

hope this helps

#

you will have some trouble* extracting audio from a particular track*

ember nexus
#

Thanks, I'll have a look. Can you explain what you mean by turning the texture into art using shadergraph?

undone coral
#

the texture contains just the audio data

#

the drawing from that audio data into a line for example is done with the shader (created with shader graph)

#

that's what i mean by "art"

#

the texture itself is not the art

#

it is an idiosyncratic way to store the audio data

#

does that make sense?

#

you owuldn't write a shader. you would use shader graph to turn that texture into 2d graphics, like a line

#

or whatever

#

you don't want to write a shader.

ember nexus
#

I was initially thinking of doing this in a .compute shader, but I was not sure it would be a good idea because I figured my game would be bottlenecked by GPU

#

but I guess for tasks like writing to a texture, it's a nobrainer to use the GPU since its specialized for that task

undone coral
#

ou don't need a compute shader

#

you dont' need any shaders

#

you need to use shader graph, which is a visual tool

ember nexus
#

I know shader graph, though i've never used it yet

undone coral
#

and a little bit of code to glue the audio data to something it can use

#

which is a texture

#

shader graph creates shaders*. i am saying you definitely, 100% do not want to author, by hand, hlsl code

ember nexus
#

Do you understand what the texture data contains? Does it contain the data that will be drawn, similar to my own code but without actually making the draw call yet?

#

Or is it just a strange way of storing the spectrum data, and I have to somehow interpret the spectrum data inside shader graph

undone coral
#

it [is] just a strange [the] way of storing the spectrum data, and I have to somehow interpret the spectrum data inside shader graph

#

so you won't do any drawing, in any sense of the word, in C#

ember nexus
#

I see, so it has to be stored inside a Texture object in order to send it to shader graph

undone coral
#

it can be stored in a variety of ways but a texture will be the most convenient

#

it can also be stored using graphics buffers

ember nexus
#

That's why its not just stored as a float array, like it natively is, and then sent to shader graph

#

Oh, okay.

undone coral
#

but i think that will be out of scope for you

#

focus on what there are examples for in github

#

i search "audio waveform unity github" in google

#

i'm sure there are asset store assets for this

ember nexus
#

Yeah, they all seem to be non-shader though, so I figure i'd try to do it myself lol

#

I'm honestly tempted to try to make a compute shader though, since I have zero experience with shader graph

undone coral
#

don't write a compute shader

#

stop with the shader writing

ember nexus
#

Thanks for your help

jolly token
undone coral
#

it doesn't sound like Burst a/k/a "HPC#" supports finally

jolly token
scenic forge
undone coral
#

HPC# fka Burst

#

"FKA Burst" would be josh peterson's stage name

bold berry
#

I want to debug my 2d gravity field to see how big the range is, can someone help.

scenic forge
#

Which I thought an easy solution would be to just do my own validation with CertificateHandler except with LE's CA embedded, but no.

#

I guess I'll have to either: tell my users to update their OS (or get a new phone if it's no longer receiving updates), tell my users to manually install LE's new CA, or I don't use LE for my backend.

#

Thanks Unity.

kind sigil
#

What PrefabUtility method will allow you to input a game object instance and get back its Prefab asset?

kind sigil
kind sigil
#

Build errors:

The type or namespace name 'SceneManagement' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?)
The type or namespace name 'Editor' does not exist in the namespace 'Sirenix.OdinInspector' (are you missing an assembly reference?)

This script uses PrefabStageUtility and all of that code is wrapped inside UNITY_EDITOR directive. Same for Sirenix, I am using an inspector callback with InspectorProperty arg. In order to fix this, I have to go to each method and attach namespaces on all of them and remove using namespace above. That's annoying. Is this a bug or did I miss something?

austere jewel
#

Sounds like it's not wrapped in the directive tbh. It wouldn't be compiled if it was

sly grove
#

Often for code that is editor-only, I like to forgo using statements and just use the fully qualified class name inline so I don't have to worry about separately excluding the using directives too

kind sigil
#

Ah. I see. Iโ€™ll just make a partial and wrap the whole thing instead. Thx.

muted root
#

Optimization question: If I have a hundred xml files in a folder and want to often access them, should I keep all files opened in an instance or opening them on the fly is fast enough? Or considering they have the same structure, should I merge them all into one huge xml instance? The files themselves would only be a few Ko.

sly grove
#

Are you loading and unloading individual files repeatedly? You might benefit from keeping them in memory.

Are you only accessing a few of them, the rest going unused? You might want to consider lazily loading them on demand.

muted root
#

Lazily loading?

sly grove
#

yes

muted root
#

What's the difference with loading ?

muted root
#

Thanks

sly grove
#

that article is in the context of a website with JS but the concept is the same

muted root
#

Ok, got it. It makes sense indeed

sly grove
#

here's a more general purpose article... https://en.wikipedia.org/wiki/Lazy_loading

Lazy loading (also known as asynchronous loading) is a design pattern commonly used in computer programming and mostly in web design and development to defer initialization of an object until the point at which it is needed. It can contribute to efficiency in the program's operation if properly and appropriately used. This makes it ideal in use ...

muted root
#

But in the case I need to scan all of them to validate the xml content anyway, it's still better to keep them all in cache since I already loaded them anyway? Overall it would only increase the memory by a few Mo I guess so it shouldn't have much impact? If memory does even have impact on performances?

sly grove
#

again it depends on the access patterns

#

in general it is not a good idea to keep unnecessary resources in memory unless you have a good reason

#

A good reason might be: "I know I'm going to use it again soon"

#

why do you need to validate the xml content of all of the files?

#

and when do you need to validate the xml content of the files?

muted root
#

Because the game would be moddable and use xml files to add content to t he game. And I'd like the game to validate the structures of the xml the players will add in their mod folder to find mistakes and give proper error messages.

#

Meaning, I'd load all xml at game launch, then they'd be used only when the player start an actual playthrough. And during the playthrough, they might be loaded quite often. The XML would contain data about events in game so they'd need to be access which time time passes.

sly grove
#

For the validation I would do it in a background thread at game launch, and not keep the XML data loaded, no. Also I'd probably make "auto validate all XML files" an option in the settings which can be disabled because it could be a pretty heavy operation.

Only would actually load them as needed when a game starts otherwise, and probably would have a system allowing you to enable/disable which ones you want loaded in a particular game.

Also once you load the data you need into runtime structures, you can release the XML string and XML tree themselves

muted root
#

Is keeping the XML tree in memory heavy ?

cobalt topaz
#

Hey can anyone pls help me with the procedural terrain generation (I am quite confused by the perlin noise). Script (ignore the comments, just for testing): https://pastebin.com/Pdd1wYi0. It looks like this, but it doesn't actually has the right offset, as you can see: But if I simply use "magical numbers", the upper and right terrain now works, but the left and down terrain won't: csharp Vector3[] possibleTerrainPositions = new[] { new Vector3(0, 0, 512), // up new Vector3(512, 0, 0), // right new Vector3(0, 0, -512), // down new Vector3(-512, 0, 0), // left }; Vector2[] possibleTerrainDataOffsets = new[] { new Vector2(-512,0), new Vector2(0,-512), new Vector2(512, 0), new Vector2(0, 512), }; Before:

sly grove
#

Never keep someting in memory you don't need to keep in memory. It's wasteful.

muted root
#

Ok

sly grove
#

Just look how pissed off users get when programs use unecessary amounts of memory

muted root
#

True ahah ๐Ÿ˜‰

#

Thanks for your help ๐Ÿ™‚

cobalt topaz
ebon cobalt
#

Just lookup how to make perlin noise tileable

cobalt topaz
#

I did, but couldn't find anything helpful

ebon cobalt
#

And more I found with a short search

cobalt topaz
#

The second one is also not answering my question.

cobalt topaz
ebon cobalt
cobalt topaz
ebon cobalt
#

Am sorry, I don't understand

cobalt topaz
devout orbit
#
        public static async UniTask<T> InstantiateAddressableAsync<T>(string addressableName)
        {
            var go = await Addressables.InstantiateAsync(addressableName);
            return (T)go;
        }```
#

Any know how to fix my cast issue tried where T : Monobehaviour etc

ebon cobalt
#

@cobalt topaz you can try getting the neighboring noises in advance, then adding some blur at the ends

#

Or you could also just always set the edges to completely white so they will always tile, no matter what happens

cobalt topaz
ebon cobalt
#

Nope, but I'm sure that joining the 2 images and applying blur at the right place will be possible

cobalt topaz
ebon cobalt
#

Am sure you can find info in Google about it

short fog
#

Hi. I want it to continuously increase and decrease a float value between 2.0f and 6.0f. What should I do?

grand dagger
#

can anyone tell me why is this happening?

using System.Collections.Generic;
using UnityEngine;

public class NotePlacing : MonoBehaviour
{
    public GameObject notePrefab;
    public List<GameObject> notes;

    public float xMin = -8f;
    public CharterController charterController;

    public float cellSize = 0.5f;

    float yPos;

    bool[,] grid;

    void Start()
    {
        int numRows = (int)(20 / cellSize) + 1;
        int numColumns = (int)(10 / cellSize) + 1;
        grid = new bool[numRows, numColumns];
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
-->             PlaceNote();
        }
    }

    void PlaceNote()
    {
        Vector3 worldPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        float xPos = worldPosition.x;
        float[] values = { 4.15f, 2.8f, 1.45f, 8.2f, 0.1f, -1.25f, -2.6f, 13.6f, 14.95f };

        float closestValue = Mathf.Infinity;
        for (int i = 0; i < values.Length; i++)
        {
            if (values[i] < worldPosition.y)
            {
                closestValue = values[i];
            }
        }

        yPos = closestValue;

        xPos = Mathf.Round(xPos / cellSize) * cellSize;
        yPos = Mathf.Round(yPos / cellSize) * cellSize;

        int row = (int)((xPos - xMin) / cellSize);
        int column = (int)(yPos / cellSize);
-->        if (grid[row, column])
        {
            return;
        }

        GameObject instantiatedNote = Instantiate(notePrefab, new Vector3(xPos, yPos, 0), new Quaternion(0, 0, 0, 0));

        grid[row, column] = true;

        notes.Add(instantiatedNote);
    }
}

IndexOutOfRangeException: Index was outside the bounds of the array.
NotePlacing.PlaceNote () (at Assets/Scripts/Charter/NotePlacing.cs:56)
NotePlacing.Update () (at Assets/Scripts/Charter/NotePlacing.cs:30)

flint sage
#

Could you know mark the lines

grand dagger
#

yeah wait a sec

flint sage
#

But I'm guessing your array math is wrong and its out of the bounds

grand dagger
#

then how would i go about fixing it

flint sage
#

Figure out what's wrong in your math

#

Or clamp it to the array size

#

Also your ScreenToWorldPoint always returns the camera position

#

position A screen space position (often mouse x, y), plus a z position for depth (for example, a camera clipping plane).

undone coral
ember nexus
#

Hey @undone coral , i'm trying to do what you told me yesterday but i'm not clear on some basics. Are you aware if the link you sent me yesterday is only meant for particle effects? https://github.com/aaronstatic/unity-vfx-extensions
I've got it set up until the Shader graph step, but idk where to go from there. I've set the Audio Spectrum Shader Binder to a UI RawImage, and set it up as you can see - but could you tell me how to retrieve the data inside my shader graph?

undone coral
#

you have to use what your ead inside of them to create a texture

#

maybe this is too complicated.

#

i think you should prerecord the wavform and play it back

#

since it's not going to be that important for gameplay

ember nexus
#

I realize that it only gives me the data

#

I'm just not sure how to retrieve the data inside shader graph, that's all

undone coral
#

you can call .SetTexture on the material using the sahder

ember nexus
#

I think it does this already, the library

#

I just don't know how to retrieve it lol, I realize it's probably super basic

undone coral
#

you'll figure it out

unborn sky
#

any vscode & SourceGenerator users have an idea of how to debug / see the output of failing / buggy source generators?

#

the only way i know to actually access the generated files in vscode is by using go to definition on a code path created by the generator, but this obviously doesn't work if the generator itself is having issues

undone coral
#

what is the goal?

unborn sky
#

we're using them to generate boilerplate for a buffer of state frames

#

anyways, we figured out a nice enough solution, which was to just throw in the generator with the text of the generated file -- that's usually my first tool so i don't know why we didn't reach for sooner

scenic forge
undone coral
#

what do you mean? what are you trying to do

#

usually for data transport objects / serialization, you should use a mature framework

#

like protobufs, msgpack or if you're a maniac cap'n'proto

unborn sky
unborn sky
#

and weโ€™re using a sourcegenerator to synthesize annoying stuff like equality for the frame and convenience accessors on the state wrapper that pass through to the most recent frame

unborn sky
scenic forge
unborn sky
#

we have it working now, just not a great workflow for debugging issues with the source generator, would be nice to be able to view the (even broken) output (and logs) somewhere consistent thru vscode

#

also seeing some weird behavior. the source generator runs for every dll in the unity project and if it succeeds on the first few dlls (even though it generates nothing valuable) it stops generating for dlls later in the build chain

#

so we have to throw an error for all the dlls we don't care about generating code for

scenic forge
#

In IDE or when building the game?

#

As for debugging source generator, if it runs successfully you can view the generated files directly to see what's up; if it throws during generation then I'm not too sure either, all my generators are rather simple so I haven't ran into that, would be interested to know how you guys deal with that.

unborn sky
#

when building & in the unity editor logs. vscode seems good for debugging issues when something is generated that you can cmd+click into, but otherwise not

scenic forge
#

Not sure about that then, I know Unity sometimes doesn't rerun SG and you have to force a recompile (for example it won't detect additional file changes and won't rerun SG dependent on additional files)

#

But from my experience when building it always reruns all SG.

#

As for debugging SG throwing, you can attach debuggers but I never went that far. I simply try catch and write the error out to a generated file, but that probably isn't a real solution.

fickle inlet
#

Hey, how do I edit a specific line inside text mesh pro ui component? Let's say I have N number of lines of text and I want to edit 3rd line, how do I do that?

pliant crest
#

you just manipulate the string

#

if its one object

#

split it via whatever delimiter and modify the 2nd index or something

#

or...just have multiple objects per line

compact ingot
lofty inlet
#

so I'm trying to assign a color value to a TMP_Text element, but for some reason the alpha isn't being assigned [the other aspects are: r, g, and b]. Does anyone know how I can copy the alpha value over as well?
I did some debugging, and apparently the alpha value is changing but it isn't being reflected in the actual scene/game

undone coral
#

and you're making macros

#

because that's what you're familiar with from C++

#

to do something like, blah blah blah, this field in this class is replicated. the class happens to be a blah blah thing, but it could be anything

#

is that the idea?

undone coral
jolly token
unborn sky
#

hehe nah, not much of a c++ person. but used meta-programming facilities in many languages, and while i endeavor to design apis that are meta-programming avoidant, in some cases (in particular in typesafe languages with a not-sophisticated-enough type system ;) sometimes itโ€™s the right tool for the job.

unborn sky
jolly token
#

Compare to vs code

unborn sky
#

yeah :/

undone coral
remote drift
#

Is there a way to register MonoBehaviour that is created in a file that does not match type name?

#

so it appears in Inspector

sly grove
cedar stone
#

I have a situation where I need to shoot a raycast from one gameobject, which is GameObject currentGameObject, and then I need to assign the hitted gameobject with this variable. How could I do that?

glass wagon
#

How to get a callback when a value is changed in the Inspector of a ScriptableObject?

glass wagon
sly grove
#

There is

#

But it doesn't tell you if something changed

#

Nor what changed if something did

glass wagon
flint geyser
#

I made this abomination

public class ContinuousAttackDependantOnAnimationDecorator :  IDamageDealer
    {
        public ContinuousAttackDependantOnAnimationDecorator
        (
            IContinuousDamageDealer continuousDamageDealer,
            IToggleableAttackAllower toggleableAttackAllower,
            IMecanimStateExitedNotifier stateExitedNotifier,
            IAnimatorBoolSetter animatorBoolSetter
        )
        {
            _continuousDamageDealer = continuousDamageDealer;
            _toggleableAttackAllower = toggleableAttackAllower;
            _stateExitedNotifier = stateExitedNotifier;
            _animatorBoolSetter = animatorBoolSetter;
        }
        
        private readonly IContinuousDamageDealer _continuousDamageDealer;
        private readonly IToggleableAttackAllower _toggleableAttackAllower;
        private readonly IMecanimStateExitedNotifier _stateExitedNotifier;
        private readonly IAnimatorBoolSetter _animatorBoolSetter;

        public void DealDamage(IAttackTargetsProvider targetsProvider, float amount)
        {
            _continuousDamageDealer.OnAttackStarted += StartWorking;
            _continuousDamageDealer.OnAttackEnded += StopWorking;
            _continuousDamageDealer.DealDamage(targetsProvider, amount);
        }

        private void StartWorking()
        {
            _toggleableAttackAllower.ToggleOn();
            _stateExitedNotifier.OnStateExited += StopWorking;
            _animatorBoolSetter.SetBoolToTrue();
        }
        
        private void StopWorking()
        {
            _toggleableAttackAllower.ToggleOff();
            _stateExitedNotifier.OnStateExited -= StopWorking;
            
            _animatorBoolSetter.SetBoolToFalse();
            
            _continuousDamageDealer.OnAttackStarted -= StartWorking;
            _continuousDamageDealer.OnAttackEnded -= StopWorking;
        }
    }```
#

Looking forward to your comments

midnight violet
flint geyser
midnight violet
# flint geyser Why would it

the continuousDamageDealer never changes, so the function being called on it calls itself again. Or is the reference always on another "level" when being called?

flint geyser
midnight violet
#

From the code, it looks like its a round based thing?

flint geyser
#

What do you mean round based?

#

Game?

#

No

midnight violet
#

Just trying to understand your game design around your code to see, if there are improvements to be made or not. At least I thought you were asking about thoughts and suggestions ๐Ÿ˜„

flint geyser
#

Yeah I was

#

Someone in another channel suggested using callbacks instead of events

#

But I don't how's it any better

flint geyser
#

Like mario, but with ability to hit

midnight violet
#

Did the other guy explain why using callbacks instead of events?

flint geyser
# midnight violet Did the other guy explain why using callbacks instead of events?

Quote
"You're using events where simple callbacks might be more suitable. In DealDamage, you're assigning 2 listeners to them, when the first event is triggered, you add another listener, and when the 2nd (or newly subscribed to) event triggers, you remove all listeners again. In short, you're really only interested in 2 Calls: attack start and attack end/state exit.
Just based on the names, it is difficult to say if there might be more things that could be adjusted. OnStateExited is only subscribed to, whenOnAttackStarted is triggered. If OnAttackStarted is not triggered, OnAttackEnded can still cause the "end" of the DealDamage-handling. And OnStateExit and OnAttackended are treated exactly the same way, but only if OnAttackStarted didn't trigger yet."

midnight violet
#

I guess you would need to explain a bit about the code for me to udnerstand. Maybe there are others that get it right of the bat, but if you want to explain, I am free to read ๐Ÿ˜„

flint geyser
midnight violet
#

Yeah sure, why not. You could also use hatebin for quick pasting ๐Ÿ™‚

still glade
#

Is it possible to create new ui when a player instantiates a new prefab? so every new prefab has their own ui with specific info that may vary from the previous prefab?

midnight violet
still glade
midnight violet
flint geyser
#

Attack related scripts are located here and here
EnhancedDIAttempt/Assets/Scripts/PlayerActions/StateMachine/States/Behaviours/Actions/Attacks/
EnhancedDIAttempt/Assets/Scripts/AnimationInteraction/ContinuousAttackAction/

autumn topaz
#

I am really stuck here, I have declared a struct variable as public NativeArray<Quad> quads { get; set; } in a job but I keep getting this error: InvalidOperationException: The Unity.Collections.NativeArray 1[ProceduralMeshes.Quad] has been declared as [WriteOnly] in the job, but you are reading from it. whenever I try to read it. do you guys know what I could possibly be doing wrong?

midnight violet
flint geyser
#

Sure

autumn topaz
#

ok, so I added [ReadOnly] to the array and now its saying that GridMeshJob2.generator.quads can not be marked with both [ReadOnly] and [WriteOnly]. despite a writeonly seemingly not being anywhere in the code at all.

#

and yes I might have a look in #archived-dots if there are no answers here

flint geyser
#

dots channel is way more active than this one AFAIK

autumn topaz
#

ok will try

spare pond
#

Hi. Question about loading screens. Its not that hard to trigger loading screen logic by some event like when scene changes, but more often you need loading screen to hide visuals for load big amount of resources in the current scene. Like in WoW when you have to wait for all the assets being loaded after teleport from one side of the map to the other. How it possible to track amount of resources that needs to be loaded? Is it possible with Addressables or I need to lookup for some internal unity methods?

wide bolt
spare pond
# wide bolt If I understand your question correctly, then I think you can achieve what you'r...

But thats for the loading the scene. What I'm looking for is to make system that will determine when to show loading screen based of the resources that gonna be loaded. Imagine you are in a scene, and you want to load something heavy and this loading process would look not so pleasing for the player immersion.

It feels like I need to create a special tool that will track incoming resources, determine is it heavy enough to be loaded in more than treshold and show loading screen

wide bolt
spare pond
#

The pure example is loading assets in WoW. Sometimes it will take so much time that you will see loading screen. Sometimes you wil just see greyed objects and see how they get colored. And thats on 1 scene, not talking about crossing different scenes (instance, 1 world to another)

wide bolt
#

Maybe there's a better way that I don't know of, but here's an idea...
You could start the load asynchronously, and wait a few frames before launching the load screen. During those few frames you could monitor how quickly the progress property is progressing, and make your decision about the load screen based on that information.
It's a bit of a hack, but it's the best I can think of off the top of my head.

spare pond
#

Actually, yeah. The frame count check will be the treshold that satisfy needs

#

Thank you @wide bolt

misty glade
#

@spare pond A nice "fakey" way of doing it is save the amount of time the load actually took each time you load and write that out to a file. Then just show a timer that is related to that time. For example, you load in 10 seconds, save the 10 seconds, show a timer with % of 10 seconds (and it's OK if it skips or freezes at the end). Seed the timer with something based on your best guess when you distribute the product.

Maybe save 3-5 of the "past loads" to get a nice average.

This gets you a load time that's customized for the users' hardware/network connection, and is reasonably "smooth" instead of trying to do stuff like estimate the load time based on file size, asset count, or hand-crafted checkpoints in your code.

#

Maybe I misunderstood the question, too, but if you're just looking for how to do those async loads - what Ramblin suggested works (using the unity AsyncOperation), or you can just Task off your own async stuff, you can coroutine it, or you can use the unity jobs system.

My approach for my load screen (a fresh install load is like ~10 seconds as it downloads assets from the server) is my own async tasks so that unity happily keeps doing unity things.

zealous summit
#

Hello! About a month ago I followed a tutorial about setting up a character controller. I found this tutorial to be exceptionally good because it presented a system in which all characters (including enemies, players and all others) can use the same capabilities but with different inputs. The input controller itself is an abstract scriptable object with bunch of methods for retrieving bools, floats and vectors for different capabilities like jump, shoot, look etc. I now wanted to start coding enemy AI but realized that there is always only one instance for scriptable object and since it is not a mono behavior it canโ€™t have access to transform or other components that are required to set up AI. I could pass those params to a new method in input controller (SO) but again there is always only one instance of it and it would make all enemies retrieve the same input regardless of situation. Do you know how to deal with it? Maybe someone did something similar before? If you need any more information please let me know. Thanks in advance

flint sage
#

Don't your entities have a reference to that SO that you can change to adifferent one?

#

Why is an input controller an SO in the first place?

#

SOs should really be data objects and not have game logic

zealous summit
flint sage
#

But clearly you can't just swap them

#

Otherwise you wouldn't be here asking this question

zealous summit
#

I have a mono behaviour class with a InputController reference and I can just swap it in the inspector (or via code) any time

#

but for now I have only player controller working (it returns player input) and current AI controller just returns values like false and Vector2.zero

#

I thought of changing it from SO to just mono behaviour but that would require quite a restructuring so I wanted to firstly know is it possible with SOโ€™s since the author of the tutorial claims it is

midnight violet
glass wagon
#

If an object instance knows that it's in a List in another object, and wants to remove itself from that List, but does not know its index within that List, how can it remove itself from that List?

flint sage
#

list.Remove(this)?

glass wagon
flint sage
#

It loops through all items in the list internally comparing references to the instance passed

#

If it matches, it knows the index and removes it

#

You gotta have a reference to the list of course

glass wagon
flint sage
#

Well yeah, an object won't just know where it is in a list

glass wagon
# flint sage Well yeah, an object won't just know where it is in a list

I get that, I'm trying to weigh up the issues with making own manual self awareness indexing for object instances, such that they know their index ID even as it changes in the list, versus using something like this which might have a performance cost that's unknowable because it's not going to be sure how long the list is

flint sage
#

Unless you have thousands of instances, the latter is probably better because of the hassle of having to ensure consistency

glass wagon
abstract hill
#

Hi everyone, I was wondering how I would go about running code on the main thread from an async function running on a background thread. I know its not ideal but I want to do a web request using Async, using the code below.

using (UnityWebRequest webRequest = UnityWebRequestTexture.GetTexture(url))
{
    UnityWebRequestAsyncOperation asyncOp = webRequest.SendWebRequest();
    while(asyncOp.isDone == false) 
        await Task.Delay((int) (1000f / 30f));

    switch (webRequest.result)
    {
        case UnityWebRequest.Result.Success:
        {
            return DownloadHandlerTexture.GetContent(webRequest);
        }
        case UnityWebRequest.Result.ConnectionError:
        case UnityWebRequest.Result.DataProcessingError:
        case UnityWebRequest.Result.ProtocolError:
        {
            Debug.Log( $" - - There was and error when downloading the image: {url},\n Error: {webRequest.error}, URL:{webRequest.url}" );
            return null;
        }
    }
}```
However GetTexture can apparently only be called on the main thread, since to my knowledge the web request is the thing that is going to be taking up the time I thought would it be possible to run the line
```using (UnityWebRequest webRequest = UnityWebRequestTexture.GetTexture(url))``` on the main thread and then pop back?

From what I know UniTask would solve this pretty easy, but I can't use it as this is an already existing project I have just been brought on to so adding more packages isn't an option right not. Any help would be apreicaited
undone coral
#

and call it something else lol