#archived-code-advanced

1 messages Β· Page 190 of 1

undone coral
#

if you want to make a package, make a package

timber flame
#

OK, do you include data inside that package? How do you fill it?

#

Do you change that data asset after importing in a project?

undone coral
#

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

timber flame
#

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

undone coral
#

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

timber flame
#

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

undone coral
#
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

stuck onyx
#

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

buoyant vine
#

and good luck with iOS...

#

πŸ˜„

meager kite
#

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

compact ingot
meager kite
#

i know

compact ingot
#
Type type = objectModel.GetComponent<UnitBehavior>().GetType();
objectCreated.AddComponent(type);
meager kite
#

oh i didnt know GetType existed

#

would that give me my base class, or the specific abstraction of it?

compact ingot
#

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

meager kite
#

ah gotcha

#

thanks

rocky mica
#

looks like a horrible hack but it works perfectly haha

somber tendon
#

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

zenith ginkgo
proud cipher
#

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

rocky mica
#

dont cross post

proud cipher
#

you didnt asnwer

#

πŸ’€

rocky mica
#

Dont crosspost

proud cipher
#

OK

#

So help?

sterile mortar
#

This head is an NPC

proud cipher
#

Dont crosspost

proud cipher
inland delta
# proud cipher How should i assign it
[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

rocky mica
hazy epoch
#

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.

tribal pivot
somber swift
#

Ig just regular lerp

hazy epoch
somber swift
#

You can google the formula for lerp...

#

A+(B-A)t

tribal pivot
#

Yeah, cause your example seems just to be lerp(20,290, .3)

somber swift
#

a+y(b-a), thats just lerp

hazy epoch
#

πŸ’€

#

Yeah. Time to call it a night. Over here trying to reinvent the wheel. Thanks you two. 😩

rocky mica
#

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

severe grove
#

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?

hazy epoch
severe grove
rocky mica
#

interfaces, virtual classes both should work

hazy epoch
# rocky mica 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.

proud cipher
kindred tusk
#

What is the difference between ScriptableObject.Awake and ScriptableObject.OnEnable?

flint sage
#

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

kindred tusk
#

Those distinctions don't matter to me. So long as I can guarantee the code is run before any access to the object.

flint sage
#

It should be iirc

kindred tusk
#

Thanks for clarifying. πŸ™

stuck onyx
#

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?

flint sage
#

You mean you want that exception where your thread is started?

stuck onyx
#

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?

final kindle
#

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.

broken socket
#

oh wait you wanna yield during the coroutine and callback another one inbetween

#

yeah seems like a bad idea for future you

final kindle
#

It does but like... what if though?

broken socket
#

I never tried because it's baaaad design. So I'll let others answer

#

(sorry for zero help)

final kindle
#

I doubt many have tried it πŸ˜…

stray plinth
#

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

tribal pivot
final kindle
final kindle
tribal pivot
# final kindle That would be nesting. So one then the other. I'm looking for layering them, so ...
    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

broken socket
stray plinth
broken socket
#

πŸ™‚

final kindle
compact ingot
quaint flint
sly grove
#

Your class structure and JSON structure don't match

quaint flint
#

Oh
how can I fix my class structure ?

sage radish
quaint flint
#

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 ?

tribal pivot
#

You need a class with a batteryLevel and name

sage radish
#

No, ForceTube 31321321 is a string, not an object. It will be a string field in whatever object rifleBolt represents

#

Just remember to enable "Use Fields", since Unity's JsonUtility expects fields.

quaint flint
#

oh amazing

sage radish
#

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"

quaint flint
#

the json isn't smthing I can edit

#

it's generated by code one of my predecessors in the company wrote

sage radish
#

Do you intend to ignore those fields in your code?

quaint flint
#

yup

#

I think so

sage radish
#

Then it doesn't matter

quaint flint
#

the fields are emptied or filled depending of IRL manipulations

so smtimes it'll be empty

sage radish
#

The tool will generate a List<object> field for those empty arrays, which you can just remove after copying it.

quaint flint
#

i see

final kindle
#

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.

tough tulip
final kindle
tough tulip
final kindle
#

I wrote that expecting Test2 not to get called, but the console says otherwise.

rocky mica
#

That looks normal to me

#

why did you expect it to not work?

final kindle
final kindle
rocky mica
#

Your subscription happens after returning from the coroutine

#

its my imagination or this this just gonna loop forever?

final kindle
final kindle
rocky mica
#

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

final kindle
final kindle
#

Or at least, by the time I figured out a simple way to do it, this was already setup.

rocky mica
#

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)

