#archived-code-advanced
1 messages ยท Page 33 of 1
I've seen my graphics engineer colleagues doing some crazy stuff with custom RPs in like a couple of days
the application is multiplayer features for streaming, e.g. https://appmana.com/watch/bonneville . there are people building multiplayer games on the streaming platform, and i'd like to support a very large number of players
Stream apps and games directly to your browser. Join the waitlist.
multiplayer example - https://github.com/appmana/appmana-unity-starter-hdrp - observe this is "just" two cameras, although a lot more sophisticated than furioos
@harsh lion here if you wanna join my marble demo room: https://appmana.com/watch/unity-starter-hdrp
Stream apps and games directly to your browser. Join the waitlist.
That's cool! Runs super smooth
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
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
well, unfortunately HDRP sells lol
I think as we go along we'll make things easier for projects like this. Render Pipelines are still growing
well once you see the editor experience for multiplayer in that sample (you just have two game views, one is display 1, another is display 2, player 3 is display 3, etc. and it Just Works) you'll comprehend why someone is asking for 10 players
I still don't quite understand how to talk to render passes from monobehaviours?
You can call other functions from the Custom Pass to pass data to your other C# scripts
oh, like setting a static member?
remind me what you are trying to do
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
yes I am reading up on that, but I'm not sure
- how to make a render pass for URP (is it different from a render feature?)
- 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
a render pass for URP is a render feature
Making it interface with a script so I can get a list of lights in the scene
you should get an argument somewhere with the lights that are visible by the camera
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
I see the method Execute() which has a proper context...
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)
okay, i got it working. Thanks!
wow
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.
I used to make a console application and โreplayโ the battle report step by step.. when I was working server side and I wanted to test it before hand it over to client
Maybe something like that is enough for your use case? Though with Unity I think you could make debug mode of your client
A console application is what the server already is, but it's .. too much information to parse for gameplay. I actually already "sink" the data out to Seq, which works great, but .. it's just fiddly to get through. I'll snip a few seconds of gameplay while tailing the output in Seq.. sec
each of those yellow texts is .. the entire state from either the server's POV or the Client
In debug mode it's about 1kb compressed - but .. obviously it's too noisy for production
Oh well I meant.. 'visual' console application.. It looked like console tetris ๐
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)
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
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"
๐
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 ๐
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}
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
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?
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.
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"
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. ๐
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?
I build shaders, renderers, games, and other stuff that's fun to stare at.
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?
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.
hey. is there any way here to fill the if statement?
if ( /* inside default physics scene? */ ) {
Physics2D.Raycast( )
}
else {
gameObject.scene.GetPhysicsScene2D().Raycast( )
}```
the GetPhysicsScene2D will throw if it's not in the default PhysicsScene
PhysicsScene2D myscene=null;
try {
myscene = GetGetPhysicsScene2D(scene);
} catch { }
if (myscene == null)
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
then use PhysicsScene2D?
sounds a bit messy... but yeah I guess there's no workaround ยฏ_(ใ)_/ยฏ
I ll have another look tomorrow
testing it right now
ok so apparently I'm dumb and it doesn't throw on default PhysicsScene
issue closed for good. โ
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.
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
Heres gameplay:
The task doc:
I would really appreciate your thoughts about it, cause I am really confused...
your repo is privqte I think
404
now should work
its not a visible repo on your account either
yup, works
I cant see what they didn't like...
Was this a big company?
no
it wasnt was it?
how realistic is the chance they used you as free labor?
I don't see anything glaringly wrong
so you think that they did use me as a free labor?
im not saying it is the case, im only suggesting that its possible
it's just so weird
I am really not able to see any way how could I improve the game.
gotta ask reddit ig
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)
@onyx blade Was wrong, they do have website. Unfinished but they do https://devhub.team/
yeah, I see
Oh god what is that website
they don't even have their "Career" page working
Do you think this company is legit?
I personally don't think they are
judging by the mistakes and general negligence on their website I have questions
It's just inhuman to do like this, if they actually did. Anyway they made me feel broken, and made me doubt my skill
I could definitly be wrong tho
but from what I am seeing, I dont feel confident they are a well-established company
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
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
thanks for the nice words:)
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
hey
I just implemented chunks into my game
But now all of the code that finds tiles' neighbors is broken
(sending more context...)
Guy on reddit just told me about that circular joystick. Somehow I just missed this part of the task, still pretty easy to implement tho. Thank you!
for example, here: the arrows show how they should be neighbores
But instead, it just ignores them
and the 2 green tiles just connect to tiles from another chunk on that side for some reason
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
The important thing is that you tried your best
use Rider
I think I'll switch, yeah
Just gotta figure out how to switch the formatting to Intelij's
and the icons
and everything
why?
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
do you have headless / backend tests for the units with these abilities?
Is it possible to get smooth transition between opposite directions in unity blendtree?
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?
for 8way movement
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.
I have never got any job, even tho I am into this industry for over 2 years. I am ready for any opportunity.
Nobody even invites me for an interview
because I need to change my shader code at runtime..
well what's the idea?
user-inputted equation, can use logarithms, raise one number to the power of another, etc.
there's really no way about it, i can't do something like that with simple variables
it's a mathematical equation graph renderer?
what is the application?
rendering fractals
you mean rendering 3d fractals?
nah, just 2D for now
yep
there's not really a method I can think of that doesn't involve editing the shader at runtime
well, yes, i would like it to be real-time
it's fully functional atm, but i need to go into the shader file and manually edit the equation to change it
is that the goal?
well not infinite
yk there are limitations because its a computer lol
and whom or what is this for?
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
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
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๐
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 ?
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
again, i'm sure i'll want to do it again in the future, and i may need to use unity for the other aspects of my project when that time comes
okay well this is the warmest lead i found https://github.com/przemyslawzaworski/Unity-Post-Processing-Mod-Tool
good luck out there
cool, thanks mate
my only feedback to you is that between the two choices, choosing the first one was the wrong one
it happens
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
it was a good idea to ask and i think you'll figure everything out, it'll be great
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.
๐คท
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?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
amountOfResourcesTotal is anywhere from 1 to 170
I initialize the resource types earlier, but simply distribute it in this loop
paste code for calculateTotalResourceProbabilityIndex()
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--;
}
}
}```
Is resourceRegistry a POCO or monobehaviour? ie - you don't have any special logic on the get for .rarity?
the rarity is just a standard float - resourceRegistry is a list of scriptable objects
no special gets or sets
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 ๐
Random.Range has both a float and an int version
calling it with ints returns an int
Oh, nevermind, there's an (int, int) override
Ok, back up then - what's system?
And what's outpostsInSystem? A list? array?
so each of the outposts is related to a central "system" class
list
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
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)
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
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
yeah
line 19 is a clusterF
so 170*outpostsinsystem
ik lol im tryna find if its in the range of one of the rarities
thanks, ill look into it
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
its long, 999+ outputs
how can i send the whole thing?
it just repeats mostly
amount of resources is an int?
yep
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
thanks, id appreciate it
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?
yeah
i randomly assign outposts to satelites, and each outpost must have at least 1 resource
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)
isnt that the exact same thing, but simply outside the while loop
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. ๐
It doesnt, good point
Appreciate it!
outposts only have one type of resource?
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
- try to test exclusively headlessly, in a process that embeds your game logic and nothing more.
- the trace work stream:
- create a trace format that is solely game actions, and check that the game state is identical when the trace is replayed.
- create a test that randomly, mass plays games in this embedded environment. use the emitted traces to start tackling
Exceptionand other programming errors - the integration test work stream:
- create a test harness that lets you play out the match in code
- test greater and greater amounts of the content you authored, trying to increase code coverage this way
(thx Dr - will review in a sec after helping this guy)
@meager kite - Outposts only hold one type of resource?
yes
public class ResourceOutpost : MonoBehaviour
{
public Resource resourceAtOutpost;
public int amountAtOutpost;
public bool isBeingCollected;
}
@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 ๐
neither to both
why?
(you're simply comparing pointers here, which is not probably what you want to do - your entire app breaks if you reload the registry)
oh fun
don't worry about it, i fix
voila
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
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"
thank you!
ill implement .equals in my classes now
i really appreciate you sitting down and helping me refractor\
One additional note - GetHashCode should return same value for same (equal) object, you might encounter issue when using hash based collections with your class
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
i only diagnose using the debugger, but in spellsource the java stack exactly matches the game stack
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
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
once you record traces in production, you will be able to reproduce them locally and hopefully that helps in the long run
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
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
this is my largest area of concern
if you are seeing invalid gameplay, you have to author unit tests, it's unavoidable. if you are seeing exceptions, mass random play will help a ton and be higher yield than anything else.
overall these seem fine to me
and make sense
Almost no exceptions at this point (it's been 20 days without a crash)
if you saw my earlier conversation with someone, you successfully did "every function has the same signature"
yeah, for the most part, although i changed the signature halfway through implementation .. so much work to refactor ๐ฆ
i assume somewhere you have Effect(string name, ...) that delegates to these
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
and gosh no, not a string, an enum ๐
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
yeah these make sense to me
i think it's all fine
so you will have this random mass play and it will be
I'm tempted to use the messagepack compression https://github.com/neuecc/MessagePack-CSharp#lz4-compression but I'm not yet sure if it's even really needed
Man, that is horrible
probably excessive for this case
horrible in what way?
horrible in that it's lots of fun and has lots of cool abilities? ๐
you dont need the switch
i mean, the abilities need to be delegated somewhere
zero reflection has many benefits
yes, in an array which matches the enums
@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
what, something like:
Dictionary<ActiveAbilityType, Action> lookup;
...
lookup[type].Invoke();
?
could be
to be fair not all of them are identical - some are async, some aren't, some are passive and so do nothing
yes - the code that sorts that all out, that glue, has to live somewhere
but I see your point, the delegation could be a bit more automated
it can live in the form of a class, a switch statement, etc. it can't necessarily be less.
๐คท 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
yeah
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
Yeah, that's my current approach - I made some "denormalized" strings to summarize the state:
but it's still super tedious to pick through the JSON
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?
I want to integrate Whisper AI to my app
Whisper AI link: https://openai.com/blog/whisper/
hmm, maybe I didn't check it well, I will give it another try
Thanks a lot for the help! @undone coral
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?
beforeAssemblyReload is still raised, isn't it?
It is not
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. ๐
that's a shame
Maybe something that is called in some onvalidate editor methods, checks for file changes, etc
Is this specifically for when files are deleted?
It's whenever the assemblies are reloaded
so generally when they get changed is when I want it firing
I'm just surprised (still) that onBeforeAssemblyReload isn't fired then
that's.. exactly what it's for
If there is compile error then assembly wouldn't reload
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?
I just use this callback for that kind thing
https://docs.unity3d.com/ScriptReference/AssetPostprocessor.OnPostprocessAllAssets.html
Do you specifically use this for automatic code gen?
before I go trying it
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
I use it when I need to generate code when asset is modified
my auto code gen happens outside unity so ๐คท i gen the code, drop it in a unity folder and unity recompiles happily
great, sounds like exactly what I want
You might wanna consider rosyln source generator as well
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
You can always filter whatever you're interested
i mean, go nuts, but be prepared to ctrl-alt-delete that sucker ๐
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
If you're doing code generation, why not just read the .cs files? Reflection is more for running and compiled code.
Yeah after 2 hours of fighting with myself I've come to the conclusion that that's the only option
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...
dont use anonymous delegates .if you want to unsubscribe you need a named delegate
so I need to store it somewhere then ๐ค
void ApplyWithArgs() => Apply(items, right);
ah, its expecting an object of type action
Action click = () => Apply(items, right);
primaryButton.Q<Button>().clicked += click;
same thing
it kinda is, but your method wont allow me to set those parameters locally
so long as you can reference the delegate from where you call the unsubscribe, you are good
you can make local methods (methods defined inside another method)
ah fair yea
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
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!
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
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
I retargetted the android studio SDK installation folder to the unity installation folder
should I have done it the other way round?
I would yeah
hmm, in taht case do you know what the default installation path is?
Also not sure in general why you need to manually install extras ๐ค
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
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?
perhaps you could map an inverse relationship from distance to angle required
at a certain distance away the angle might shrink down to 0
yeah
yea i think i got it working, thanks
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
do c# threads work in unity?
because i'm trying to run discord rpc callbacks on separate thread and nothing happens
code doesn't use unity api
Then it should work so the issue is somewhere else
C# threading works totally fine as long as you're not touching Unity Engine objects
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,
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)?
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
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
Depends on how the asmdef is set up, look at the checkboxes
I never use these
easier if i show you
rotaryheart is editor only so that should not have an impact
Yep the second one is good
If the first one is only used in Editor, then its checkbox must be checked
And nothing else
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
If you use anything that only in editor assembly you'd get error
Editor folder is same as other folders when it's under asmdef
ohhhh ok, so i need to give it its own asmdef uh
Yes
thanks for the help @jolly token & @fresh salmon
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.
where is this code running? On the main thread? Elsewhere?
main thread, but I was trying to take some long running init stuff off it
if you put a log before the await line does that print?
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?
right in the snippet you shared
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)
I don't see 6 and 7 running?
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
yep - maybe confirm with a quick (constant string) log before that line to make sure that's the issue
is there a reason you're not just using the debugger and seeing where it gets to on either
I was, but.. I don't [yet] know how to step into tasks.. the calling method just immediately goes to the next line
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
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)
you must await everything that produces a Task for the exceptions to be thrown properly
so this calling method needs to be awaited? (it's not currently)
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();
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
๐
Task would hold the exception so it can be thrown when await happen.. that's why it does not logged in main thread
But async void explicitly saying that it will not be awaited by returning void so it will be logged in that case
I blame the ligature
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?
is VS configured for unity?
yes it is, I get a unity project view
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
alright, then i have no idea ๐คทโโ๏ธ
- 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
I was messing with source generators awhile ago and had some success, I imagine it's somewhat similar.
Have you added the analyzer to csproj?
well, unity generates the csproj files automatically...
I did do the whole RoslynAnalyzer asset label fun
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.
oof, that sounds like a horrible hack... but also like sth that would work 
ironically, generated source files work with Rider with custom source generators, but their diagnostics don't display either
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.
reading that: you can just add a magic csc.rsp file anywhere with the -additionalFile:"..." line as content. works for me for source generator files ^^
I'll try the onGeneratedCSProject now, thanks for the hint!
Does that work inside the IDE too?
I thought that only adds compiler arguments to Unity.
I use that to add a json which I parse in my source generator, and the generated files show up in Rider
Interesting.
Well the entire Unity and C# integration feels like a giant hack tbh, nothing surprises me anymore ๐
same 
Hmm, the generated .csproj files already have an <Analyzer Include="absolute/path/to/analyzer/dll"/> in them
That makes sense, Unity probably sees the asset label and adds it for you automatically.
yet I can't get the IDE to recognize analyzer diagnostics
nice
Rider seems better for this sort of thing
yeah, but it's still all horribly broken ๐ at least we've got some generators running in production, but no chance for analyzer diagnostics in the IDE
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
what do you mean?
i think there is a prime31 plugin for this
"Android: Due to security changes in Android 7.0 (More information), Application.OpenURL can no longer be used for opening local app files, you need to use https://developer.android.com/reference/androidx/core/content/FileProvider which allows you to share files with other applications."
"iOS: Application.OpenURL cannot be used for opening local files."
i think check for a prime31 plugin
Ooh neato thanks mate
Hi there, how do I convert an .apk or .zip file to a unity project?
don't crosspost
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?
this was already discussed in another channel
Im just trying to re-upload an old appstore game that was taken down 2 years ago
The owner of the game does not care whatsoever
Other people have done it too
this is neither advanced code related, nor allowed to be discussed in this server
Apologies, I was just answering his question
So you're taking a game someone else made and trying to upload it to the store with your own account?
Sounds like that'd probably violate some TOS rules and be counted as plagiarism
The owner does not care whatsoever
He even went ahead and let other people do it
there's a mediafire copy of it
I can send you
its an .apk
If others have done it and it's already on the store, then why do you need to?
They didnt upload it upon the store, they give you an apk file that you can launch
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
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
Its already converted into an .zip
and yet its still not a unity project, funny how that validates exactly what i said, right?
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
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?
if you're using rigidbody2d for collisions you're going to want to either AddForce or set velocity for side-to-side movement for it to play nicely
can you load androidlib with resources only (images) at runtime?
wdym androidlib?
please, help! any idea if it is possible to combine multiple PhysicsScene into a single one?
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)
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
ChatGPT is wrong, if it can go in a list it can go in an array and vice versa
The C# Discord's help channels are also not closed
hmm
Imagine looking in the archive and expecting to be able to post things in there
Help 0 is also open
Anyways, chatgpt is not to be trusted
oh it was scrooled down to archive ๐
that is forum and i prefare chats like this
I was just correcting the incorrect information
The C# Discord has open help channels
yeah help-0 is not but the one which i was redirected from archive was forum
anyway, thanks for help, i think chatgpt is wrong too, i just wanted someone else confirm it too
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
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??"
It already is unfortunately
ChatGPT is not only wrong at times, when that happens itโs also wrong very confidently.
but 1+1 is 3
Hello, can someone tell me why I get this error message as soon as I use my shader on a material? https://prnt.sc/6EClTj1qpVt4
I'd say share your shader code and this error in #archived-shaders
Okay thanks
you can read the list implementation in C# and see that it's not doing anything particularly fancy, it's pretty much just a wrapper around an array: https://referencesource.microsoft.com/#mscorlib/system/collections/generic/list.cs
has there even been talk about getting unity to support z=up?
There has of course been talk for many years. I wouldn't hold my breath on it ever happening.
y=up is the correct way anyway, don't @ me
Stop relying on ChatGPT
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.
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 ๐
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();
no
You can do it with source generators.
Might be a bit overkill though unless it's a pattern you use a lot.
its a useless pattern
you can just do ```cs
public interface IFoo
{
public void Execute();
}
List<IFoo> items;
items.ForEach(it => it.Execute());
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.
this sounds like the definition of composite, which is sorta of what Anikki's code does except you hide the fact that there are multiple things by creating an implementation of IFoo that takes a variable number of other IFoo and then runs the loop on them
how do you add a signature of a method form a classes generic parameter as a method on the class?
Extension methods.
You can write a source generator that analyzes the call you want to make, and generate an extension method matching the signature.
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.
adding source generators was such a mistake, loads of stupid ideas that people are now finding ways to realize
Adding that feature to C#?
public void CallForEachT<T>(Action<T> action)
{
foreach (T subscriber in GetSubscribers<T>())
{
action(subscriber);
}
}```
Stopped on it for now
you can also do it with reflection but its still a silly idea
It's far from a stupid mistake, it's an amazing feature that enables lots of previously impossible patterns.
thats precisely why its stupid, too much power, too little control
also it makes the answer to all questions "yes"
which is not helpful
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.
"very much" being debatable
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
anyway, i'm not against source generators i'm against using them for obviously silly ideas
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.
all the problems in programming stem from programmers using stuff/patterns/paradigms they don't fully understand the consequences of
Every your message sounds toxic to me, I'm out, sorry
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.
Reading back, I think you chose well ๐ Some people see donuts, and others only see holes XD. I think you are on an interesting path to simplify your workflow, and I'm interested in seeing other peoples solutions to it as well.
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
Thanks, will try it out soon
I'm using 2022.2. In docs (also 2022.2) it has this https://docs.unity3d.com/2022.2/Documentation/ScriptReference/SceneManagement.PrefabStage.IsPartOfPrefabContents.html
But it's not coming up in code. Do I need to add an additionally assemebly def for this?
Too much praise for me
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?
Anyway for now I got this, tho name of the lower method looks too long
Perhaps I should introduce a metaphor
nope, i have worse
the more important it is, the longer it gets. that way it's easy to find it from a single glance ๐
I think it's a little better this way
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
Is it a unity app? If so, you just use the update of a MonoBehaviour afaik.
a c# application console for server
Then I'd suggest asking in the C# discord
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 ?
Ask in #๐ฑโmobile
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?
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.
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?
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
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?
Let me run that test
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
- do nothing (GC will collect mesh and finalize it)
Destroy(ask nicely to destroy something by the start of the next frame)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.
I'm just about done setting up a test case I can use to see the memory usage in the profiler
@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
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?
you have to profile the standalone player
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?
Hm... it'll be harder to test in standalone, I'll need to find some way of putting this script on a single chunk, I just manually added it in play mode to test
that will also cause misery. you will have to explicitly free those
I do not know what this means
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.
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
how much did creating the mesh increase memory?
Quite a bit more than was freed
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
are you visualizing a microphone or an audio clip
audio clip
okay
have you looked at this - https://github.com/keijiro/WavTexture
the docs say GetRawTextureData doesn't allocate memory and that you shouldn't store it anyway. Also, I question updating a texture in FixedUpdate
@ember nexus what is your goal?
I saw it, but I don't understand how his code works exactly (cursorly glance) and it looks like he's drawing a mesh in Update(), he also mentioned that it was bad to do it for realtime audio kek
No, an audio channel
what's the objective? what is the game?
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
okay
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?
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
okay
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
Here's an example
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
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*
Thanks, I'll have a look. Can you explain what you mean by turning the texture into art using shadergraph?
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.
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
ou don't need a compute shader
you dont' need any shaders
you need to use shader graph, which is a visual tool
I know shader graph, though i've never used it yet
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
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
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#
I see, so it has to be stored inside a Texture object in order to send it to shader graph
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
That's why its not just stored as a float array, like it natively is, and then sent to shader graph
Oh, okay.
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
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
I'll try your method, I have no idea wtf i'm doing though, but I guess i'll have to learn shader graph either way
Thanks for your help
in Burst, if an exception happens inside or outside a try block, the exception throws as if any finally blocks do not exist.
https://docs.unity3d.com/Packages/com.unity.burst@1.8/manual/csharp-language-support.html
Is this just meaning "Burst do not supportfinally, only let you write one"?
yes
it doesn't sound like Burst a/k/a "HPC#" supports finally
Yeah I'm okay with that but that documentation is weird
Does anyone have an implementation of https://docs.unity3d.com/ScriptReference/Networking.CertificateHandler.ValidateCertificate.html that validates certificates like built-in?
base doesn't provide an implementation, it's hidden on the native side.
I want to debug my 2d gravity field to see how big the range is, can someone help.
After wrestling with it for a while, I've come to the conclusion that CertificateHandler is probably designed for the purpose of validating custom cert only and not for full chain.
For reference the problem I'm trying to solve is: https://forum.unity.com/threads/curl-error-51-cert-verify-failed-unitytls_x509verify_flag_expired.1176929/#post-7548508
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.
What PrefabUtility method will allow you to input a game object instance and get back its Prefab asset?
Gizmos?
If Gizmos isnโt an option. Try DebugExtensions from Asset Store. Itโs free and easy to setup/use.
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?
Sounds like it's not wrapped in the directive tbh. It wouldn't be compiled if it was
Looks like you didn't wrap the using directives
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
Ah. I see. Iโll just make a partial and wrap the whole thing instead. Thx.
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.
It really depends on the access patterns
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.
Lazily loading?
yes
What's the difference with loading ?
Thanks
that article is in the context of a website with JS but the concept is the same
Ok, got it. It makes sense indeed
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 ...
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?
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?
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.
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
Is keeping the XML tree in memory heavy ?
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:
Never keep someting in memory you don't need to keep in memory. It's wasteful.
Ok
Just look how pissed off users get when programs use unecessary amounts of memory
After magical numbers:
Is anyone able to help me with that?
Looks like tiling issues
Just lookup how to make perlin noise tileable
I did, but couldn't find anything helpful
And more I found with a short search
The first one is in a language looking like python, doesn't help, and makes it overcomplicated
The second one is also not answering my question.
I really just need to know how can I make it tileable.
Then understand what he's doing then write it in c#/HLSL, I don't understand your complaints
But it is far too complicated for my needs. I really just need to understand how to implement offset for perlin noise based on "tiles".
Am sorry, I don't understand
What don't you understand? What I am trying to achieve?
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
@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
Do you know how I could implement that blur over two neighbors
Nope, but I'm sure that joining the 2 images and applying blur at the right place will be possible
But I simply don't know how. I wanna implement infinite procedural terrain generation, I really just need to get the smooth transition between two neighbors with perlin noise working.
Am sure you can find info in Google about it
Hi. I want it to continuously increase and decrease a float value between 2.0f and 6.0f. What should I do?
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)
Could you know mark the lines
yeah wait a sec
But I'm guessing your array math is wrong and its out of the bounds
then how would i go about fixing it
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).
Addressables.InstantiateAsync(addressableName).GetComponent<T>() is what you mean right?
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?
those packages do not directly let you blah blah blah
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
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
you can call .SetTexture on the material using the sahder
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
create a texture property in shader graph ๐
you'll figure it out
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
what are you trying to use source generators for
what is the goal?
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
You can also turn on EmitCompilerGeneratedFiles to persist the generated files and examine them.
?
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
ah cool, is there an easy way to use this vscode-omnisharp/unity?
weโre building a third person character controller w/ state rewind, & the character state itself is a wrapper around a buffer of n state frames
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
(iโll do some digging around on my own in any case, thanks for pointing me in the right direction!)
What issues are you having currently?
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
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.
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
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.
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?
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
in addition to the simple way of modifying the string TMP gives you full access to generated mesh and limited meta information of how it layouted the text, you can use that transform the parts that represent line 3
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
hmm, so you're saying you're making some kind of multiplayer game
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?
just not a great workflow for debugging issues with the source generator,
there are a bajillion reasons why hardly anything people like to use has macros, and why they're pretty radioactive
I just make my source gen to emit Log.cs with bunch of comments ๐
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.
yeah this is the route weโre taking too.
Also Rider has definitely better UX for source gen ..
Compare to vs code
yeah :/
i see well i'm sure it'll all work out
Is there a way to register MonoBehaviour that is created in a file that does not match type name?
so it appears in Inspector
No
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?
How to get a callback when a value is changed in the Inspector of a ScriptableObject?
Custom editor scripting or an off the shelf solution like https://dbrizov.github.io/na-docs/attributes/meta_attributes/on_value_changed.html
is there no OnValidate for ScriptableObjects?
There is
But it doesn't tell you if something changed
Nor what changed if something did
hummmm.... think I'll write my own checking rather than import anyone's code. CHEERS!
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
Isnt this looping forever in your DealDamage void?
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?
_continuousDamageDealer != this
Okay, so every damagedealer has another damagedealer in itself. got it.
From the code, it looks like its a round based thing?
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 ๐
Yeah I was
Someone in another channel suggested using callbacks instead of events
But I don't how's it any better
The game is a 2d platformer
Like mario, but with ability to hit
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."
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 ๐
I will upload the code to github and tell you in which folders to look, are u fine with it?
Yeah sure, why not. You could also use hatebin for quick pasting ๐
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?
Not sure on what part this would not be possible? did you try it or have any reason to question the possibility?
Been trying for past week, its my first real project and im struggling so im resorting to asking for ideas on how to approach this mechanic.
what were you struggling with? Need some more context to get the gist of your setup ๐
Attack related scripts are located here and here
EnhancedDIAttempt/Assets/Scripts/PlayerActions/StateMachine/States/Behaviours/Actions/Attacks/
EnhancedDIAttempt/Assets/Scripts/AnimationInteraction/ContinuousAttackAction/
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?
Just tried to get into your code, but I only can jump in and out right now. If I got time later, I try to look into it again.
Sure
perhaps #archived-dots ?
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
dots channel is way more active than this one AFAIK
ok will try
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?
If I understand your question correctly, then I think you can achieve what you're looking for using the progress property of the AsyncOperation returned by SceneManager.LoadSceneAsync. I don't know if you can get the number of resources, or the size of them, but it will return a percentage representing the completion of the entire load process.
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
I see, so you're trying to determine whether the load time is long enough to justify a load screen?
Yea, exactly. Sorry for my language XD
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)
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.
Actually, yeah. The frame count check will be the treshold that satisfy needs
Thank you @wide bolt
good luck
@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.
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
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
that's a good question. But it has one advantage that you can just swap it in real time with ease
But clearly you can't just swap them
Otherwise you wouldn't be here asking this question
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
Are you talking about input controller from builtin unity or a custom one that just handles movement?
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?
list.Remove(this)?
Does this work? If so, how does it work?
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
So it's effectively a hidden for loop rather than self awareness?
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
Unless you have thousands of instances, the latter is probably better because of the hassle of having to ensure consistency
Cheers! Will leave it be, then, and hope that my worst case ( a few thousand, rarely) isn't slow when pulling objects out of this iteration pool... it's a list for manually calling updates on the objects in it, and once they're "retired" they'll need to remove themselves from the list
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
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.
copy and paste the code out of unitask that achieves this
and call it something else lol