#archived-code-advanced
1 messages Β· Page 190 of 1
OK, do you include data inside that package? How do you fill it?
Do you change that data asset after importing in a project?
huh?
like make a concrete example
i have no idea what your application is
you haven't given me a concrete application problem
which is
anyway
i don't know, i guess use zenject. it's a bad idea
you haven't answered my questions for the most part
i use and author a lot of packages, used by a lot of people, in unity and other programming languages
I said, in one project the base url is www.example.com
in another project, it is www.example2.com.
In the custom package, some classes need that base url.
One way is to include server data in the custom package and according to the project, change the value
it just seems completely and utterly obvious how you would have two different baseUrls for a client API in two different projects
i must have incomplete information, or you have really dug yourself in a deep, deep hole
especially since your examples are configuration
the app store example is the only one that sort of makes sense... but it still doesn't, because somehow unity and a dozen othe rpackage authors have achieved an app store interface for some use cases that doesn't need dependency injection
Totally, changing data asset inside a package is OK?
Suupose it is an IAP package
This IAP package needs a base url defining based on a project
are you asking how to pass configuration to a piece of code?
var myIAPInstance = new IAP(baseUrl: "https://www.example.com");
and i suppose that url could come from a configuration file? that can be achieved many ways in unity
i use microsoft configuration
this is what i mean by obvious
so i don't know
you're introducing zenject to save someone the trouble of what exactly? having to write 1 line of code?
you could provide default configuration. input system does this
there are lots of packages that do this well
anyway
i would run by this decision with the people whom you're making this for
you've been at this for
almost a year
it sounds like your editor tool is a simulator for app stores?
i don't wanna razz you too much @timber flame i'm sure this will work out
Tasks-unitadks yes or no:
After a few months developing for unity iOS platform ive seen tons of exceptions caused by non awaited tasks
Im starting to think thats not a good idea to use tasks for everything, just for the parts of the code that really need it and cant be resolved with coroutines
Im sick of getting system.aggtregate exceptions for stuff like this
So, whenever possible, donβt use task/unitask
unity is NOT thread safe, if you have heavyy lifting use DOTS
and good luck with iOS...
π
hey i hate to ask repeat questions, but something yesterday didnt click
UnitBehavior unitBehavior = objectModel.GetComponent<UnitBehavior>();
GameObject objectCreated = new GameObject(objectName, typeof(UnitRTS));
objectCreated.AddComponent<objectModel.GetComponent<UnitBehavior>>();```
UnitBehavior is an abstract class
I am attempting to get the specific abstraction from another reference, and then instantiate a new game object with that reference
this does not compile
i know
how do i achieve this?
Type type = objectModel.GetComponent<UnitBehavior>().GetType();
objectCreated.AddComponent(type);
oh i didnt know GetType existed
would that give me my base class, or the specific abstraction of it?
GetType gets the most derived type that inherits from UnitBehaviour
whenever your type is not known at compile time, you cant use generics
so you need to use the AddComponent overload that takes a (runtime) type argument
You can just hard cast it
looks like a horrible hack but it works perfectly haha
check if the destination is within it's attackrange - 2, it might be the cause it wont move since you've set the navagent stopping distance with attackrange - 2
yep. you got it right on the head! the stopping distance was the cause
I am tryna reference a sprite renderer from a script and its not appearing in the editor when i load the game!
How should i assign it
dont cross post
Dont crosspost
This head is an NPC
Dont crosspost
Do you have the answer
[SerializeField] private SpriteRenderer _sprRenderer:
[field: SerializeField] public SpriteRenderer SprRenderer { get; private set; }
public SpriteRenderer SprRenderer;
Lot of ways
Of doing it
Just take a quick look into the unity docs / unity learn
I know this is a simple answer, but it's late, my brain is fried, but I want this done tonight. I can't remember how to figure out what a value is, based on a percentage between two other values.
x = 33% between 20 and 290.
For example
x = y% between a and b
x = 33% between 0 and 100
x = 33...
But I need to calculate that based on different values in the y, a, and b slots.
Maybe you are looking for inverse lerp?
Ig just regular lerp
Not trying to do any lerping here I just need an equation.
Yeah, cause your example seems just to be lerp(20,290, .3)
a+y(b-a), thats just lerp
π
Yeah. Time to call it a night. Over here trying to reinvent the wheel. Thanks you two. π©
if you ever forget, you can just figure out the line equation
y = mx + n
and make an equation system with points a and b, replace, then figure out both m and n
I'm trying to implement a tag system for character abilities. The goal is to have something that works like this. A tag of Ability.Target.Self. I want each portion to be filterable. I.e. it has the tag of Ability, Ability.Target, and Ability.Target.Self. How would you go about setting something like this up?
Sounds like you need to be using interfaces.
I'll start digging that direction. Thanks.
interfaces, virtual classes both should work
Agreed. If it's just the one thing (Target) than simple inheritance should be enough. ...but if you start tacking on different things for different abilities @severe grove, that you want to be able to use across multiple abilities, you'll have to tap into interfaces.
I mean link it to the variable so it automatically finds
What is the difference between ScriptableObject.Awake and ScriptableObject.OnEnable?
Effectively nothing iirc
Might be that awake is called first on all SOs and then OnEnable is called on all SOs
But that's also not reliable in all cases since (at least) OnEnable is called when you select one in the editor iirc
Those distinctions don't matter to me. So long as I can guarantee the code is run before any access to the object.
It should be iirc
Thanks for clarifying. π
i have a routine to find the time with ntp
calling it on a thread
is it possible to get an exception like this one with a thread?
or that belongs exclusively to some task?
You mean you want that exception where your thread is started?
nono, i mean if this type of exception can be caused because o a thread, not a task
Im doing this
since the stacktrace doesnt give me the source o that
i wonder if this kind of call could cause a Task.Aggregate exception
I'ts not a task so... i guess it doesnt belong to this right?
Anyone know much about custom yield intructions? I'm curious about layering coroutines rather than just nesting them. I want to make a yield function that will wait for another coroutine to yield. So for example I could have some complicated lerp coroutine that when yielded, then lets a callback coroutine resume. Very niche and probably a bad idea, I know, but I do think it could actually be pretty useful and it's interesting. How could you make something like this.
Events instead of Coroutines
oh wait you wanna yield during the coroutine and callback another one inbetween
yeah seems like a bad idea for future you
It does but like... what if though?
I never tried because it's baaaad design. So I'll let others answer
(sorry for zero help)
I doubt many have tried it π
I did something similar, but I used a Func<bool> that I would call from the second coroutine passed in from the first one, to check if it can continue, basically waiting for the previous to end.
My usecase was async loading a scene, but then waiting until an animation finished before actualy activating the new scene.
// First coroutine
IEnumerator DoX()
{
bool isReady = false
readyCallback = () => isReady;
StartCoroutine(LoadX(readyCallback));
// Play animation
// Animation done
isReady = true;
}
// Second coroutine
IEnumerator LoadX(Func<bool> ready)
{
while( !ready() )
{
yield return null;
}
}
Something like that, don't have editor here
I dont think its such a bad idea, but reminder you can yield coroutine in another coroutine.
IEnumerator firstRoutine()
{
yield return StartCoroutine(doLerp(1,2,3));
//Done after the lerp is done
}
That would be nesting. So one then the other. I'm looking for layering them, so one yields, then the other goes until it's next yield.
Not quiet what I maen but that is a way cleaner way of doing something else I've got.
IEnumerator routineA()
{
yield return new WaitForSeconds(1f);
yield return new WaitForSeconds(2f);
}
IEnumerator routineB()
{
yield return new WaitForSeconds(3f);
yield return new WaitForSeconds(4f);
}
IEnumerator pingPong()
{
var a = routineA();
var b = routineB();
while (true) //TODO: Break out of this when you cant move next. Currently infinite loops!
{
if (a.MoveNext())
yield return a.Current;
if (b.MoveNext())
yield return b.Current;
}
}
I think this would work.
Although you are indeed getting into moderately dodgy territory
Interesting use case π€ (I would still handle this with events though, for coworkers and future you sanity's sake)
Yeah, I removed it since, but had it in production for a while with no issues π
π
That definately looks more like what I was after. Thanks, I'll have to play around with this.
You should definitely look at async/UniTask if you need stuff like that
Hi
I need to use some JSON
I coded that class to use it
(we obtain the json by calling the line 26)
and the json looks like that : https://cdn.discordapp.com/attachments/473873090426961950/976415897138921542/unknown.png
how can I use that in another script ? How ???
Your class structure and JSON structure don't match
Oh
how can I fix my class structure ?
You need more than one class. Each {} in the json represent a new object. Each [] represents an array of an object type.
that sounds so complicated
like
I need a class for "pistol1" etc
and a class for ForceTube 31321321 containing the name and battery
is that right ?
You need a class with a batteryLevel and name
No, ForceTube 31321321 is a string, not an object. It will be a string field in whatever object rifleBolt represents
You can use this tool to convert JSON into a C# class representation
https://json2csharp.com/
Convert any JSON object to C# classes online. Json2CSharp is a free toolkit that will help you generate C# classes on the fly.
Just remember to enable "Use Fields", since Unity's JsonUtility expects fields.
oh amazing
Also, the json you give shouldn't have any empty arrays, like the example you gave us
There's no way to know what kind of object can go into "other", "pistol1" or "pistol2"
the json isn't smthing I can edit
it's generated by code one of my predecessors in the company wrote
Do you intend to ignore those fields in your code?
Then it doesn't matter
the fields are emptied or filled depending of IRL manipulations
so smtimes it'll be empty
The tool will generate a List<object> field for those empty arrays, which you can just remove after copying it.
i see
I'm absolutely losing my mind. Once again I'm having troubles passing a function as a paramater because using Action will actually just make a copy of it so it doesn't work with subscribing to actions. Got told this was actually just a unity problem, if not a coroutine problem, and I'm too frazzled to tell what's real anymore. Anyone know what the deal with this is?
Here's the method, to show what I mean.
private IEnumerator OvershotLerp(SlimeHumbleObject hexagonObject, LerpContext context, Action OnLerpFinished) {
yield return StartCoroutine(OvershotLerp(hexagonObject, context));
hexagonObject.MovementFinished += OnLerpFinished;
}
And an example of calling it. (OnLerpFinished is just some void function).
StartCoroutine(OvershotLerp(trackedHexagon, context, OnLerpFinished));
OnLerpFinished won't actually get called at all. The one passed in becomes a copy or something equivelent, and so basicly useless for this.
the easy fix for this is,
Action afterOvershotLerp = delegate() { hexagonObject.MovementFinished += SomeFunction; };
then pass this action to some method and invoke it in that method to subscribe to a function directly instead of subscribing to a copy of it
That would work, thankfully, but still. Do you know if this is a Unity or coroutine specific bug? I remember showing it was a C# thing before, but having a little online compiler up now it doesn't seem to be.
its a thing in c# itself.
normally to pass an action and to subscribe within the passing function, you pass it as ref Action
but since its an IEnumerator, you cant pass in a ref.
But then how come this works without ref?
I wrote that expecting Test2 not to get called, but the console says otherwise.
Because this fails at doing the same thing.
Pinging you just in case you need it.
Your subscription happens after returning from the coroutine
its my imagination or this this just gonna loop forever?
As in intended. The Coroutine started in there starts another one before exiting out.
Different paramaters π Maybe should rename that though.
are you completely sure you are actually reacing that part of the code when you subscribe?
try adding a breakpoint or a log after the subscription
I dont think your issue is the subscription itself
as a side note, for this kind of lerping behavior you might consider using a tween engine
would save you a lot of headaches with callbacks
I tried. It doesn't have the kind of behaviour I want π
Or at least, by the time I figured out a simple way to do it, this was already setup.
are you invoking the method afterward? Are you sure you dont have something desubscribing the event (something that uses = for example so it deletes all other subscriptions)
The only thing that unsubs it is the method it calls, so definately not that. Other things do run off .MovementFinished too. It's actually what made this problem so hard to find, it'd run something twice since this in part controls unsubbing something else.
hmmm yeah I think this might not be a sane workflow, for all purposes that should work
This isn't the first time I've run into subbing problems. In fact, in OvershootLerp, this monster is found.
I really, really hate passing Action around. This was the only way I could get this to work.
yeah no I think your architecture here is the issue, you might have some kind of race condition going on
hard to tell
I think my use case is fine. I have the same lerp to run, with one of two methods to sub to at the end of it based on what's running it. Maybe it's a little odd to need to sub late into it, but the lerp consists of two shorted lerps so there's no easy way to do that ahead of time.
I think your issue comes from passing the action around
you dont usually do that
it's different to have an action be defined in a class
than passing in that same action as a parameter
Nope, but like I said, I can't sub to it at the start since it needs to sub to the second lerp in the sequence.
I remember before having it chain onlerpfinish into new lerps but that got fucky.
Got it, I would really need to see what your rest of the code looks alike, I cant tell the problem from this snippets
This is pretty much an animation. Lerp a little to one side, tell the expressions system to do something, lerp back.
from what I can tell here, you are basically replicating the functionality of a tween engine
The lerp itself is complicated, since it has a very consisent accel and deaccel. I couldn't tell how to do that with DOTween, but that's a seperate matter.
you can call update functions on tween engines
you arent limited by what the engine provides
LeanTween for example has an OnUpdate method that accepts a custom function and will run it constantly until the tween is done, passing as a parameter the current tweened value and optionally a ratio (the % of the tween done), you could still use your custom lerping with this
LeanTween.value(start, end, time).OnUpdate(customFunctionUpdateHere).onComplete(functionToCallOnComplete)//Can keep chaining things
from what I can tell, this is what you wanna achieve
π€ I'll have to give it another look. I intended to do it later as some cleanup but it looks like it'll clean more than just the lerp function I made.
If you go that route dont doubt at pinging me if you need some guidance
I stopped using coroutines almost entirely after switching to tweens for UI/Animation related stuff
Thanks. I didn't like having to make a maze of lerps, but at the time I had no idea how to make the lerp properly in the first place. I learnt a little physics, and now it's small and easy I should learn a little of DOTween to add that functionality.
what is your objective?
OnLerpFinished (really, MovementFinished) isn't getting called anywhere in this code, so it's unsurprising it is not called
can you show the code where MovementFinished is called?
He said he has an invoke after the first coroutine invocation
Does setting and unsetting a objects parent take up more or less resources then instantiating a new one ?
he probably is invoking the event before he has added the action to it. i mean, what else could it be
what is your exception?
it's confusing, because there's a lot of little things that can be wrong with this code
it sounds like you've assumed where the error is and have posted tiny snippets of code that don't even contain the line where the error would be happening to begin with @final kindle
yup yup, there might be other weird stuff going on either but I cant tell from the snippets
but what i can say for sure if that the functionality that he wants is just reinventing a tween engine so I would suggest going for that route first π
I posted the relevet issue. I know exactly what the error is. The question was never about the error. It was about how to handle passing an action like this, which is why I only gave what was relevent to what I wanted to know. You can tell me the a b problem if you want, but if you read through the actually nice discussion on it with Nyx, you'll see I do plan to do that later. i.e. once I've got this working enough to use.
are you using regular Task or UniTask
tasks and threads aren't the same thing
i think that's a pretty common misunderstanding
I prefer LeanTween tbh
Once again I'm having troubles passing a function as a paramater because using Action will actually just make a copy of it so it doesn't work with subscribing to actions.
You assumed this, and you could've been directed towards why it's actually not working because you've almost certainly got a syntax error or misunderstanding on actions somewhere else in your code - if your intent is to post some vague open-ended question based on false assumptions in the hope someone jumps through the hoops in explaining why you're wrong with the least information possible, that's fine though - but you clearly haven't really learnt what the issue is still, only received guesses at workarounds π€·ββοΈ
DOTween seems to be the thing other package authors have settled on
for support
Yeah I hear a lot of people use it, I settled on dottween to how easy is to work with
it will get called. i was assuming that you were talking about later unsubscribing the event using the same function from which you created the delegate
You dont really need LeanTween support, it is really simple haha
I shipped a game with it with no issues at all so I am vouching for it π haha
Why oh why do you think I've only assumed the issue? Do I need to make a thurough list of the things I have done to prove it's the issue? Can I not just ask a question about passing Action's without it being insisted some other question gets answered instead?
one 3d party asset was using tasks, it was throwing non awaited agregates exceptions like hostnotfound or dns failure, i changed that one with a script that checks the utc time using ntp, sockets with ip address and threads, im still pending of approval to see if those exceptions stop
Another 3d party asset was using unitask, now is disabled
@final kindle passing an Action to a method doesn't make a copy of it. based on that error, it seems reasonable to ask you for the code. this is the last say i have on it until i see it
Better question yet, how are you so confident what my issue is if you think I haven't given enough information to properly answer how to fix it?
which asset was it?
i see what you mean
it sounds like there was some buggy stuff
in general
The main problem is I donβt see the source in the stacktrace
Because we know enough about the Unity part of the code so we know it's not unity
it is indeed your code
we just dont know where
because we only have snippets
with the info provided, we know it is you at fault, just not exactly what it is
your objective is to interact with an NTP server?
One was anticheat detector, has a method to query the utc time based on webrequests
hmm
anticheat in the sense of, you have a need in your game to prevent the user from modifying local system time?
Another one was unirest, an api to communicate with a sql database, this last one was using unitask
you don't need a time server for this. you can hit a URL like this http://worldtimeapi.org/
World Time API: Simple JSON/plain-text API to obtain the current
time in, and related data about, a timezone.
I've done this song and dance before, several times, as I've mentioned. When I subscribe an action that's been passed via ref, it does not get called. As seen by my mentions to it reaching that part of the code, and by MovementFinished indeed running, and by nothing being able to unsubscribe it, and as by seen by that whole monsterous waituntilevent class that exists because I've done this whole thing before. So please, before I completely lose my wick, could you not be quite so arrogant in asserting I'm just assuming everything and asking bad questions, at least when it seems like telling me that is the thrust of you responding at all.
Yeah but for the moment i was just using 1 particular call to get the real utc time
unirest... hmm
you want to communicate with a sql database using REST?
Now disabled
are you familiar with postgrest?
if you want to interact with things this way, which i recommend only if you are sophisticated, you can read about row level security and postgrest
you can use supabase which provides these things for you
To comunicate with postgresSql?
yes
is your goal to interact with a pre-existing API you've authored?
or to interact with postgres over HTTP?
Unirest seemed An eassy way to do this
I will when i go back to the laptop @undone coral
I appreciate your interest
I'm happy to be told my code is wrong and that I've misunderstood something or that I need to show something else for the question. This is not the way to do that. Especially after Nyx had very kindly gone through it with me and both helped me with my little work around, but also showed me how I should very much refactor this to avoid the problem entirely.
Hey guys, if my compute shaders work on both dx11 and dx12 is there any reason why it wouldnt on vulkan?
each graphics device has its own limitations
as do the specific platforms, like android
hm, i cant find any good resources for the differences, everywhere i find seems to say they should be mostly the same when programming for. do you know of any resources that could point me in the right direction?
this is the tool thats not working in vulkan
Hey guys, I am creating a primitive database with CVS. Is it possible to write to CVS file from unity or even better, runtime Android or iOS?
do you by chance mean CSV? What is your goal exactly? Naturally you can write any kind of file from unity.
CSV indeed. I want to create a food database with nutrients.
a csv is just a text file
so yeah, you can
there are dedicated xls/csv/excel libraries too for C#/unity if you are into that
and why would you want to use CSV? its a very inconvenient format, you could just as well serialize to Json
I want something that I can build from scratch. You can recommend something else too.
any reason for building it from scratch?
Practice. Doing it to expand my GitHub portfolio.
what exactly is that supposed to demonstrate?
i mean, what do you want to implement on top of that CSV file?
in terms of a database
Read and write custom objects to database
a fully fledged database like postgres is around 2 million lines of code, a key value store like redis is 20k lines, a CSV parser is like 5 lines.
It won't be anything production ready, just a practice project. Read and write data, then save it.
thats not a database
thats writing a file or serialization
alright, so for that purpose i'd pick a slightly more interesting format
something that also has a feature that makes it useful, like say an INI file
or something that supports multiple tables
could just be an extension to CSV, a syntax you come up with that allows multiple tables, but still compatible with basic CSV
this is way more interesting than "hey i added the 10000000th trivial practice project that nobody needs"
Is JSON achievable from scratch? I don't mind using JSON utility
yes, json parsing is fairly simple if you don't care much about performance
its the most achievable of the "proper" serialization formats
I used it before with firebase but how could i achieve the same locally?
what exactly? write an arbitrary c# object to a file as JSON?
Yes
then yeah, JSON is your best bet
Like where would the JSON file be stored?
anywhere you want
Unity boasts about security but in my experience you can write anything anywhere on the disk lol
you arent limited to the applicationdatapath if thats what you are wondering
well first you have to limit the scope of how well you want to replicate that C# object, for example deep serialization (of referenced objects) is way more work than primitive types
It supports mobile?
that might be different
I havent tried it personally
I know android file access is a lot different than windows
Nyx, why are you hijacking this conversation?
I will use the database for my calorie counter app too
what does that mean LOL
you are not contributing anything but confusion
Either way, you should be able write to the app data path, and it doesnt matter what you are using, csv, json, you can write to that location on any platform
if you are using simple data structures you can use something like JsonUtility or SimpleJSON to achieve it
I know Jason utility
Used it a lot
Just didn't know I could create JSON locally
So that's how I ended up with csv
So it's okay to call it database?
It's not a large database but it still stores data
yeah thats just a database by definition
it doesnt matter if its a sql database or a csv file haha
Does this look like accurate testing results? it appears the regex formatting is the fastest initial but slowest overall
what exactly are you testing?
message formatting and splitting into different variables
A tool for sharing your source code with the world!
whole testing code
you testing for performance here?
I assume ticks is cycles each operation took
mhm
Thank you both for the help!
im doing 10 tests per type of formatting, each containing 2 string message calls
it makes sense, regex operations are more expensive
string operations should always be faster
huh..
so spending so much time on making the regex one was pointless
is there anything faster than the substring/indexof stuff?
Slice should be faster
how does that work
similar to substring
I am not sure how fast compared to what you are doing tho
if you ever wanna search for performance, try googling benchmakrs, I found a couple that way
also there!
*might be different on unity tho haha
any reason you are looking this deep into optimizations? Working on big datasets?
twitch integrations, chat messages
theoretical floor of hundreds of messages per second
makes sense
on top of it executing and checking for a command list, it gets big
Hey there. Not sure if this is the correct place to put this but I have previously been using Application.OpenURL to open a separate application. Recently I've found the need to send information from my current running application to the next one so I opted to try to just do it using the Process class but I found after debugging for a little bit that Unity's IL2Cpp doesn't have an implementation for the Process class. So, basically, does anyone have any pointers as to how OpenURL works at opening an exe? I understand that the IL2Cpp won't open it because it's literally not implemented but how come OpenURL works fine for this purpose (though typically not recommended) and if there are any known work arounds, please let me know. If ultimately it cannot be done, I can just offload my arguments to the network and handle it further down the line. Thanks.
@rocky mica so slice literally does the same as substring?
but its slower π€
but also uses a lot less gc lol
haha yeah, it doesnt allocate
but tbh that might just be dotnet
I would test it on Unity's context
either way, substring should be your way to go
my issue with substring is that
wel maybe its not substring but indexof
startString = "display-name=";
splitPoint = meta.IndexOf(startString) + startString.Length;```
i need to .Length the damn searched string part
otherwise it gives me the index of the very first character instead of the end
and its doen 3 times
per message
more if i end up adding more metadata read
Hey ok so I'm making a K-d tree and I'm almost there. I am writing the closest point method, but I can't quite conceptualize the "walking back up the tree" part of the algorithm in my brain. Can someone put it in real simple terms for me? The computerphile video doesnt help.
Also I get why we walk up the tree just not really, how
my last attempt created an infinite loop
just use regex until you actually need to wrestle with optimizing, thats what it is for
i already have the substring lmao
which is better and a lot easier to read imo
i just want some optimizations for stuff like meta.IndexOf(startString) + startString.Length
do your nodes have a reference to their parent?
They do. I figured out I needed that
then you'd just use that reference to continue making comparisons in the neighbouring nodes
Yeah but what comparisons do I make to which nodes. Do I go back down the tree? What am I looking for? What do I do when I pass and fail?
you get all distances to points in the same node, then compare with the distance to neighbouring node's bounding boxes and if any of those boxes are closer than any of the local points, compare all points in that neighbouring node until you have a list of all points that potentially could be nearest, then pick the closest one
the key here is that the distance to a bounding box tells you if any point inside it has the potential of being close(r), so if the box is farther than the closest point you already found, you can disregard it and all the points inside it
Distance to the center of the bounding box? Also, when did I need to calculate the bounding boxes? I just have a tree of points right now
no, distance to the edge, whenever you add a new point you update the bounding box in the node it gets added to
Iβm starting to think my implementation is flawed. Should I share my code because Iβm a bit lost right now
there are a few variations on how to implement a k-d tree, maybe yours doesn't have bounding boxes
i.e. some implementations split on every point added and the split sits on top of the point
like this
others work like this
All I need it to do is to be able to quickly find the nearest neighbor of a point cloud
thats what k-d trees are for π
if you split on points you still create those rectangles that you can infer the bounds for, and you have to check against those
Also I should note Iβm doing this only using value types so if it looks weird thatβs why
i'm heading out, but maybe someone else can dive into the code
is this an exercise or a learning project or do you need that for something productive? in the latter case i'd just use a readymade one, getting these things right and efficient is usually way too much work π
oh, I think I just found a readymade one for DOTS. I was using the wrong words when I was searching for one
what is your objective
oh yeah i remember now
are you running your editor in vulkan on windows right now?
yea
sometimes i get an error about it not finding the main kernel but only once in the beginning
please
i need somebody from usa
to do a little test, 5 seconds
216.239.35.0
216.239.35.8
this are google ntp servers
can you check if those are the same for you?
if they work in usa?
apple just rejected our app
and the only explanation is they cannot reach those ips
216.239.35.12
those are ntp servers to check the time please someone in usa cold test if those ips work from there?
shit maybe apple has blocked the access to google π
in their offices i mean
I was wondering if someone could help me solve an issue I'm having with my inventory system. I have a GenericItem class, which has a scriptable object variable for my UseableItem Class, and a int for the amount of the item. My UseableItem class then gets inherited by other specific types of items, like weapons or consumables. I tried storing the items info in a list of my GenericItem Class, but when I try to access the child data like in a weapon, I can't seem to access any variables like damage amount etc. I wanted to make a more modular system for storing items, but I can't seem to get it to work. I'm not sure if it should be working and if so could it be that I messed up the referenced data somewhere along the line? Thanks in advance for any help, I appreciate it.
What's the correct way to have a monobehavior callback run after a domain reload, but at the same time after all of the awakes have run
Like a start method, but which is also run when scripts reload, at the time that start would normally run
I have an initialization procedure, which I think could restore the scene just by calling it again
time1.google.com is unreachable (216.239.35.0). The others are.
thank you very much
Also, 216.239.35.12 is time4.google.com
You need to cast it back to the class you expect it to be. So if you have a UseableItem class and you store it in a List<GenericItem> then you need to cast it back to UsableItem class to get access to it's properties. If you cast into wrong type it will be null.
Hi, is it safe to compare two tasks with eachother using the == operator or .Equals() function in order to determine if they are the same? I am using Task.WhenAny() in an observer and I need to determine if the completed task equals the initial task reference.
So far it worked, but I have never been sure if it's reliable to do this. Is there something else I can use?
I noticed a task instance has an Id field. Is that better to check?
yes
https://docs.unity3d.com/Manual/class-MonoManager.html
if you need more control for specific functions only, you could create your own "LateAwake" MonoBehaviour, that has a script execution order set below everything else, and in its Awake call yourScript.LateAwake() -
onWall = Physics2D.OverlapCircle((Vector2)transform.position+rightOffset,collisionRadius,Ground)
|| Physics2D.OverlapCircle((Vector2)transform.position+leftOffset,collisionRadius,Ground);``` Why it doesnt change the state of the bool?
Because the right side evaluates to the same value as the variable's original value
Has anyone ever tried to modify mesh vertices of a TextMeshProUGUI component? Already have script that modifies text component I just need to apply this script to work with text mesh pro component (Which class to extend and which method to override in order to achieve vertex manipulation)?
any idea why this network manager callback on mirror doesnt get called ? public class Ch : NetworkManager { public override void OnServerConnect(NetworkConnectionToClient conn) { Debug.Log("onServerConnect"); this.GetComponent<NetworkIdentity>().AssignClientAuthority(conn); } }
Object Serialization...
How can I Serialize a object to send it over my server to my clients and reconstruct it WITHOUT using BinaryFormatter?
There is BinaryWriter and BinaryReader if you still want binary
Is it secure? Like i dont want my clients to run remote code
They don't have the vulnerabilities that BinaryFormatter has
Ok thx I will look into it.
But it's not really a BinaryFormatter replacement. You can't just give it any object to serialize/deserialize.
Hmmm. What type of objects work?
Primitive types, like int, float, byte but also string.
You have to manually serialize and deserialize each field
uufff
Making sure you do it in the right order on both ends, otherwise things will break in weird ways.
Do you know other options?
I will try to be a bit more specific
If performance or bandwidth isn't a priority, JSON is fine.
Im trying to format a list of my custom class that contains public and private fields that id like to format
Tryed JSON wasn't that successful
What part wasn't successful?
Did you put [Serializable] on the class?
Also most json serializer can't serialize a list directly. You need to wrap it in another class.
Are you using Unity's JsonUtility or something else?
jsonUtility
If you want to serialize private fields, they need to have [SerializeField]
There are many options available out there. XML is pretty old at this point and not used as much as JSON. There are many binary formats available, or you can make your own, which is what BinaryWriter/Reader would let you do.
Most popular binary format is probably Google Protobuf
Uhhh every option seems so unattractive. I cant imagine writing a formatter for everything (that aint a primitive) that i send over my server... BinaryFormatter seemed so easy and efficient :')
@sage radish Last question cause u seem to know much about serialization. Wouldn't the binary formatter be safe when i instantly cast the desterilized object into the type i want? (stupid question)
I am just doing a bit of toying around and was wondering if there is a way to add a bunch of predefined GameObjects at once. Obviously there is storing them in a scene and loading them additively. Another option would possibly be to save the diffs of the objects and instantiate the GameObjects and then apply the diffs. But that would create a lot of garbage, and idk if the diffs could be applied before Awake was called. Any thoughts?
I don't know the specifics of the vulnerabilities of BinaryFormatter, but since what you described is how most people use BinaryFormatter, I doubt that avoids the problem.
Hello, which one is better to use?
new Vector3(0.5f, 0.5f, 0.5f) or Vector3.one * 0.5f
The first one as it is more explicit and imo easier to read. Also easier to edit in the future.
@vital breach the docs clearly state (emphasis is theirs)
The BinaryFormatter.Deserialize method is never safe when used with untrusted input.
more details
The Deserialize method can be used as a vector for attackers to perform DoS attacks against consuming apps. These attacks might render the app unresponsive or result in unexpected process termination. This category of attack cannot be mitigated with a SerializationBinder or any other BinaryFormatter configuration switch.
and
BinaryFormatter.Deserialize may be vulnerable to other attack categories, such as information disclosure or remote code execution.
sorry, was aimed at Yae
Multiplying will be marginally slower.
what about the cost, if any, of creating a new Vector3?
it copies a new one either way
so Vector3.one does new Vector3 in the background anyway?
it's not some cached thing?
It is a struct, so a new one has to be created after multiplying
as the result?
Yes
Thank you, makes sense
Also the * operator is defined like this:
public static Vector3 operator *(Vector3 a, float d)
{
return new Vector3(a.x * d, a.y * d, a.z * d);
}
hello
i want to call a service with native java plugin
i know how to call the native service
but idk how can i write the java plugin so please help
i wish if someone here knows what a service is
The cost of making new Vector3 is pretty much 0 because its a struct (saved in stack and not heap). Allocating new instances of class unnecessarily (new keyword is used for both classes and structs) can be bad because things stored in heap has to be garbage collected which can cause lag spikes but structs are not a problem
Are you talking about in Android?
yep
why would i need a service for pc
for pc you can even run the app in background
Windows has services
do you even know what native java service calls are?
a service is the Java name for a cohesive part of the codebase that has a clearly defined interface which other parts of the program can use without knowing anything about it except the interface
yea
but i dont know how to use it
i am literally new
I know that "native java service" isn't an official term used by anyone. When you say native, do you mean services that are native to the Android platform, such as GPS, notifications, things that aren't Java specific, but Android/mobile specific? Or do you mean native as in JNI (Java Native Interface)?
you use it like any other code, read its docs, understand it, tinker with it, fail and learn
yep
there are no docs
no help
i know found how to call the service
dont know how to write the native java plugin
Unity will automatically compile any .java source files in your project during Android builds.
So you can avoid setting up the Android SDK and compiling it yourself.
yes i know
but what should i write inside that java plugin
so that i can make a call to it and return a bool
Is this what you're looking for? https://docs.unity3d.com/Manual/android-plugins-java-code-from-c-sharp.html
i have read this but idk if it would work
also its extern
meaning that you can call the function from C#
also a question
would the service work like an update void that send the thing everytime
?
If your .java file looks like this:
package com.companyName.pluginName
public class MyPlugin
{
public static bool MyMethod()
{
return true;
}
}
then you can call that method from C# like this:
using (var myPlugin = new AndroidJavaClass("com.companyName.pluginName.MyPlugin"))
{
bool returnedBool = myPlugin.CallStatic<bool>("MyMethod");
}
ohhhh thanks
let me try it
please stay online till then
is it possible to map these up using that extern trick?
I think that's only for natives plugins written in C/C++
for java it works as well but its not a native call
you are using native functions in C#
in my case i am making a native call
Is it possible to have files outside of the assets folder included in a build, and if so, can you read them from inside?
nope
but you can have bundles
Dang, I didn't think so π¦
I wanted to do an experiment with having possibly several 100k files but that of course would slow asset database down a bunch.
idk why do you want to do this anyways
these are 3d graphics assets?
if i recall you are doing the FBX importer thing
nah, they would just be text files or custom binary files.
and you're using parallel importer?
in principle with a cache server
it's prob easier to import it once
and just deal
a computer doesn't care if it's 100k or 10k
I wanted to try experimenting with putting each GameObject in their own file instead of storing them in scenes.
i don't think it will matter. it either works at 1k or it doesn't work at all
like for git purposes?
or because you want to create the prefab elsewhere
For level streaming
to make life easier for you, create a build.gradle and set up a proper yava project that way. gradle init is all you need, then the android libs. so you'll have autocomplete and the files will be compiled by unity. you can also easily create a shadowed jar and add that to unity
don't overthink this
you mean at runtime?
Yeah
i've seen this a bajillion times in various unity packages
hi @undone coral π sorry it took me so long to come back π
you can maybe set a flag that the event was raised, then in Start run your initialization (instead of Awake) and clear the flag
are you busy?
go for it
btw
i'm testing your IPs on my windows computer
and i do get proper time
$ w32tm //stripchart //computer:time1.google.com
Tracking time1.google.com [216.239.35.0:123].
The current time is 5/19/2022 9:46:31 AM.
09:46:31, d:+00.0212070s o:+00.6225572s [ | * ]
09:46:33, d:+00.0197775s o:+00.6220386s [ | * ]
09:46:35, d:+00.0206514s o:+00.6225264s [ | * ]
all three worked
i am located in san francisco
i don't think it's blocked for them, i think they gave you a bad report
ah yeah thats fixed, i thought it was a problem with the ntp servers but seems the apple guys test no connection situations and my app was not being able to come back from offline
so i take the ntp servers were fine
i'm surprised they tested anything at all
they don't really have the bandwidth for that. you're supposed to give them a thing that just works and does basically nothing
yeah you asked me why to use ntp servers, since the game does not work without connection i use a list of ntp servers that i choose randomly to guarantee the user has connection, and at tthe sime time i get the real utc time to avoid cheating
so they approve it
now waiting again for the review
One problem i was with this querying firs is i was using a 3rd party asset that used tasks to do the queries
but i was getting reports of a lot of exceptions like... 'dns not resolved' 'unknown host' etc....
those were aggregated exceptions
so i take this or another asset was not managing the most basic exceptions internally
One of the suspicious ones was unirest
you asked me why to use it and suggested postgrest
whats the difference? both communicate with sql using rest i take
I have to mention... the operations we do with unirest are not vital
we dont use it for save the game or anything like that
we are doing our own analytics and we started by taking custom data into sql
got it
and since uniRest was easy to install and use...
unirest has a wordpress plugin - is that how you're operating its backend?
yes exactly
okay
and its very friendly so the game designer , not a coder, can make queries without knowing sql
if you want to do the time thing, i'd use unitywebrequest and query a basic http time API
it will be a lot less painful
since you don't need microsecond-synced time
yeah but, i think i rather use microsoft, apple and google servers
for analytics, use google analytics. the newest version is appropriate for apps
because it will guarantee me they will be always on
actually i have a remote option that will allow me to use directly their ips
so i wont have any dns problem
C:/Users/NodeAdministrator # curl --head http://google.com
HTTP/1.1 301 Moved Permanently
Location: http://www.google.com/
Content-Type: text/html; charset=UTF-8
Date: Thu, 19 May 2022 16:54:55 GMT
Expires: Sat, 18 Jun 2022 16:54:55 GMT
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 219
X-XSS-Protection: 0
X-Frame-Options: SAMEORIGIN
do you see that it has the date
in the headers
the problem with that is you do a webrequest
and sometimes im getting exceptions in them
it has the current date and time in every response
and im not sure if its a unity bug
to google
so you don't even need a time api
you can read the Date header
from www.google.com
yeah i see...
hehehe
there's always a lot of inertia
after you've written all this code and fixed all these bugs
it's okay
sometimes you just gotta delete
yeah, tell me about iit, i've been working on this 3.5 years
i don't think you should use unirest for analytics
google analytics is completely free
it should already have a unity library
personally i would use mixpanel
yeah we tried it, and sincerely im not the data analyst type, thats my partner, and regardinng him with that you just get absolute numbers... but you cant get certain things
mixpanel?
i understand there's a desire to get personalized analytics
never heard of it
you'd have to use mixpanel
their people feature
i believe google analytics nowadays also has personalized data
i will ttake a look for sure thanks
i think your partner may be looking at universal analytics
which is the google analytics everyone has known since forever
and google analytics v4 is what you should be using now
we were using the firebase one, is that what you mean?
no
google analytics for unity?
I didnt even know it was possible
π
sincerely when he talks me about data and statistics i disconnect
okay i see firebase analytics
i don't really know what it does on the backend, i assume it would be google analytics, but who knows
Google Analytics you can interact with via a REST API
you recommended mixpanel and google's analytics v4
you don't need a library
mixpanel is personalized
i assume that's why you were asked to do a bespoke analytics integration
A Mixpanel User profile reflects the most recent information about a user.
Mixpanel builds profiles by connecting information about a user to a distinct_id, which creates a location that collects ...
because you want something like this
whereas google analytics is "Aggregated"
uhmm, no i was not asked iwas simply interested in your opinion of it
okay this looks good
mixpanel's way of looking at things supports people who are successful
so when you adopt analytics that help populate their dashboards, you wind up measuring the right things
hey all. i have somewhat of an advanced question to ask about a shader swap on a tmp_submeshui. any suggestions on where i'd ask that question?
instead of coming up with your own ideas and trying to visualize it
goo ahead
so mixpanel is the dashboard but the data comes from analyticcs integrated in your code
correct?
mixpanel provides an API and a unity library for reporting analytics events to them
ah ok ok
Read our advanced documentation on Mixpanel's Unity SDK integration. You'll dive deeper into additional configurations and use cases including super properties.
thanks i will defiitively take a look
i'm in a situation where i need to swap the shader on a TMP_SubMeshUI during runtime, but don't want to make any permanent changes to the material. setting mesh.material or mesh.material.shader seems to do nothing. setting mesh.materialForRendering.shader DOES work but it commits the changes to disk, and i can't set mesh.materialForRendering itself as it's get-only. wondering if i maybe missed a material property i should use instead, or perhaps there's some other way to do this.
i guess my other option would be to create a completely separate TMP_SpriteAsset with a brand new material that uses this new shader, and only reference that sprite asset in the text string during this special circumstance
but that seems... unnecessarily convoluted. maybe it's the only way.
Can you guys take a look please? https://stackoverflow.com/questions/72309013/unity-position-different-in-function-compared-to-update/
It seems that loading multiple asset bundles asynchronously at once is causing the editor to crash. Is this a known thing? Should I not be doing that and just waiting for each one to load before doing the next?
I've changed my Asset Bundle Loader to wait for the previous one before starting and I haven't hit a crash yet. I comment that out and it'll crash the second time I start the game nearly every time
Async Bundle Loading code:
http://pastie.org/p/6cZHYEfNBLc6Mkb597kOzg
you're calling Attack() on the Weapon component on equippedItem.prefab. If that is indeed a prefab rather than an instance, then the values on its transform component will be garbage. You need to get a reference to the instance in the scene, not the prefab asset.
Okay, with the bundles loading one at a time, I can force a crash by stopping the game during a particular bundle loading, then restarting. When it tries to finish that bundle, it tells me it's already loaded. I am calling UnloadAllAssetBundles in Destroy so it should be getting rid of the old one, but it seems to not be
I fixed it thanks
Does anyone know how to use the Localization Pack?
I think what I need to do is check if there is a running AssetBundleCreateRequest on quit and cancel it if there is, but there doesn't seem to actually be a way to cancel one. Have I missed something? How do I cancel an AssetBundleCreateRequest?
What would be the best way to create a power bar for a golf game? Id like to hold down spacebar and have some UI shift up and down, and when released debug x value to apply as force against the ball.
The jump is not working when on the wall, it gets stuck on the slidding
using UI.Image of course, though it's more of #π²βui-ux question rather than an advanced one
No im actually talking about the code part
Image.fillAmount
Obviously I get that, but the whole mechanism behind holding the spacebar etc...
getting the good said amount even when releasing
whats unclear about doing that? this seems kinda trivial.
Having a mind block
float howSweetAreWe = 1f - Mathf.Clamp01(Mathf.Abs(timeSinceKeyDown - sweetspotCenterPosition) / howBigIsTheSweetSpot);
and
fillAmount = Mathf.Clamp01(timeSinceKeyDown / maxTime);
How do i make this work? when i press shift it just goes faster down
ill see if i can work that into something tomorrow, thanks !
you definitely want a kinematic controller if you do stuff like wall grabbing
Okay, I need some help. Im kinda at a loss of what do to.
I created an item system using an Item class that looks like:
[CreateAssetMenu]
public class Item : ScriptableObject
{
public Sprite ItemSprite { get => itemSprite; }
[SerializeField] Sprite itemSprite;
public string Identity { get => identity; }
[SerializeField] string identity;
}
I have an Inventory script which allows me to assign item slots in the inspector through [SerializeField] List<Item> items;, which displays them in my UI automatically. I can create unique items through the [CreateAssetMenu] attribute, and they all exist in a folder in my assets file.
The issue I have NO idea how to tackle is saving and loading what items you have during runtime. throughout my project i have been using a custom SaveSystem class that makes JSON Saving much easier, and puts them in the correct folder to save and load them during runtime.
This works and has been working if im trying to save serializable datatypes, like a struct tagged as [System.Serializable] that has floats and strings and arrays that its trying to save. a List of scriptable objects is not one of those.
I wish to be able to save and load them by saving an array of strings of the Item's string Identity. on load read the list and assign the items, and on save just read the identity of each item and save that list.
I have no idea how to approach converting the list of Item Identities into a list of Items. I know it should be possible, but i have no idea how.
im gonna play a game, please mention me if anybody ends up being able to help me out.
you keep a listOfAllItems, each item has a unique ID,
Saving: you serialise an array of an arbitrary selection of those IDs (from your ingame inventory) to a JSON file.
Restoring: you load an array of IDs from a JSON file, match the IDs to items in your listOfAllItems. on a match you put a reference to that matched item into an ingame inventory slot.
hmmm okay, that makes sense however now the quesiton is where to store a listOfAllItems. maybe a Unique SerializedObject called like ItemGet? That sounds like a good idea. ill try it out, thank you.
does not matter, MonoBehaviour, SO, custom stuff, its all the same
easiest would be a manager-type/singleton MonoBehaviour
Well if it was a MonoBehavior, it would have to be a singleton to persist across scenes, and it would have an uneccessary transform and uneccesary Update... nah ill stick to a ScriptableObject in my assets folder.
these are completely irrelevant concerns
this is true
if a monobehaviour has no Update/Start/Awake defined those obviously dont get called
a transform that does not move produces 0 performance overhead
Still trying to find the source of these Editor crashes when loading asset bundles in the editor. Remembered that the editor leaves a log file so I thought I'd go look at that and see if there's anything beyond where I saw in the editor itself before crashing:
http://pastie.org/p/6qIOzYazoIQC3H3IpoDCYG
It's definitely something related to cleanup. The bundles are all entirely materials, and everything here seems to be related to cleaning up cached materials. I exit the game, it tries to clean up the assets from the bundles, and dies a horrific painful death.
Does anyone know a solution for this? Is this something related to how I'm loading bundles, or is there a memory leak in how bundles are handled in-editor?
sigsegv usually has something to do with memory violation, so yeah, maybe memory leak
okay im back where i was yesterday.
Can someone please explain to me step by step how the walking-back algorithm for a K-d tree works? I know why we do it, but my brain hasn't fully conceptualized how
i see this mistake all the time. why oh why people make the scriptable object a data container. it can contain one field that typed to your data. first:
[Serializable]
public struct Item
{
public Sprite ItemSprite { get => itemSprite; }
[SerializeField] Sprite itemSprite;
public string Identity { get => identity; }
[SerializeField] string identity;
}
[CreateAssetMenu]
public class ItemScriptableObject : ScriptableObject
{
public Item Item { get => item; }
[SerializeField] Item item;
}
okay, you're done. you no longer have a list of scriptable objects!
you should never mutate scriptable objects
what is your objective
why? what's your objective
what are you trying to do
I dont understand why the difference between these two matters at all, gonna be honest.
probably due to lack of c# and unity knowledge but either way i dont get it lmao
it will be easier to parse/serialize the Item, than serializing each property one by one
SOs were introduced as a way to store config data. As such it makes little sense to mutate that data at runtime (since that would only create confusion). But SOs can be used for other things and when doing these things, and it is clear they are not config-SOs, you can mutate as much as you like. But just as with MonoBehaviours, it is advisable to treat serialised fields as immutable (keeps things simple, no need for runtime validation).
Wait, what do you mean by mutate or immutable in the first place?
and @undone coral Why would i not use SerializedObjects as data containers for data that wont change, like the sprite and identity of an item?
In object-oriented and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created. This is in contrast to a mutable object (changeable object), which can be modified after it is created. In some cases, an object is considered immutable even if some internally used attributes...
Okay okay that makes sense. Im not trying to change the content of the item, its meant to be immutable info about individual items. the thing that would be mutable is the List of the Item SO's. I dont see how im mutating anyhting
this seems like a reasonable use case
aight aight thank you for the clarification and help.
yall are continuously wonderfully helpful in this server
I know I have to trace the parents, but then what
Hey guys I am trying to create a extension method to create full scriptable object instance (datas,inner scriptable objects and their datas)
{
//CREATE BASE INSTANCE
T Instance = (T)ScriptableObject.CreateInstance(typeof(T));
Instance.name = BaseScriptableObject.name + "-Instance";
//TEMP FIELD INFOS
FieldInfo[] InstanceFields = Instance.GetType().GetFields();
FieldInfo[] BaseFields = BaseScriptableObject.GetType().GetFields();
if (BaseScriptableObject.HasField())
{
for (int i = 0; i < BaseFields.Length; i++)
{
//SCRIPTABLE FIELDS RECURSIVE
if (BaseFields[i].IsScriptableField(BaseScriptableObject))
{
T InnerScriptable = (T)InstanceFields[i].GetValue(BaseScriptableObject); // ISSUE WITH CASTING <-
InstanceFields[i].SetValue(Instance,InnerScriptable.Clone());
}
//OTHER FIELDS FLOAT, STRING ETC.
else
{
InstanceFields[i].SetValue(Instance,InstanceFields[i].GetValue(BaseScriptableObject));
}
}
}
return Instance;
}
but how can i solve the casting issue that line i wrote
whats the error?
InvalidCastException: Specified cast is not valid.
thats it? i think it provides the actual types that you are attempting to cast, at least sometimes
i will check
sounds like your IsScriptableField extension method is buggy
maybe public static bool IsScriptableField(this FieldInfo field, ScriptableObject scriptableObject) { return field.GetValue(scriptableObject).GetType().BaseType == typeof(ScriptableObject); }
I fixed the casting issue but now its gives the error "AttributeSO doesnt contain a def. for Clone()" but how its also a scriptable object class .
When i use dynamic that structure doesnt see the extension methods ?
{
dynamic InnerScriptable = BaseFields[i].GetValue(BaseScriptableObject);
dynamic InnerScriptableInstance = InnerScriptable.Clone();
InstanceFields[i].SetValue(Instance,InnerScriptableInstance);
} ```
Yeah. Dynamic is a pretty bad idea in a strongly typed language.
i fixed everything ok ```public static T Clone<T>(this T BaseScriptableObject) where T : ScriptableObject
{
//CREATE BASE INSTANCE
T Instance = (T)ScriptableObject.CreateInstance(typeof(T));
Instance.name = BaseScriptableObject.name + "-Instance";
//TEMP FIELD INFOS
FieldInfo[] InstanceFields = Instance.GetType().GetFields();
FieldInfo[] BaseFields = BaseScriptableObject.GetType().GetFields();
for (int i = 0; i < BaseFields.Length; i++)
{
//SCRIPTABLE FIELDS RECURSIVE
if (BaseFields[i].IsScriptableField(BaseScriptableObject))
{
dynamic InnerScriptable = BaseFields[i].GetValue(BaseScriptableObject);
dynamic InnerScriptableInstance = Clone(InnerScriptable);
InstanceFields[i].SetValue(Instance,InnerScriptableInstance);
}
//OTHER FIELDS FLOAT, STRING ETC.
else
{
InstanceFields[i].SetValue(Instance, BaseFields[i].GetValue(BaseScriptableObject));
}
}
return Instance;
}
here is the code if anyone use to create full instance of scriptable object and their childs xd
Should use inheritance or interfaces instead.
yeah if u dont know the expecting type your option would be nicer
Make sure that you correctly Destroy the child objects when you're done with them.
I'm gonna just explain my UI problem here, if there's anyone really skilled at UI, please help.
Context:
I have a button where I have two areas, one for the header, one for the price. These scale with the button. I made this simply via anchors, this works great.
Next, the price. The price sits within a container. I can replace whatever display is used at runtime, depending on the currency type. So, within that price container I'm going to spawn price displays at runtime, from prefabs, which span the entire parent (the entire price container).
Problem:
Price tag on the left, and the currency sprite to the right of it, all left aligned within the parent. This is basically what I'm trying to achieve.
Now, I need the text to span as much of the parent as it can, but without overflowing. So the font size needs to change dynamically based on the available height, but no more than width + width of image. Same with the image - it should scale its height with the parent, while keeping the aspect ratio.
I've tried parenting the image to the text, but then it may overflow
I've tried using a horizontal layout, but then the text inexplicably becomes 0 width
I've tried different combinations of the aspect ratio thing and content size fitter
I've read most of the documentation on unity UI, which was not helpful
it would be helpful to draw it out, or show a screenshot of what you're seeing with some notes on what you want to achieve
also: #π²βui-ux might have helpful feedback as well
What is all required for mesh generation?
vertices + triangle indices?
Cause for some reason this gives me Gizmos.DrawMesh requires a mesh with positions and normals
When I try to draw it in Gizmo
private Mesh GenerateMesh()
{
float3 localPos = transform.localPosition;
localPos.z = 0;
_radius = localPos.Magnitude();
_circleLength = math.PI * 2f * _radius;
int numOfSegments = (int)(_circleLength / resolution);
float t = circleFraction / numOfSegments;
List<Vector3> vertices = new List<Vector3>();
List<int> indices = new List<int>();
for (int i = 0; i < numOfSegments; i++)
{
float curT = t * i;
float nextT = t * (i + 1);
math.sincos(curT, out float curSin, out float curCos);
math.sincos(nextT, out float nextSin, out float nextCos);
Vector3 curPoint = new Vector3(curSin, curCos) * _radius;
Quaternion rotation =
Quaternion.LookRotation(new Vector3(nextSin, nextCos) - curPoint, Vector3.forward);
Vector3 leftVert = rotation * Vector3.left * thickness + curPoint;
Vector3 rightVert = rotation * Vector3.right * thickness + curPoint;
vertices.Add(leftVert);
vertices.Add(rightVert);
indices.Add(i);
indices.Add(i + 3);
indices.Add(i + 1);
indices.Add(i);
indices.Add(i + 2);
indices.Add((i + 3));
}
var mesh = new Mesh() { name = "pepe" };
mesh.Clear();
mesh.vertices = vertices.ToArray();
mesh.triangles = indices.ToArray();
mesh.RecalculateNormals();
return mesh;
}
i have football game with slider that goes green to red and player presses it so it can shoot(Green easy shot,Red Hard) my broblem is after the first shot the slider has no effect that the player can shoot without the slider, how do i "reset" the slider that the shootball checks for it again ?
https://paste.ofcode.org/xUzQdqrdSHNAFgad6YpyX8
that is my shootball
i have the slider reseted but the shootball does not need it after the first shot
@main stump It looks like you should split up your controlls and you ball itself. I made an example for you that should explain the procedure https://pastebin.com/rT04hJ9e
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.
Can we run a model dll whose target framework is net core 3.1 in unity?
If you want to achieve this through code I would suggest learning about procedural generation
Though if you want to build the terrain by hand I believe thereβs a built in terrain editor in unity but itβs not the best
If youβre looking to a place to start thereβs the complementary Brackeys video covering the topic
Generate a landscape through code!
Check out Skillshare! http://skl.sh/brackeys11
This video is based on this greatwritten tutorial by Catlike Coding:
https://bit.ly/2Qd1o1d
β Perlin Noise: https://youtu.be/bG0uEXV6aHQ
β More on generating terrain: https://youtu.be/wbpMiKiSKm8
β Singleton: http://wiki.unity3d.com/index.php/Singleton
β₯ ...
Sebastian Lague also created an in depth tutorial https://youtu.be/wbpMiKiSKm8
Welcome to this series on procedural landmass generation. In this introduction we talk a bit about noise, and how we can layer it to achieve more natural looking terrain.
A quick summary:
'Octaves' refer to the individual layers of noise.
'Lacunarity' controls the increase in frequency of each octave.
'Persistence' controls the decrease in ampl...
I need to generate a procedural mesh out of a list of sockets(which you can grab position so technically points) for the part between floors. I did researched a little and saw Unity's triangulator, but I couldn't been able to find a clue about it(The links are corrupted). What is the best way/algorithm to deal with such a generation?
Which is for generating this type of floor separators(?). I don't really know what exactly people call them.
Wave function collapse?
O h wait
I misread
This is a tutorial on how to solve problems in Unity by using math such as Linear Algebra and C# code. You will learn how to find out if an enemy is infron or behind you, how to follow waypoints and learn when you have passed a waypoint, how to figure out if you are to the left or to the right of an object, how to find where an array intersects ...
Did you work this out? You need to anchor the objects proportionally and then just a text mesh pro ui object for the text, and set it to resize the text to fit
Since we have some incredibly smart C# devs here, I wanted to ask some advice for a heap-allocation problem I'm facing.
Yeah, I'm doing approx 21.7 GB worth of heap allocations.
I've managed to get almost everything optimised to use the stack but it seems foreach() loops require IEnumerator which would need to be allocated on the heap.
The method MoveGeneration() is essentially having a foreach loop inside of it, which has 2 foreach loops inside of it and one of them then calls the method MoveGeneration() recursively for each of its iteration.
Short story: loads of foreach = loads of IEnumerator<> - question is, how do I avoid such a large amount of heap allocation?
yes foreach does allocation. This cannot be avoided if you use foreach
maybe use a normal for loop?
Yeah this was the other thing in my mind, to use a normal for loop. I just wasn't using it because I thought there was a better way to do foreach maybe.
I would also say that avoiding recursion would be a good idea for memory management in general
It's not heap allocation but it's still heavy
Well yeah, recursion is an issue but in this case, it's quite necessary.
Not saying you can't, but the thing is, an iterative function would be way too complicated.
probably not as complicated as you think
graph algorithms are quite simple
you would need only to introduce a single Stack<Node> or Queue<Node> and you can do any graph/tree algorithm iteratively
This is how it currently looks (in case you want to know).
and number of nodes increase exponentially at every depth.
The code for an iterative move-generation would be so long.
I mean you'd just have a fringe which is a Stack<(Color, int)> and you basically just do what you are doing now in a while loop while (fringe.Count > 0) you pop off the next color/depth and do exactly what you're doing now
and instead of the recursive call you just push the next thing onto the fringe
What?
I'm confused by what you mean.
https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack?view=net-6.0 - If you're referring to this, I can't even be using that.
why can't you use basic data structures?
Because again, heap allocation. I'm trying to avoid it.
it's a small allocation. Is this a Job?
I'm allocating everything on stack except the Enumerators right now. It's what has given me a speed of 70M nps right now.
You can make a custom struct enumerator that doesn't allocate. Most of the built-in collections do this, like List.
I think you're worried too much about allocation instead of the big picture of overall performance
Really?
How do they do that?
I don't get it - how's stackalloc related to Enumerators?
It doesn't I was responding to a question that wasn't asked but I thought was asked
So foreach doesn't actually care about the IEnumerable and IEnumerator interfaces. It will happily work with a struct enumerator as long as it implements the bool MoveNext() method and a T Current { get; } property.
You'd have to explain what MoveList is and what MoveList.Get returns
https://github.com/TheBlackPlague/StockNemo/blob/1a4d5661df49c557f390c9342cf47f26296c9871/Backend/Perft.cs#L91 - If you can figure out an iterative version of this that is faster than the recursive version, I'd be fine switching.
This is what you're looking for.
Oh I see. But wouldn't returning such a struct have to copy?
Do you mean make it a ref struct?
Is this a Chess game
Just change your BitBoardEnumerator to a struct and add a method to BitBoard that is defined like this public BitBoardEnumerator GetEnumerator()
most likely a chess engine
A chess engine.
Yeah but again, doesn't that require copying the enumerator construct after constructing?
A struct copy won't allocate garbage that needs to be collected.
I see.
I can try it but I have a feeling that with the amount of copying, it'd actually be slower.
Any ideas / solutions for generating a grid of waypoints given a road mesh? Basically, I need it to generate waypoints points for minimap navigation, while all info I have is the road mesh
It's not copying much each time. It's only two Int32s and a UInt64, 16 bytes.
And the copies are all in stack memory, which is a lot faster than heap memory
Ah it seems doing such has another issue - Parallel.ForEach() expects an IEnumerable.
Looking for general advice. I have a nosql database and multiplayer game server, and am pondering how to do environment/version management. My tentative thought is to create a copy of the database for each version and/or environment. IE:
Database-Production-v6.0
Database-QA-v6.1
Database-Dev-v6.2
Any time we migrate a version and/or a change to the structure of the database, we'd manage a migration script as well:
Migrate-v6_0-to-v6_1.cs
Migrate-v6_1-to-v6_2.cs
And run this script as part of the migration against a NEW database, smoke test it, and go back online. So deploying 6.1 to production would look like this:
- Create copy of Database-Production-v6.0, name it "Database-Production-v6.1"
- Run Migrate-v6_0-to-v6_1.cs against it
- Change configuration settings of game server to point to the new database.
- Smoke test and if it looks good, go back live.
Additionally, I'd be interested in hearing thoughts on versioning the clients when a client version becomes incompatible with a new server version (say there's new networking messages or serialization of objects). Should I run multiple versions in parallel (and manage the complexity of which users can interact with which other users on different versions), lock out the users? Something else..?
Is there no chance of implementing BitBoardEnumerator as an indexer instead?
@weary stag
Parallel.ForEach checks if the IEnumerable also implements IList, and uses that instead.
I'd expect that to also perform better, because it be more easily be parallelized.
What do you mean as an indexer?
I see your enumerator is doing this:
int i = BitOperations.TrailingZeroCount(Value);
Value &= Value - 1;
Is there no way to calculate what Value should be at iteration N without doing all the iterations before it?
Anyone know how to change the speed of a mecanim animation clip?
And I do NOT mean change the speed multiplier parameter value (I need that one to be dynamic at runtime) But only the default clip playback animation speed
Well foreach() doesn't do iterations.
TZCNT is a hardware operation.
And once TZCNT has been calculated, next thing is to &= Value - 1
It must be done in order basically.
You can't skip to future iterations of Value.
TZCNT just returns the number of unset bits before the first set bit in the uint64
So could you store the results of your enumerator into an array and pass that to Parallel.ForEach?
Because Parallel.ForEach also handles arrays in a more optimized way.
That would mean having to convert it first into an array by looping and then passing an array (looping over it again)
Honestly when we get into this low level of code I'm wondering if it doesn't make more sense to use a chess engine written in C/C++ and use it as a native plugin?
Parallel.ForEach must be doing that already, right? It can't iterate over your enumerator in parallel, because it has to be done in order, as you said.
Well, if I wanted to do that, I could use Stockfish. I'm trying to make my own.
he wants to make his own chess engine
I'm not porting Stockfish lol.
Ok I misunderstood that https://github.com/TheBlackPlague/StockNemo is your repo
Hmm. Unless it's doing something else?
Does it really convert IEnumerable into arrays to loop in parallel?
How else could it do it?
Yeah I looked at it, but I didn't go far enough to see what it ends up doing with the IEnumerable
It creates a Partitioner
not sure what that is
I don't think it makes it into an array afaik.
actually
it does
My guess it's partitioning the workload into chunks, so it's not converting your whole enumerable into one big array, but chunks.
Yeah.
Not sure what's cheaper tbh haha.
Also if I use arrays, they're also heap allocated.
and not stack-allocated.
since arrays by default in C# are objects (heap-allocated).
Is this project specifically for Unity or are you trying to make a general C# library?
This is more so a general library. Currently, for ease of development, I'm using a terminal-based GUI, but once the engine is decently out of the backend development phase, I'm going to integrate it into my Unity Chess Board application.
This is the current terminal GUI.
Stockfish for example has a speed of 242M nps. I'm currently at 70M nps.
nps: Nodes per second.
And one of the reasons for their speed (after talking with their devs) is that Stockfish and other fast chess engine allocate on the stack rather than the heap in hot code like this.
(among other reasons)
I don't know if Parallel has some special privileges that allows it to do what it does, but if not it sounds like you'd gain a lot by writing your own thread/job management that uses more unsafe features to optimize. Or maybe something like that already exists.
That would be a lot of work which I'm looking to avoid.
Also it seems Parallel for some reason even with a max-concurrency limit of 4 uses up 100% of my CPU.
which I don't understand how it even happens given the CPU literally has 16 logical processors.
Thing is, the text is also set dynamically
it might be "10" it might be "1234567890"
Basically, all I need here is to run some line + curve detection algorithm, then find their intersections and just pot markers wherever they intersect
One of the problems is that it needs to work in 3 dimensions
think bridges over roads
does this package keep the road data anywhere after generation? anyone knows?
That's a question better suited for the asset creator
C# should have a migration package to deal with this
too late i wrote it already π
I probably should have googled more on it but .. I didn't think that I wanted to go through learning/configuring something new so I just rolled my own
how do you deploy your backend right now?
github actions
I push the repo, execute the action manually which builds and publishes to .. wherever. Currently the admin tool is an asp.net app that gets published to azure apps, and the server is a console app that gets built into a docker container and pushed to azure container instances. The database (before today) i manually provisioned using the azure portal, and the connection strings are in a github secret that gets echoed to a App.ENVIRONMENT.Config file in the docker container
so now the plan is to use the file I wrote and create a new cosmos instance, migrate the data, then set new connection strings at "upgrade time"
I've been doing some experimenting and testing with scene loading and Instantiation and found some interesting things(maybe).
My goal/test was to get 4000 simple cube privative prefabs in to the world.
Initially I had all the cubes at 0,0,0. I first tried instantiation them, and then loading them, and then using a coroutine to instantiate them (because why not).
As expected instantiation takes considerable longer and creates a tone of garbage. I was surprised that loading a scene didn't create any though, my guess is because it is handled on the C++ side?
I then thought to instead lay the cubes out in a grid with a single plane under them to see if the results were different. And boy were they.
Instantiating got faster and scene loading slower.
Scene loading went from 18ms to 22ms. That increase was due to the physics system doing stuff.
Scene loading also seems to split the work up which results in two spikes. The first is the initial load of all the objects. The second is split between the physics system and shadow initialization.
If you combine the time of both of those spikes it ends up actually being the same as instantiating GameObjects.
I don't really have any grad discovery or conclusion, but thought others might find it interesting haha.
I was hoping I could come up with a way to add objects that was more performant than loading a scene, but it seems not. I think instantiating with a coroutine is interesting as it allows more control over how fast objects are 'loaded'. But the garbage is a lot and I'm not really sure how it would do in a real game with lots of other systems running.
has anyone used the Playables API? I'm trying to properly apply root motion from animations while also blending with an Animator component but I don't know how
That assumes that you need to spawn them at all. Depending on what it is, you might be able to have one object that draws what the 4000 game objects would have looked like, and does so based on some data model. Creating the renderer for that one object is not trivial, though.
I was working on a board game that did that sort of thing.
One game object handled drawing all the visible tiles and status auras (selected, out of range, etc.). Clicks were just world coordinate -> tile coordinate conversion.
You mean instanced rendering?
I need help figuring out the best approach for my problem. I have procedural generation code and I want a loading screen to play while the map is loading. I've been doing a lot of research and have looked at async, jobs, multithreading, but each seems to have its own problems.
Async - It doesn't actually run on its own thread. (I'm pretty sure I want it to run on its own thread)
Jobs - See screenshot
Multithreading - Not necessarily safe
What do you guys recommend?
No solution you mentioned is safe
I figured it out, it was a wrong setup with the animation I was playing
Async can also run on threads, it's jut not guaranteed to and is not intended for long running operations
Handling threading yourself is really your only option
For real?
Yeah and with a situation like this it should be really easy.
Okay, good to know
I'm only using a few UnityEngine things in my code, Vector2Int and Random.Range
Considering it is just a one and done thing. This assumes you are not loading GameObjects and stuff
yeah, that's done elsewhere
So basically what you're saying is just handle the threading myself?
Yes
Yup
Well thanks, I at least know where to go now.
Everywhere I've turned has lead to dead ends, so thanks a lot. Do you have any resources for me to learn how my own custom threading works?
Threading is not that complicated (ten thousands asterisks).
lmao
Just look into System.Task and see how deep the async rabbit hole goes
I thought I was supposed to do my own threading approach though?
They weren't speaking practically. They were just saying it's a deep topic.
I mean you can work directly with threads if you really want, I don't think you do
oh okay
Ohhh I misunderstood.
God I'm so confused, there are so many different opinions on this
So... they're all threads. The biggest question is what exactly you're doing.
Just google "C# threading"
Main thing to keep in mind is that you can't interact directly with Unity's thread with your threads
Like is the "procedural generation" code really all that expensive?
It's quite expensive depending on the number of iterations you choose to do
Impossible to say without seeing the code
It's like o(n^2) x 5 or something. Not very well optimized
idk how big o notation works, but the larger you choose to have it, the longer it takes
I'm not really talking about O notation. I'm talking about... milliseconds? seconds? minutes?
I mean you said you just want a loading screen, and that really has nothing to do with threading
That's the thing, it could be all of this
If your code is running slow, then it's time to start looking into threading
Then you should probably specify that first.
It's a dungeon generator, so let's say I have 100 rooms, then it takes about 1 second
but if I have 1000, it takes about 30 seconds
Are those actual numbers?
They're close yes
I want the player to be able to choose
30 seconds of up front loading time is fairly acceptable
For the main game It'll be something small, but I want an extra thing so that the player can do whatever they want
(I'm intentionally ignoring whether that order of magnitude makes sense... it's possible that the algorithm could just be faster. Or not. No idea.)
Yeah, that's fine. It probably could be, but it's effecient enough with a reasonable number of rooms
It's kind of a judgement call on how much time you should spend modifying the procgen code to be threadable versus how much you're worried about the up front load time turning off players
I don't mind the up front loading time. That's unaviodable
I just want a loading screen without blocking the main thread
Yeah, at that point the background thread would just be making sure the event pipe is pumped.
Unity is async by nature, you don't really need threading for that
You just have a gameobject with an update loop
With the loading screen?
^ that assumes that you can break your work up into discrete steps.
Like I already said, the code freezes the main thread
Oh god I'm scared
Not necessarily... it could be "show loading screen" "spawn background thread" "background thread does one massive blocking call" "hide loading screen"
one moment
that's kinda what I want, yes