final kindle
#

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.

rocky mica
#

hmmm yeah I think this might not be a sane workflow, for all purposes that should work

final kindle
#

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.

rocky mica
#

yeah no I think your architecture here is the issue, you might have some kind of race condition going on

#

hard to tell

final kindle
rocky mica
#

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

final kindle
#

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.

rocky mica
#

Got it, I would really need to see what your rest of the code looks alike, I cant tell the problem from this snippets

final kindle
#

This is pretty much an animation. Lerp a little to one side, tell the expressions system to do something, lerp back.

rocky mica
#

from what I can tell here, you are basically replicating the functionality of a tween engine

final kindle
#

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.

rocky mica
#

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

final kindle
#

πŸ€” 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.

rocky mica
#

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

final kindle
#

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.

undone coral
#

can you show the code where MovementFinished is called?

rocky mica
#

He said he has an invoke after the first coroutine invocation

regal olive
#

Does setting and unsetting a objects parent take up more or less resources then instantiating a new one ?

undone coral
undone coral
#

it's confusing, because there's a lot of little things that can be wrong with this code

obsidian glade
#

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

rocky mica
#

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 πŸ˜„

final kindle
# obsidian glade it sounds like you've assumed where the error is and have posted tiny snippets o...

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.

undone coral
#

well i tried

#

yeah if the objective is "reinvent dotween" use dotween

undone coral
undone coral
#

i think that's a pretty common misunderstanding

rocky mica
#

I prefer LeanTween tbh

obsidian glade
# final kindle I posted the relevet issue. I know exactly what the error is. The question was n...

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 πŸ€·β€β™‚οΈ

undone coral
#

for support

rocky mica
#

Yeah I hear a lot of people use it, I settled on dottween to how easy is to work with

tough tulip
rocky mica
#

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

undone coral
#

i meant like, to add extensions to

#

and to test

#

but yes

#

i hear you

final kindle
stuck onyx
# undone coral are you using regular `Task` or `UniTask`

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

undone coral
#

@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

final kindle
#

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?

undone coral
#

i see what you mean

#

it sounds like there was some buggy stuff

#

in general

stuck onyx
#

The main problem is I don’t see the source in the stacktrace

rocky mica
#

it is indeed your code

#

we just dont know where

#

because we only have snippets

undone coral
#

the user has had enough attention i think

#

it's fine

rocky mica
#

with the info provided, we know it is you at fault, just not exactly what it is

undone coral
stuck onyx
undone coral
#

hmm

#

anticheat in the sense of, you have a need in your game to prevent the user from modifying local system time?

stuck onyx
#

Another one was unirest, an api to communicate with a sql database, this last one was using unitask

undone coral
final kindle
# undone coral <@185859257483264001> passing an `Action` to a method doesn't make a copy of it....

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.

stuck onyx
undone coral
#

you want to communicate with a sql database using REST?

stuck onyx
undone coral
#

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

stuck onyx
#

To comunicate with postgresSql?

undone coral
#

is your goal to interact with a pre-existing API you've authored?

#

or to interact with postgres over HTTP?

stuck onyx
#

We are using a mysql database for non important stuff

#

We track users actions there

undone coral
#

can you give me the bigger picture game here?

#

just so i remember

stuck onyx
#

Unirest seemed An eassy way to do this

#

I will when i go back to the laptop @undone coral

#

I appreciate your interest

undone coral
#

a wordpress plugin... hmm.

#

okay sure

#

dont' sweat it πŸ™‚

final kindle
stone swallow
#

Hey guys, if my compute shaders work on both dx11 and dx12 is there any reason why it wouldnt on vulkan?

undone coral
#

as do the specific platforms, like android

stone swallow
#

this is the tool thats not working in vulkan

fickle inlet
#

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?

compact ingot
fickle inlet
rocky mica
#

so yeah, you can

#

there are dedicated xls/csv/excel libraries too for C#/unity if you are into that

compact ingot
fickle inlet
compact ingot
#

any reason for building it from scratch?

fickle inlet
compact ingot
#

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

fickle inlet
#

Read and write custom objects to database

compact ingot
#

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.

fickle inlet
#

It won't be anything production ready, just a practice project. Read and write data, then save it.

compact ingot
#

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"

fickle inlet
#

Is JSON achievable from scratch? I don't mind using JSON utility

compact ingot
#

yes, json parsing is fairly simple if you don't care much about performance

#

its the most achievable of the "proper" serialization formats

fickle inlet
#

I used it before with firebase but how could i achieve the same locally?

compact ingot
#

what exactly? write an arbitrary c# object to a file as JSON?

fickle inlet
#

Yes

rocky mica
#

then yeah, JSON is your best bet

fickle inlet
#

Like where would the JSON file be stored?

rocky mica
#

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

compact ingot
#

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

fickle inlet
#

It supports mobile?

rocky mica
#

that might be different

#

I havent tried it personally

#

I know android file access is a lot different than windows

compact ingot
#

Nyx, why are you hijacking this conversation?

rocky mica
#

hijacking_

#

?

fickle inlet
#

I will use the database for my calorie counter app too

rocky mica
#

what does that mean LOL

compact ingot
#

you are not contributing anything but confusion

rocky mica
#

if you are using simple data structures you can use something like JsonUtility or SimpleJSON to achieve it

fickle inlet
#

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

rocky mica
#

yeah thats just a database by definition

#

it doesnt matter if its a sql database or a csv file haha

thick birch
#

Does this look like accurate testing results? it appears the regex formatting is the fastest initial but slowest overall

compact ingot
thick birch
#

whole testing code

rocky mica
#

I assume ticks is cycles each operation took

thick birch
#

mhm

fickle inlet
#

Thank you both for the help!

thick birch
#

im doing 10 tests per type of formatting, each containing 2 string message calls

rocky mica
#

it makes sense, regex operations are more expensive

#

string operations should always be faster

thick birch
#

huh..

#

so spending so much time on making the regex one was pointless

#

is there anything faster than the substring/indexof stuff?

rocky mica
#

Slice should be faster

thick birch
#

how does that work

rocky mica
#

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

thick birch
#

what about GC generation

#

cuz thats also important emooSip

rocky mica
#

also there!

#

*might be different on unity tho haha

#

any reason you are looking this deep into optimizations? Working on big datasets?

thick birch
#

twitch integrations, chat messages

#

theoretical floor of hundreds of messages per second

rocky mica
#

makes sense

thick birch
#

on top of it executing and checking for a command list, it gets big

surreal bane
#

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.

thick birch
#

@rocky mica so slice literally does the same as substring?

#

but its slower πŸ€”

#

but also uses a lot less gc lol

rocky mica
#

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

thick birch
#

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

jovial totem
#

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

compact ingot
thick birch
#

which is better and a lot easier to read imo

#

i just want some optimizations for stuff like meta.IndexOf(startString) + startString.Length

compact ingot
jovial totem
compact ingot
#

then you'd just use that reference to continue making comparisons in the neighbouring nodes

jovial totem
compact ingot
#

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

jovial totem
compact ingot
jovial totem
#

I’m starting to think my implementation is flawed. Should I share my code because I’m a bit lost right now

compact ingot
#

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

jovial totem
#

All I need it to do is to be able to quickly find the nearest neighbor of a point cloud

compact ingot
#

thats what k-d trees are for πŸ˜„

jovial totem
#

I believe mine splits on points

#

Again should I share the code I have currently?

compact ingot
#

if you split on points you still create those rectangles that you can infer the bounds for, and you have to check against those

jovial totem
#

Also I should note I’m doing this only using value types so if it looks weird that’s why

compact ingot
#

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 πŸ˜„

jovial totem
undone coral
#

are you running your editor in vulkan on windows right now?

undone coral
#

did you try frame debugger

stone swallow
stuck onyx
#

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

halcyon schooner
#

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.

maiden turtle
#

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

lucid girder
stuck onyx
#

thank you very much

lucid girder
stuck onyx
#

cant be the ip though

#

i already discarded

#

must be something diferentbut thannks

stray plinth
random dust
#

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?

obsidian glade
rocky fractal
#
        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?
devout hare
#

Because the right side evaluates to the same value as the variable's original value

cosmic meadow
#

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

fresh basalt
#

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); } }

vital breach
#

Object Serialization...
How can I Serialize a object to send it over my server to my clients and reconstruct it WITHOUT using BinaryFormatter?

shadow seal
#

There is BinaryWriter and BinaryReader if you still want binary

vital breach
#

Is it secure? Like i dont want my clients to run remote code

shadow seal
#

They don't have the vulnerabilities that BinaryFormatter has

vital breach
#

Ok thx I will look into it.

sage radish
#

But it's not really a BinaryFormatter replacement. You can't just give it any object to serialize/deserialize.

vital breach
#

Hmmm. What type of objects work?

sage radish
#

Primitive types, like int, float, byte but also string.

#

You have to manually serialize and deserialize each field

vital breach
#

uufff

sage radish
#

Making sure you do it in the right order on both ends, otherwise things will break in weird ways.

vital breach
#

Do you know other options?

vital breach
sage radish
#

If performance or bandwidth isn't a priority, JSON is fine.

vital breach
#

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

sage radish
#

What part wasn't successful?

vital breach
#

Well the jsonString just contained {}

#

basiclly 0

sage radish
#

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.

vital breach
#

nope

#

I will give it another shot.

sage radish
#

Are you using Unity's JsonUtility or something else?

vital breach
#

jsonUtility

sage radish
#

If you want to serialize private fields, they need to have [SerializeField]

vital breach
#

ok

#

do i get it right.. my options are JSON, XML and Binary?

sage radish
#

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

vital breach
#

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)

urban warren
#

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?

sage radish
sturdy edge
#

Hello, which one is better to use?
new Vector3(0.5f, 0.5f, 0.5f) or Vector3.one * 0.5f

urban warren
compact ingot
# vital breach <@153952447516114944> Last question cause u seem to know much about serializatio...

@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

sage radish
sturdy edge
#

what about the cost, if any, of creating a new Vector3?

modest lintel
#

it copies a new one either way

sturdy edge
#

so Vector3.one does new Vector3 in the background anyway?

#

it's not some cached thing?

urban warren
urban warren
sturdy edge
#

Thank you, makes sense

sage radish
#

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);
}
wise bobcat
#

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

somber swift
# sturdy edge what about the cost, if any, of creating a new Vector3?

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

sage radish
wise bobcat
#

why would i need a service for pc

#

for pc you can even run the app in background

sage radish
#

Windows has services

wise bobcat
compact ingot
wise bobcat
#

but i dont know how to use it

#

i am literally new

sage radish
# wise bobcat do you even know what native java service calls are?

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

compact ingot
#

you use it like any other code, read its docs, understand it, tinker with it, fail and learn

wise bobcat
#

no help

#

i know found how to call the service

#

dont know how to write the native java plugin

sage radish
#

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.

wise bobcat
#

but what should i write inside that java plugin

#

so that i can make a call to it and return a bool

agile yoke
wise bobcat
#

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

#

?

sage radish
# wise bobcat so that i can make a call to it and return a bool

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");
}
wise bobcat
#

let me try it

#

please stay online till then

formal lichen
sage radish
wise bobcat
#

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

urban warren
#

Is it possible to have files outside of the assets folder included in a build, and if so, can you read them from inside?

urban warren
# wise bobcat nope

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.

wise bobcat
#

idk why do you want to do this anyways

undone coral
#

if i recall you are doing the FBX importer thing

urban warren
undone coral
#

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

urban warren
#

I wanted to try experimenting with putting each GameObject in their own file instead of storing them in scenes.

undone coral
#

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

urban warren
#

For level streaming

undone coral
# wise bobcat ohhhh thanks

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

undone coral
urban warren
undone coral
stuck onyx
#

hi @undone coral πŸ‘‹ sorry it took me so long to come back πŸ˜…

undone coral
#

you can maybe set a flag that the event was raised, then in Start run your initialization (instead of Awake) and clear the flag

stuck onyx
#

are you busy?

undone coral
#

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

stuck onyx
#

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

undone coral
#

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

stuck onyx
#

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

undone coral
#

so they approve it

stuck onyx
#

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

undone coral
#

got it

stuck onyx
#

and since uniRest was easy to install and use...

undone coral
#

unirest has a wordpress plugin - is that how you're operating its backend?

stuck onyx
#

yes exactly

undone coral
#

okay

stuck onyx
#

and its very friendly so the game designer , not a coder, can make queries without knowing sql

undone coral
#

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

stuck onyx
#

yeah but, i think i rather use microsoft, apple and google servers

undone coral
#

for analytics, use google analytics. the newest version is appropriate for apps

stuck onyx
#

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

undone coral
#

okay well

stuck onyx
#

ah no, right now i try both

undone coral
#
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

stuck onyx
#

the problem with that is you do a webrequest

#

and sometimes im getting exceptions in them

undone coral
#

it has the current date and time in every response

stuck onyx
#

and im not sure if its a unity bug

undone coral
#

to google

#

so you don't even need a time api

#

you can read the Date header

stuck onyx
#

yeah i see...

undone coral
#

so just delete this NTP thing

#

completely

#

sorry

stuck onyx
#

hehehe

undone coral
#

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

stuck onyx
#

yeah, tell me about iit, i've been working on this 3.5 years

undone coral
#

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

stuck onyx
#

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?

undone coral
#

i understand there's a desire to get personalized analytics

stuck onyx
#

never heard of it

undone coral
#

you'd have to use mixpanel

#

their people feature

#

i believe google analytics nowadays also has personalized data

stuck onyx
#

i will ttake a look for sure thanks

undone coral
#

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

stuck onyx
#

we were using the firebase one, is that what you mean?

undone coral
#

no

stuck onyx
#

google analytics for unity?

undone coral
stuck onyx
#

I didnt even know it was possible

#

πŸ˜…

#

sincerely when he talks me about data and statistics i disconnect

undone coral
#

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

stuck onyx
#

you recommended mixpanel and google's analytics v4

undone coral
#

you don't need a library

#

mixpanel is personalized

#

i assume that's why you were asked to do a bespoke analytics integration

#

because you want something like this

#

whereas google analytics is "Aggregated"

stuck onyx
#

uhmm, no i was not asked iwas simply interested in your opinion of it

undone coral
#

ah

#

i think it is very very good for app developers

stuck onyx
#

okay this looks good

undone coral
#

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

hollow cipher
#

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?

undone coral
#

instead of coming up with your own ideas and trying to visualize it

stuck onyx
#

so mixpanel is the dashboard but the data comes from analyticcs integrated in your code

#

correct?

undone coral
stuck onyx
#

ah ok ok

undone coral
stuck onyx
#

thanks i will defiitively take a look

hollow cipher
#

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.

void spruce
plain abyss
#

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

gray pulsar
plain abyss
#

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

tidal depot
#

Does anyone know how to use the Localization Pack?

plain abyss
#

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?

zenith hedge
#

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.

rocky fractal
#

The jump is not working when on the wall, it gets stuck on the slidding

somber tendon
zenith hedge
#

No im actually talking about the code part

compact ingot
zenith hedge
#

Obviously I get that, but the whole mechanism behind holding the spacebar etc...

#

getting the good said amount even when releasing

compact ingot
#

whats unclear about doing that? this seems kinda trivial.

zenith hedge
#

Having a mind block

compact ingot
# zenith hedge Having a mind block
float howSweetAreWe = 1f - Mathf.Clamp01(Mathf.Abs(timeSinceKeyDown - sweetspotCenterPosition) / howBigIsTheSweetSpot);

and

fillAmount = Mathf.Clamp01(timeSinceKeyDown / maxTime);
rocky fractal
#

How do i make this work? when i press shift it just goes faster down

zenith hedge
compact ingot
quasi granite
#

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.

compact ingot
quasi granite
#

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.

compact ingot
#

does not matter, MonoBehaviour, SO, custom stuff, its all the same

#

easiest would be a manager-type/singleton MonoBehaviour

quasi granite
#

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.

compact ingot
#

these are completely irrelevant concerns

quasi granite
#

this is true

compact ingot
#

if a monobehaviour has no Update/Start/Awake defined those obviously dont get called

#

a transform that does not move produces 0 performance overhead

plain abyss
#

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?

somber tendon
#

sigsegv usually has something to do with memory violation, so yeah, maybe memory leak

jovial totem
#

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

undone coral
# quasi granite Okay, I need some help. Im kinda at a loss of what do to. I created an item syst...

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

undone coral
#

what are you trying to do

quasi granite
#

probably due to lack of c# and unity knowledge but either way i dont get it lmao

somber tendon
#

it will be easier to parse/serialize the Item, than serializing each property one by one

compact ingot
# quasi granite I dont understand why the difference between these two matters at all, gonna be ...

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

quasi granite
compact ingot
# quasi granite Wait, what do you mean by mutate or immutable in the first place? and <@2477931...

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

quasi granite
#

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

compact ingot
quasi granite
#

aight aight thank you for the clarification and help.

#

yall are continuously wonderfully helpful in this server

jovial totem
short junco
#

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

thin wedge
#

whats the error?

short junco
thin wedge
#

thats it? i think it provides the actual types that you are attempting to cast, at least sometimes

long ivy
#

sounds like your IsScriptableField extension method is buggy

short junco
#

maybe public static bool IsScriptableField(this FieldInfo field, ScriptableObject scriptableObject) { return field.GetValue(scriptableObject).GetType().BaseType == typeof(ScriptableObject); }

short junco
#

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);
            } ```
untold moth
#

Yeah. Dynamic is a pretty bad idea in a strongly typed language.

short junco
#

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
untold moth
#

Should use inheritance or interfaces instead.

short junco
untold moth
#

Could always use object.

#

And cast it

kindred tusk
#

Do colliders move with rigidbody or transform?

#

For the purposes of raycasting

kindred tusk
maiden turtle
#

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

long ivy
#

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

lucid girder
maiden turtle
#

I need the price tag to scale dimentions with the button

#

that's basically it

remote drift
#

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;
        }
main stump
#

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

carmine agate
river tartan
#

Can we run a model dll whose target framework is net core 3.1 in unity?

eager reef
#

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

#

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

β–Ά Play video
round jacinth
#

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.

flint sage
#

Wave function collapse?

#

O h wait

#

I misread

kindred tusk
weary stag
#

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?

sly grove
#

maybe use a normal for loop?

weary stag
#

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.

sly grove
#

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

weary stag
#

Well yeah, recursion is an issue but in this case, it's quite necessary.

sly grove
#

recursion is never necessary

#

anything you can do recursively, you can do iteratively

weary stag
#

Not saying you can't, but the thing is, an iterative function would be way too complicated.

sly grove
#

probably not as complicated as you think

weary stag
#

It's like going through a tree of billion nodes.

#

That's what MoveGeneration does.

sly grove
#

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

weary stag
#

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.

sly grove
#

nope

#

it'd be almost exactly as long as this

#

and be faster

weary stag
#

How would you do it then?

#

I'm genuinely curious now.

sly grove
#

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

weary stag
#

What?

#

I'm confused by what you mean.

sly grove
#

why can't you use basic data structures?

weary stag
#

Because again, heap allocation. I'm trying to avoid it.

sly grove
#

it's a small allocation. Is this a Job?

weary stag
#

I'm allocating everything on stack except the Enumerators right now. It's what has given me a speed of 70M nps right now.

sage radish
#

You can make a custom struct enumerator that doesn't allocate. Most of the built-in collections do this, like List.

sly grove
#

I think you're worried too much about allocation instead of the big picture of overall performance

weary stag
#

How do they do that?

#

I don't get it - how's stackalloc related to Enumerators?

sly grove
#

It doesn't I was responding to a question that wasn't asked but I thought was asked

sage radish
# weary stag How do they do that?

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.

sly grove
#

You'd have to explain what MoveList is and what MoveList.Get returns

weary stag
weary stag
weary stag
#

Do you mean make it a ref struct?

sly grove
#

Is this a Chess game

sage radish
hollow garden
weary stag
weary stag
sage radish
weary stag
#

I see.

#

I can try it but I have a feeling that with the amount of copying, it'd actually be slower.

maiden turtle
#

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

sage radish
#

And the copies are all in stack memory, which is a lot faster than heap memory

weary stag
#

Ah it seems doing such has another issue - Parallel.ForEach() expects an IEnumerable.

misty glade
#

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:

  1. Create copy of Database-Production-v6.0, name it "Database-Production-v6.1"
  2. Run Migrate-v6_0-to-v6_1.cs against it
  3. Change configuration settings of game server to point to the new database.
  4. 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..?

sage radish
#

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.

weary stag
#

What do you mean as an indexer?

sage radish
#

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?

hexed meteor
#

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

weary stag
#

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

sage radish
#

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.

weary stag
#

That would mean having to convert it first into an array by looping and then passing an array (looping over it again)

sly grove
#

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?

sage radish
weary stag
#

Well, if I wanted to do that, I could use Stockfish. I'm trying to make my own.

sly grove
#

Looks like you're starting wiht a C# port of stockfish

#

unless this is your port

hollow garden
#

he wants to make his own chess engine

weary stag
#

I'm not porting Stockfish lol.

sly grove
weary stag
#

Does it really convert IEnumerable into arrays to loop in parallel?

sage radish
#

How else could it do it?

weary stag
#

This is the internal code of Parallel.ForEach

sage radish
#

Yeah I looked at it, but I didn't go far enough to see what it ends up doing with the IEnumerable

weary stag
#

It creates a Partitioner

#

not sure what that is

#

I don't think it makes it into an array afaik.

#

actually

#

it does

sage radish
#

My guess it's partitioning the workload into chunks, so it's not converting your whole enumerable into one big array, but chunks.

weary stag
#

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

sage radish
#

Is this project specifically for Unity or are you trying to make a general C# library?

weary stag
#

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)

sage radish
#

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.

weary stag
#

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.

maiden turtle
#

it might be "10" it might be "1234567890"

maiden turtle
#

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?

sly stag
#

That's a question better suited for the asset creator

undone coral
misty glade
#

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

undone coral
#

how do you deploy your backend right now?

misty glade
#

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"

urban warren
#

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.

jovial basalt
#

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

red osprey
#

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.

urban warren
cunning grove
#

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?

flint sage
#

No solution you mentioned is safe

jovial basalt
flint sage
#

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

cunning grove
#

For real?

urban warren
#

Yeah and with a situation like this it should be really easy.

cunning grove
#

Okay, good to know

#

I'm only using a few UnityEngine things in my code, Vector2Int and Random.Range

urban warren
#

Considering it is just a one and done thing. This assumes you are not loading GameObjects and stuff

cunning grove
#

So basically what you're saying is just handle the threading myself?

flint sage
#

Yes

urban warren
#

Yup

cunning grove
#

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?

red osprey
#

Threading is not that complicated (ten thousands asterisks).

cunning grove
#

lmao

sly stag
#

Just look into System.Task and see how deep the async rabbit hole goes

cunning grove
red osprey
sly stag
#

I mean you can work directly with threads if you really want, I don't think you do

cunning grove
#

oh okay

red osprey
#

Ohhh I misunderstood.

cunning grove
#

God I'm so confused, there are so many different opinions on this

red osprey
#

So... they're all threads. The biggest question is what exactly you're doing.

sly stag
#

Just google "C# threading"

#

Main thing to keep in mind is that you can't interact directly with Unity's thread with your threads

red osprey
#

Like is the "procedural generation" code really all that expensive?

cunning grove
#

It's quite expensive depending on the number of iterations you choose to do

sly stag
#

Impossible to say without seeing the code

cunning grove
#

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

red osprey
#

I'm not really talking about O notation. I'm talking about... milliseconds? seconds? minutes?

sly stag
#

I mean you said you just want a loading screen, and that really has nothing to do with threading

cunning grove
sly stag
#

If your code is running slow, then it's time to start looking into threading

red osprey
#

Then you should probably specify that first.

cunning grove
#

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

red osprey
#

Are those actual numbers?

cunning grove
#

They're close yes

red osprey
#

Okay cool.

#

How many rooms did you want to generate?

cunning grove
#

I want the player to be able to choose

sly stag
#

30 seconds of up front loading time is fairly acceptable

cunning grove
#

For the main game It'll be something small, but I want an extra thing so that the player can do whatever they want

red osprey
#

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

cunning grove
sly stag
#

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

cunning grove
#

I don't mind the up front loading time. That's unaviodable

#

I just want a loading screen without blocking the main thread

red osprey
#

Yeah, at that point the background thread would just be making sure the event pipe is pumped.

sly stag
#

Unity is async by nature, you don't really need threading for that

#

You just have a gameobject with an update loop

cunning grove
red osprey
#

^ that assumes that you can break your work up into discrete steps.

sly stag
#

Yes

#

Well having a loading screen at all assumes that

cunning grove
#

Like I already said, the code freezes the main thread

sly stag
#

Then you need to fix your code

#

Pastebin it

#

Let's see

cunning grove
#

Oh god I'm scared

red osprey
#

Not necessarily... it could be "show loading screen" "spawn background thread" "background thread does one massive blocking call" "hide loading screen"

cunning grove
#

one moment

cunning grove
sly stag
#

You're probably using a while loop in Update or something similar

#

Rather than treating Update as an asynchronous method run every frame