#archived-code-advanced

1 messages · Page 71 of 1

north marsh
#

yes, the migration process was a basically a drop-in 1-1 replacement for me. We do have a few coroutines but we converted them too

scenic forge
#

If you have rewritten coroutines to UniTask, one gotcha is that coroutines get auto killed when the MB is destroyed while C# task/UniTask don't and you have to handle that on your own. That's one place to check.

north marsh
#

I am not sure. The only reason I am blaming unitask is 1) performance issue happen after I integrate it 2) I am unfamiliar with this blackbox

scenic forge
#

Oh and UniTask has "UniTask Tracker" in editor, you can open that and check if you accidentally leak tons of tasks running forever.

north marsh
#

btw do you have suggestion to deal with "not responding"? I tried collect log from players but logs aren't very helpful in pinning down the cause - it just get truncated.

#

[Game Name] is not responding

scenic forge
#

No sorry.

#

Best case scenario is to find a way to reproduce the issue directly in editor, so you can use all the profiling tools.

north marsh
#

yeah

sly grove
north marsh
sly grove
#

no

north marsh
#

what error you get if you get to memory 100%?

sly grove
#

i mean theoretically if rendering takes a really long time that's blocking

sly grove
#

something along those lines

#

or a hard crash

north marsh
#

ok

sly grove
#

if it's in the unmanaged section of the engine

edgy pivot
#

how can i change the width of an image (in pixels) via a script?
like :
myimage.width = whatever;

half swan
half swan
thin merlin
#

I could use some assistance. How to I make it so moving up with always move the player in the direction the active camera is facing?

#

Let me be more specific: I'm making a third person game with different types of cameras (think Silent Hill or classic Resident Evil). I need the character to mover correctly when the camera is rotated. How do I make it so that the movement directions act relatively to the camera?

tiny pewter
#

Camera direction is its transform.forward
I dont understand why not the camera follow the player but the player follow the camera

half swan
#

Like it jumps there

thin merlin
#

yeah, so for example if you were to hold right, you'd just run in a circle around. Likewise, if I were to have the camera face the opposite direction, suddenly down moves the player forward and up moves them backward. I want to know how to prevent that from happening in a way that works well.

#

That's the effect I'm trying to achieve.

sly grove
#

I hate to say it but this is kind of a #💻┃code-beginner question.

Project your camera's forward vector on the gameplay plane (y axis normal plane in this case). Then make a LookRotation quaternion and multiply your input vector into it.

Or project your camera's forward and right vectors on that plane and compose the movement vector from those normalized directions.

thin merlin
#

See I figured it would be something simple like that, but I tried multiplying the movement vector by the quaternion of the camera and only got an error. What would the code for that look like?

tiny pewter
#

you can use the transform.forward and left of active camera without quaternion.....

#

i forgot how the property of transform direction on x axis is called (left or right)

thin merlin
#

It's a simple solution I'm overthinking, or I just don't know how to set up the code in this particular case.

tiny pewter
#

get and copy the direction and set its .y to zero then you get the direction vector projected on xz plane

thin merlin
#

then you get the direction vector projected on xz plane What would an example of that code look like? I know how to do the first part.

thin mesa
#

Vector3.ProjectOnPlane

thin merlin
#

ah, that is a new function for me

brisk spruce
thin merlin
#

Vector3 movement = new Vector3(move.x, 0, move.y);

movement = Vector3.ProjectOnPlane(movement, camRotQuat.eulerAngles);``` So this didn't work. Now my horizontal movement is bust. Clearly I did something wrong here ...
thin merlin
austere jewel
#

eulerAngles isn't a vector you should be projecting onto anything, it's a rotation expressed in degrees, it makes no sense as a direction

thin merlin
#

So what do I use instead? Do I need to do something else entirely? I see on the API that they do something with degrees and radians ...

#


        //Vector3 planeNormal;
        //Vector3 response;
        //float radians;
        //float degrees;

        // Compute a normal from the plane through the origin.
        float degrees = Random.Range(-45.0f, 45.0f);
        float radians = degrees * Mathf.Deg2Rad;
        Vector3 planeNormal = new Vector3(Mathf.Cos(radians), Mathf.Sin(radians), 0.0f);

        movement = Vector3.ProjectOnPlane(movement, planeNormal);```I didn't expect this to work, and expectations met.
#

This is one of those things where once I've seen how it's done once it'll be so clear that I'll never need to ask again, but until then the answer is eluding me.

brisk spruce
#

ohh I see the issue, aight

proper field
#

Hey guys I need a help with this code

proper field
austere jewel
thorn flintBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

sly grove
left idol
#

Hey, I'm looking for the opinions of whoever might want to chime in:

I'm designing an inventory system, and had the choice to either use events, or just somewhat tightly couple my inventory with my UI. The inventory is very barebones and I won't be doing anything fancy. I went for the tightly coupled approach, because I dislike having "manager" classes and empty objects in my scene, as they eventually just turn up being boilerplate. Additionally, it doesn't violate single responsibility: every component does exactly one thing (even though I'm sure I could simplify it further.)

Would you make the same choice for a extremely barebones inventory for a pretty simple game, or would you go the event pathway? For me, the biggest turn off on the event pathway was that I needed to communicate with gameobjects that were not active (e.g. the menu), which would require a middleman class.
Thanks for reading, if you did. I appreciate whatever feedback. cattoblush

tropic vigil
dusty wigeon
hushed fable
left idol
#

@tropic vigil That's essential to me as well. I meant more the approach of either directly referencing say, the Player's inventory from the UI class (the classic drag and drop the reference in the inspector) as opposed to using events to communicate between layers, which requires some more setting up but is eventually more scalable. I've the feeling I might be missing something by not using events, thus the "question".

left idol
hushed fable
left idol
#

Mind you, I realise I could have an empty object manage the state of the menu, but I'd rather not as I don't like clutter in my scene

#

Aha, I see what you mean

brisk spruce
#

Im attempting to make a custom panel with custom editor properties for UI-Toolkit stuff, the custom properties show up in the editor but when I modify them, they dont persist. The X_Pos and Y_Pos values default to 0 instead of 0.5, and they just reset to 0 everytime I click away, did I miss something important?

https://hatebin.com/jrgrklcazm

#

can see in the UI the three fields show up at least

dusty wigeon
#

You should try to look into how to correctly apply/create a serialize property.

brisk spruce
#

I did lol

dusty wigeon
#

I've pretty limited in my knowledge of UI Toolkit, however this issue is frequent in Custom Editor as well.

#

Sometimes it is because you forgot to mark your class as System.Serialize, other it is because you didnt apply the modification on the prefab with PrefabUtility.RecordPrefabInstancePropertyModifications, maybe even SerializedObject.ApplyModifiedProperties has not been use correctly.

brisk spruce
#

none of that applies to these guys, they are a different class and different implementation

dusty wigeon
#

As I said, the symptom are the same which means that the issue most be simular.

#

I just gave you things that I know that can be an issue in the other implementation.

#

Just take note of that while doing your research as it can provide you point of reference.

brisk spruce
#

wow this one was esoteric, and maybe its in the docs but I have looked twice now and dont see it.

Your name property of the attribute descriptor must match exactly a kebab-case to PascalCase of the property it binds to, pure magic string stuff that uses reflection to bind

#

so I changed name to be x-pos and then the property to be XPos and now it binds fine

dusty wigeon
#

So, I guess the serialization was the issue.

brisk spruce
#

yeah but in the wonderful "silently fails and docs dont mention anything about it" sort of way, wheee

dusty wigeon
#

It is still an API in progress.

#

You might want to include your feedback.

brisk spruce
#

yeahhh... this seems like basic stuff though, how hard is it at least to log a warn or error that it binded to a property that didnt exist, it should throw something to go "hey I tried to set a value and didnt find a match" instead of just... silently failing :/

jolly token
brisk spruce
#

this feels like if css and XAML had a frankenstein baby, but in a back alley so its not documented much at all :x

thin merlin
dry bear
#

Did you get FlatSharp to compile in mobile platforms?

flint sage
#

And it does code gen which is not supported

dry bear
#

I am basically trying to serialize data in the Unity client and send it using sockets to a C++ server, and viceversa. Is Flatbuffers a good library for that? Or are there better options out there?

flint sage
#

Sure if you can make it work on mobile 😛

#

Oh, iirc some libraries support pre-generating the code gen bits

#

So it might work

#

But I haven't tried it myself

dry bear
#

I thought it would just be a matter of pasting the mobile library files in the Plugins folder

#

But I don't know how to even generate those files

scenic forge
#

With Protobuf, I think you can feed the CLI your schemas and it will generate the C# sources for you, so that one should work for IL2Cpp (untested)

jolly token
#

There are many serialization protocols libs you can try

#

Anything does build time codegen would make most sense for IL2CPP

dry bear
#

but I don't know if that would work if I'm building on Android

#

based on this I guess it won't work

jolly token
#

You don't need flatc on Android

#

The platform you need to care about that is the one you are using Unity on

dry bear
#

oh

#

I will only be using it on Windows and MacOS

jolly token
#

So that is not a problem

dry bear
#

nice

#

but will the library work on Android if the plugins folder has these files?

#

I had it mind that for Android there were different library files (.so)

jolly token
#

That is compiled thru IL2CPP

#

Things like .lib .so .a etc is native lib which will be linked without IL2CPP
Anyways those are not the case here

dry bear
#

oh okay, so basically it should be included just fine in an Android or iOS build

#

because it will get compiled into c++?

jolly token
#

Yeah

dry bear
#

cool, thanks I'll try it 🙂

torpid birch
#

nICE

#

guys can i ask you something

#

please

fresh salmon
#

If it's about advanced programming concepts, sure. Else find the most appropriate channel at #🔎┃find-a-channel

torpid birch
#

Yes

#

so talking tom voice record and playback are Hard ?

#

because i am making talking tom Clone

half swan
# torpid birch Yes

I saw your questions when you were muted yesterday for spamming. This is the wrong channel.

torpid birch
#

i am sorry

#

because i was angry yesterday

#

Please don't mute me or ban me <:3

half swan
torpid birch
#

YES <:)

#

i swear

#

i just need help on my game

#

Hello ?

brisk spruce
#

you are spamming again lol

torpid birch
#

is anyone there ?

#

No

#

this is not spam

frozen imp
torpid birch
#

YES I DID

#

BUT I AM NOT SPAMMING

brisk spruce
#

Id recommend reading it again

torpid birch
#

WHAT THE MEANING OF SPAM

hardy sentinel
#

first of all you type 1 full sentence in like 4 lines.. how's that not spam? 😄

fresh salmon
#

You are spamming right now

hardy sentinel
#

look at the picture on my screen -- it's full of your messages

#

even more -- there's not 1 bit of useful info.. if that's not spam, then idk what is 😄

fresh salmon
#

Sending multiple messages in a short succession is spam

brisk spruce
frozen imp
#

@torpid birch There's no off-topic here. If you are not asking questions or answering them - you're spamming.

torpid birch
#

Ohhh i am sorry about that 😅

brisk spruce
#

also all caps is considered rude and disrespectful / shouting, and is another good way to get muted

buoyant marsh
#

Does anyone here have Gradle experience?

brisk spruce
torpid birch
#

my bad

buoyant marsh
brisk spruce
fresh salmon
#

100% of my Gradle experience is :BUILD FAILED lmao

brisk spruce
#

^

torpid birch
#

are you using android

buoyant marsh
#

Yeah im using android

#

is there another way for me to run a build on my phone without using Gradle?

torpid birch
#

if you are using android download new gradle

brisk spruce
#

actually fun fact, the one time I had success with gradle was natively compiling android apps... on android

buoyant marsh
#

It only broke when I updated from 2020.*.* to 2022.3.5f1

#

I am using the newest version of gradle

torpid birch
#

on gradle website

buoyant marsh
#

As well as the newest LTS release

brisk spruce
buoyant marsh
#

Im not sure what else I could use though

torpid birch
#

i also had this problem but i fixed them

brisk spruce
#

something something java runtime SDK openjdk gradle foo bar phi package builder tools android google something something

torpid birch
#

to fix it you need to add user keystore to your game

buoyant marsh
torpid birch
#

Trust me

buoyant marsh
#

Check out this thread if you wouldnt mind 🙂

brisk spruce
torpid birch
#

i hope she work

buoyant marsh
torpid birch
#

do it

frozen imp
#

Good sanity check is to create a new project and test if it will compile with needed settings empty

torpid birch
#

now you are spamming

frozen imp
#

!mute 980625836875063348 7d Ignoring warnings. Spam

thorn flintBOT
#

dynoSuccess issamiyad#0 was muted.

buoyant marsh
# frozen imp Good sanity check is to create a new project and test if it will compile with ne...

Yeah I had done this to find out it was REALLY broken. I was using the older version of unity for my project when I had the first gradle issue, so I then updated unity in hopes that it would fix the gradle issue but it didnt. I ported the old version of my game to the new verison of unity and it still didnt work so I created a new version of the game as well as downloading the most recent version of gradle. I copied everything from the new version of gradle binary folder into the correct directory in the unity files but im worried there might be more

#

Do you think if I just grabbed all the gradle files and copied every single one that could work?

#

I assume the issue is outdated files based off the console logs that I have

frozen imp
#

I don't have any experience with gradle. You might want to try forums for more long term questions.

buoyant marsh
#

Alright thanks man, much appreciated

brisk spruce
#

this ui toolkit stuff seems to be buggy as hell, when it comes to something as simple as just using a sprite as a background image

flint sleet
#

Is there any way to get a summary of all profiling results in the unity profiler rather than inspecting frame-by-frame? I want to see across all recorded frames, which of my script methods took up the most cpu time. Ideally also across all threads

dry bear
#

Hey guys, I'm trying to find a good library to send data between a Unity client and a C++ server.

I was looking into Flatbuffers but the whole schema thing seems little flexible to me.

I would like to be able to do something like:

buffer.Write<int>(123);```

And from the other side do:
```string s = buffer.Read<string>();
int i = buffer.Read<int>();```
#

I don't like Flatbuffers because I think I would need to define a different schema for every message type that I send, which seems like a lot

#

do you know of any libraries that can do that?

jolly token
dry bear
#

yes

#

well, the game I'm doing is point and click so it's not like an FPS where you're constantly sending data

jolly token
#

Okay so the format can be just Json then?

dry bear
#

I feel like Json would be really slow

#

I read somewhere that compared to Flatbuffers is 40x slower

fresh salmon
#

There's BinaryWriter that can write to any Stream, you choose what to write like in your example

jolly token
#

They're using C++ server vs C# client so may need some more tuning than BinaryWriter

fresh salmon
#

Well it works on the encoding side at least

dry bear
#

yeah I tried BinaryWriter and Reader but a string sent in C++ wouldn't match, so that's why I started to look into packages

dry bear
#

maybe it's not that bad to use Flatbuffers 😂

jolly token
#

Add more API servers 😄

fresh salmon
#

What about something like messagepack? It's compact so it uses less bandwidth, and it's a global standard with a lot of implementations

jolly token
#

MsgPack is not bad but might have some friction with IL2CPP

thin mesa
#

it shouldn't, just need to use the AOT generation. but that's required if you're targeting anything other than .net framework with mono anyway

dry bear
#

I'll check that out

jolly token
#

Anyways I would recommend defining message format, it’s worth doing it

dry bear
#

the thing is, in my netcode I plan to first get an enum value from the byte[] that I receive so that it tells me what type of message it is, and what data I can expect to retreive from that buffer

#

but how can I read this first enum using Flatbuffers?

#

I think message pack is closer to what I'm trying to do, since you can do:

    public UnitInfo Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
{
    var count = reader.ReadArrayHeader();
    var unit = (LengthUnit)reader.ReadInt32();
    var abbreviation = reader.ReadString();
    var baseUnit = reader.ReadMessagePackObject<BaseUnits>();

    return new UnitInfo<LengthUnit>(unit, abbreviation, baseUnit);
}```
scenic forge
#

Pretty sure FlatBuffer can do union types.

dry bear
#

how could I use union types to know what type of package I'm receiving?

#

I fee like I'm complicating an easy thing to do, I just want to be able to do this:

From client:

buffer.Write<int>(123);```

From the server:
```string s = buffer.Read<string>();
int i = buffer.Read<int>();```

And in cases I want to read an int first so I know what I will have to read afterwards.
scenic forge
#

If all you want is just simple data types like string and various numbers, then yeah just have your own spec and implement in on both sides. String could be “4 bytes (string length) + length bytes (UTF8)”

#

The reason why people are suggesting these existing solutions, is that eventually you are just reinventing schema. An event being exchanged will very unlikely to be just one piece of data, a player moved event could be “1 byte (event type) 4 bytes (player ID) 12 bytes (position)” so you end up writing code on both sides encoding and decoding that, which is what a schema is.

thin merlin
#

GameManager.input.Player.Attack.performed += x => NullAction();So I have this code using the new input system, but I don't really know what the x is accomplishing here. I just know that the tutorial said it was required to just work. Is there something else I can put there, like a set of conditions (bool check or etc.)?

brisk spruce
#

Finally figured out a wicked clean way to type safe pub/sub to INotifyPropertyChanged, and boy does it feel good

dry bear
#

but let's say that from the server you receive an array of bytes, how do you know what schema to deserialize it to?

thin merlin
#

basically I want to make it so the attack button doesn't get set to NullAction() if a condition is true, and I want to know if I can save myself a line for an if statement in this case.

brisk spruce
#
public void BindTo<T>(Expression<Func<GameState, T>> selector, Action<T> method)
{
    var fmn = selector.GetFullMemberName();
    var compiled = selector.Compile();
    PropertyChanged += (_, e) =>
    {
        if (e.PropertyName != fmn)
            return;
        method(compiled(this));
    };
}

And then all I do is something like

GameState.BindTo(s => s.RoundCount, OnRoundCount);

private void OnRoundCount(int roundCount) => ...
scenic forge
brisk spruce
#

protobuf was pretty much entirely designed for this exact use case

#

combine it with uh, whats it called... mediator pattern

#

and/or strategy pattern

scenic forge
#

The “reading first byte and switch on it to deserialize rest of the bytes based on that type value” is all done for you by those solutions.

dry bear
#

oh

#

okay, didn't know that

brisk spruce
#

protobuff also does that sorta stuff in some form of automagical way thats at the "some team of engineers with dozens of years of experience combined and multiple PHDs on the topic" level

#

where you just define the protobuf file and then it just builds out C# files for you automatically and you just call .serialize or .deserialize on a byte array and it just gestures vaguely makes it happen

#

and it has a whole way to define a variety of types a payload can have using the OneOf attribute or whatever its called in protobuf, so you just go
OneOf foo, bar, phi and itll have one of em set and the rest null

dry bear
#

and how do you know what type it is when you deserialize? can you maybe do a switch based on the type?

brisk spruce
#

so you can just do like

if (packet.ObjectA != null)
   return DoThingAWith(packet.ObjectA);
if (packet.ObjectB != null)
   return DoThingBWith(packet.ObjectB);
if (packet.ObjectC != null)
   return DoThingCWith(packet.ObjectC);
#

maintains full type safety, no reflection/type casting/etc needed

dry bear
#

have you tried FlatBuffer? I think it's similar to protobuf

brisk spruce
#

I have not, theres a few solutions, protobuf is just the one I am familiar with

dry bear
#

could you show me an example of deserealizing a byte[] that you don't know the type of? I haven't seen anything online 😦

#

I see everywhere this:

{
    var myPerson = Serializer.Deserialize<Person>(fileStream);
    Console.WriteLine(myPerson.FirstName);
}```
#

but in the case of receiving a network message you can't just do Deserialize<Person>

brisk spruce
#

So you'd just do

var packet = MyPacket.Deserialize(filestream);
if (packet.ObjectA != null)
   return DoThingAWith(packet.ObjectA);
if (packet.ObjectB != null)
   return DoThingBWith(packet.ObjectB);
if (packet.ObjectC != null)
   return DoThingCWith(packet.ObjectC);
#

oh sick protobuf 3 now even has a specific method for checking if its set, it has an enum that gets generated

#

so in there example code you could do:

var packet = MyPacket.Deserialize(filestream);
switch (packet.AvatarOneofCase) {
    case AvatarOneofCase.ImageUrl:
        return DoThingWithImageUrl(packet.ImageUrl);
    case AvatarOneofCase.ImageData:
        return DoThingWithImageData(packet.ImageData);
    default:
        break;
}
dry bear
#

so if you have let's say 50 different message types that you want to send, you need to create 1 class with 50 fields ?

brisk spruce
scenic forge
#

You’d create a schema, the classes will be codegen’d for you.

brisk spruce
#

you can nest oneofs no problem, so you can divvy them up into groups and even groups of groups if you need

#

for organization/sanity purposes :p

dry bear
#

so you only have 1 schema and inside that schema all the different message types?

brisk spruce
#

thats where Mediator pattern and/or Strategy pattern can come in to help your sanity out for organization

brisk spruce
#

at the root you just have "packet"

#

protobuf is wicked fast so dont worry about if this sounds clunky, its actually incredibly fast performance wise

scenic forge
#

Even better, with that schema you will get code for both the C# and C++ side; if you ever need to add/change/delete something, do it to the schema and regenerate again, both sides are always in sync.

dry bear
#

but isn't the packet that's being sent going to be super big if it needs to contain info about all the packet types? maybe I'm missing something

brisk spruce
#

it does weird fancy stuff to serialize extremely fast and extremely small

#

you dont need to worry about the "how" part because people way way smarter than all of us solved that part for you, like, PHD engineers at google built this stuff and released it open source

scenic forge
#

If you have one message type “1 byte (message type) + 4 bytes (int health) + 4 bytes (int life)” and another message type “1 byte (message type) + 8 bytes (double some data)” the message is just 9 bytes not 17 bytes

#

Based on the first byte it will interpret the next 8 bytes differently.

brisk spruce
#

effectively it "re-uses" bytes and does some wild compression stuff too

dry bear
#

could you show me an example of schema for different packet types?

let's say I have a type of message called "PlayerPos" that has a string and a Vec3

and another message called "ChatMessage" that has two strings.

how should I put that inside the schema file?

#

sorry if it's too obvious

brisk spruce
#

The link I posted above has examples

dry bear
#

would this be the right way to do it? this is the flatbuffers schema

brisk spruce
#

I have no idea about flatbuffers

dry bear
#

it's the same concept as in protobuf definition

#

hmm I don't know if flatbuffers has the oneof property

brisk spruce
dry bear
#

I think I could actually do something like this


table EventOne  
{  
  id:uint;  
  timestamp:ulong;  
  adress:string;  
}  

table EventTwo  
{  
  id:uint;  
  timestamp:ulong; 
  strength:float;   
}  

union Events {EventOne, EventTwo}  

table EventHolder  
{  
  theEvent:Events;  
}  

root_type EventHolder;  ```
#

the union basically says that there will only be one of them

sweet vessel
#

I'm trying to create Procedual Island Maps. I can Generate the Procedual Maps itself but I'm struggeling to figure out how to apply the Falloff for the islands

arctic lake
#

I figured out how to get access to my phone's camera using unity. The problem is that while my phone is in portrait mode, my phone's camera is in landscape mode. So like, I have to tilt my head in order to see correctly with my camera. Does anyone know a way to fix this?

dry bear
#

omg it works

#

so cool

jolly token
dry bear
#

I think this is to be able to call a function from the server in the client?

#

not sure how that would work tbh

jolly token
obsidian coyote
#

how can i tell where these allocations are coming from? When I look purely at the CPU usage module and the call Hierarchy i dont see any allocations at all there?

dusty wigeon
obsidian coyote
dusty wigeon
#

The hierarchy section should have a column with GC.Alloc

obsidian coyote
#

that said, i was profiling with the standalone process option to try and eliminate and perf overhead the in-process version has, but it seems it misses some stuff

dusty wigeon
#

Also, 6kb sometimes is not something unusal.

obsidian coyote
#

looks like its caused by this

plucky laurel
#

deep profiling will show you exact method that generates

dusty wigeon
#

You also have the option to add Profiler.BeginSample to refine the search if Deep Profiling is not an option

dry bear
#

@jolly token I created a template to avoid repeating the same code over and over, I can reuse it for multiple packet types now 🙂

obsidian coyote
#

appears to be caused by disabling a UI element, kinda wild that unity would cause an allocation when you disable a built in component type :S

dusty wigeon
plucky laurel
#

tmp etc

#

i still consider tmp a third party, just realized

obsidian coyote
#

i was intentionally pooling my game objects for recycling which works as intended on most things, but i decided to use unity's canvas for health bars with the slider component

plucky laurel
#

are you reparenting them when releasing to pool?

dusty wigeon
#

Canvas can be tricky If I remember correctly.

#

Solution: Disable the object first, then reparent it into the pool.

#

Additionally, disabling the Canvas component does not trigger the expensive OnDisable/OnEnable callbacks via the Canvas hierarchy.

plucky laurel
#

my thought was more about the transform type, i am not sure but reparenting a rect tr to a normal tr can cause allocation?

obsidian coyote
#

i disabled the healthbar stuff entirely, looks like something is still allocating memory but now it wont tell me what, even with deep profiling :S

plucky laurel
#

collapse player loop

#

is there anything else? editor or something

obsidian coyote
plucky laurel
#

scrub it maybe some spike will show something

dusty wigeon
#

Maybe some native allocation ?

#

I know that the memory profiler sometimes is not able to correctly see every allocation.

#

I had to use the Memory Tracker for the Nintendo Switch to find out a leak that was not showing in the Memory Profiler.

obsidian coyote
#

when i scrub it its always 0 :S

#

maybe its on one of these other threads that unity appears to create, i checked a bunch, but didnt see any allocations tho, maybe i missed them though

plucky laurel
#

check them all

#

diligently, we'll wait

#

🙂

obsidian coyote
#

LOL

#

im guessing even if i do somehow figure out what it is, its likely built in unity bloat and i have no way of doing anything about it, since im still seeing the spikes even when ive disabled almost everything in my scene 😐

plucky laurel
#

i feel the same way

obsidian coyote
#

and here i wanted to flex a 0b allocation game to the other game devs i work with lol, oh well :S

plucky laurel
#

well your code is 0, it counts

long ivy
obsidian coyote
tropic stag
#

I deleted my plist file (on osx) and my standalone build is still reading a value, I think I'm deleting the wrong file. is there a way to Debug.Log the playerprefs path from the standalone build?

plush narwhal
#

Only recently have I been getting into multithreading (with system.threading, I am aware the jobs system is a thing, it just doesn't fit my needs) and I have figured out how put something on a seperate thread, but that doesn't make the process any faster.

A particularly long part of my procedural generation system is a dictionary generator which consists of:
dataDictionary = await CalculateWorldChunkData(worldGenerationData.chunkDataPositionsToCreate);

calling this task:

    {
        ConcurrentDictionary<Vector3Int, ChunkData> dictionary = new();

        return Task.Run(() =>
        {
            foreach (Vector3Int pos in chunkDataPositionsToCreate)
            {
                if (taskTokenSource.Token.IsCancellationRequested)
                {
                    taskTokenSource.Token.ThrowIfCancellationRequested();
                }
                ChunkData data = new(chunkSize, chunkHeight, this, pos, WaterThreshold);
                ChunkData newData = terrainGenerator.GenerateChunkData(data, Seed);
                dictionary.TryAdd(pos, newData);
            }
            return dictionary;
        },
        taskTokenSource.Token
        );
    }```

How might I split this up into more than one thread?
flint sage
#

Try using Parallel.Foreach

plush narwhal
# flint sage Try using `Parallel.Foreach`

so would

            {
                if (taskTokenSource.Token.IsCancellationRequested)
                {
                    taskTokenSource.Token.ThrowIfCancellationRequested();
                }
                ChunkData data = new(chunkSize, chunkHeight, this, pos, WaterThreshold);
                ChunkData newData = terrainGenerator.GenerateChunkData(data, Seed);
                dictionary.TryAdd(pos, newData);
            });```

work instead of this?:
```foreach (Vector3Int pos in chunkDataPositionsToCreate)
            {
                if (taskTokenSource.Token.IsCancellationRequested)
                {
                    taskTokenSource.Token.ThrowIfCancellationRequested();
                }
                ChunkData data = new(chunkSize, chunkHeight, this, pos, WaterThreshold);
                ChunkData newData = terrainGenerator.GenerateChunkData(data, Seed);
                dictionary.TryAdd(pos, newData);
            }```
flint sage
#

Looks vaguely okay

#

But I'm not debugging your code over discord

plush narwhal
#

lmao, I'll try running it

plush narwhal
# flint sage Looks vaguely okay

WOAH WTF my generation happened near INSTANTLY! does parallel.foreach make use of all available therads or is it some weird amount?

#

is there a way to limit the amount of threads used as well?

flint sage
#

There's an overload with ParallelOptions

plush narwhal
#

ah thanks

flint sage
#

By default, methods on the Parallel class attempt to use all available processors

plush narwhal
#

im assuming thats including the threads used by unity cause it is causing some lagspikes, so im gonna limit the threads allowed

novel plinth
#

async/await isn't multithreading

plush narwhal
#

Im using system.threading and tasks

#

with async/await

novel plinth
#

oh mb 😅 didn't see the whole conversation

#

at this day and age, you'd just use threadPool to save you some headache from the good ole Thread in c#

flint sage
#

Their goal doesn't seem to be off load the work to a different thread but rather parallelize the work

novel plinth
#

oh ok

novel plinth
#

just becareful when using factory method

plush narwhal
#

Ill look into that for the other parts i need to multithread but so far, just parralising my foreach loops was enough. Thanks

candid lodge
#

hey! is there way find mouse position on mesh without collider?

dusty wigeon
#

There is not really a reason to not have a collider on something that you want to collide with or detect.

tiny pewter
#

project the mesh on a plane with normal equal to camera.transform.forward (you will get many simple 2d shapes) then run point in polygon algorithm,
i think you can rotate every point (by multiple a rotation matrix) and input.mouseposition on that plane so that every point is located on xz, xy of yz plane, easier to work with

#

ofc the easiest way is to rely on the unity bulti in bug free (maybe) physics engine

dusty wigeon
#

Or use the following on all triangle of the mesh:

private static bool LinePlaneIntersection(Vector3 linePositionA, Vector3 linePositionB, Vector3 planePositionA, Vector3 planePositionB, Vector3 planePositionC, out Vector3 result)
    {
        Vector3 P01 = planePositionB - planePositionA;
        Vector3 P02 = planePositionC - planePositionA;
        Vector3 P03 = planePositionC - planePositionB;
        Vector3 IAB = linePositionB - linePositionA;
        float sqrMagnitudeIAB = IAB.sqrMagnitude;

        Vector3 normal = Vector3.Cross(P01, P02);
        float denominator = Vector3.Dot(-IAB, normal);
        if (Mathf.Abs(denominator) < 0.001f) { result = new Vector3(); return false; }

        result = linePositionA + IAB * Vector3.Dot(Vector3.Cross(P01, P02), linePositionA - planePositionA) / denominator;

        if ((result - linePositionA).sqrMagnitude > sqrMagnitudeIAB || (result - linePositionB).sqrMagnitude > sqrMagnitudeIAB) return false;
        if (Vector3.Dot(normal, Vector3.Cross(P01, result - planePositionA)) < 0) return false;
        if (Vector3.Dot(normal, Vector3.Cross(P03, result - planePositionB)) < 0) return false;
        if (Vector3.Dot(normal, Vector3.Cross(-P02, result - planePositionC)) < 0) return false;

        return true;
    }
candid lodge
dusty wigeon
# candid lodge I am not making a game. I have model who is 1:1 to real life. And i want to mak...

That as nothing to do with if you are making a game or not. If you are not using GameObject for the rendering, you can still use GameObject for the collision.

The function can do the collision detection for you given a collider: https://docs.unity3d.com/ScriptReference/Collider.Raycast.html You can also use the Physics API directly.
Also, the function I gave earlier can be use to resolve the collision on the mesh manually.

candid lodge
candid lodge
real blaze
#

is anyone kind enough to check the size of their Burst package folder ( com.unity.burst )? it's been downloading for some 5 minutes now, I wonder if something's went wrong

#

in Windows, it'll be at C:\Users\[user]\AppData\Local\Unity\cache\packages\packages.unity.com\com.unity.burst@[version]\ where [user] is your username and [version] is the version of Burst you've installed

scenic forge
#

~800 MB for me.

#

(Btw you might want to move package cache out of your system drive if you worry about size or frequent read/write hurting your SSD)

dusty wigeon
#

1.6.5 -> 791MB.
1.8.4 -> 680MB.

brisk spruce
wispy prawn
#

With the AStar Pathfinding Library, is there any way to Scan the area async? What i m trying to do is something like this
async void Update() { await UpdateGraphMethod(); } private async Task UpdateGraphMethod() { await Task.Run(() => { AstarPath.active.Scan(AstarPath.active.data.gridGraph); }); Debug.Log("Complete"); }
(I know it is nonsense to call it in the Update Method but this is for demonstration purposes) However when using this i get the error: UnityException: get_isPlaying can only be called from the main thread. Is there a way around that?

sly grove
#

don't start it with Task.Run

#

I don't think it supports an asynchronous/background thread approach

wispy prawn
#

Thanks. I've seen that before, i was wondering if there is a way around that or a better way to update the grid.

#

Is the Unity Navmesh a better alternative?

sly grove
#

what do you mean "a way around that"?

#

Like a way around paying for pro?

#

your options are:

  • pay for the pro version of this asset
  • use an alternative navigation asset
  • write your own pathfinding
dry bear
#

should I do anything else besides opening FlatBuffers.net35.csproj with visual studio and building?

#

and copying this 2 files to unity

dusty glacier
#

Hi, does anyone know how I can detect collisions between two boxes in 2 dimensions? The information I have about the boxes is as follows: their position, size, and rotation on one axis.

#

I need to calculate the vector that one box needs to move to stop colliding

sly grove
dusty glacier
sly grove
#

Give your object a kinematic Rigidbody2D and a BoxCollider2D

#

then you can use Physics2D.BoxCast to detect obstacles

dusty glacier
#

but I also need to get a vector movement that will correct the collision

sly grove
#

What would be stopping you?

dusty glacier
#

hold on, let me explain what im trying to do

#

I am making a controler for procedural walking and i have to check if the feet are hitting each other

#

i can ignore the Y(up) axis due to cicumstances

sly grove
dusty glacier
#

i used Physics.Overlap before but it doesn't return a vector to fix the collision, am I missing something?

sly grove
#

though im not actually sure what you mean by that

#

what does "a vector to fix the collision" mean?

dusty glacier
#

for example when the physics engine detects overlap betwen colliders

sly grove
#

Actually you know what

edgy urchin
#

i agree

dusty glacier
#

it corrects their position

dusty glacier
sly grove
#

idk

#

you ruled out the physics engine too soon?

dusty glacier
#

thanks man

edgy urchin
#

please

edgy urchin
#

so like

#

what do i do

sly grove
edgy urchin
#

ty

echo pond
#

I am currently trying to implement the unity jobsystem in an pice of code that iterates through multiple behavior classes. That all imply funktions to calculate their own ContextMap. The Base funktion (Not jobifyd) looked like this: ```csharp
public void FindMoveDirContex(List<baseBehaviour> Behaviours, AIData aiData)
{
float[] evade = new float[8];
float[] interrest = new float[8];

    //need replacment to execute a series of Behaviours
    foreach (var Behaviour in Behaviours)
    {
        (evade, interrest) = Behaviour.CreateContextMap(evade, interrest);
    }
    ...rest of code

}

sage radish
echo pond
sly grove
#

you should probably go through some simple "getting started with the job system" style tutorials first to get an idea of how it works

tiny pewter
#

You cant even jobify or parallel your code in any way, the create context map is depend on previous result, that means they must wait before previous one finish

sly grove
#

but maybe

tiny pewter
#

But the method in uml return two array

static warren
#

Can anyone help me recreate the viewfinder mechanic in unity?

tiny pewter
#

Though array is a reference type, no need to be returned, the length of return array should be same as input i think

sleek marsh
#

is there anyway to make the top job NOT get scheduled on the main thread?

echo pond
brisk spruce
#

So I have 2 class sets, one is a bunch of POCOs implementing INotifyPropertyChanged that is already hooked into all of their Properties, most of which are public get/set, the other is a set of MonoBehaviors with Serialized fields.

Both "sets" of classes have the same structure in terms of names, just as an example here you can see some of this code, the field names match the property names between the two.

I want to figure out a "clean" way to auto hookup every single field of my MonoBehaviors to implicitly subscribe to the GameStates INotifyPropertyChanged event, such that if GameState changes, the field matches it too

Screenshot is example of my code in the monobehavior

#

Im thinking I can prolly do some fancy reflection stuff perhaps, with expression trees, I actually already have a handy method on GameState that lets me bind an Expression<Func<GameState, T>> to a matching Action<T> or Action that I can act on

#

thoughts on what isnt a brutal way to achieve this perhaps?

#

Alternatively:

does applying SerializeField attribute to stuff add any overhead if the class is not serialized in the editor, in publish mode?

#

I could potentially just simply re-use the GameState itself, and slap SerializeField somehow on it... maybe, I actually dont know if there is a way though to properly make my Event notifications bind to it right though, and I worry that because this is purely for debug purposes (and wont be included in publish mode), adding attributes and whatnot to my "published" classes will add overhead to the published game anyways, so its better to instead have a second "debug" monobehavior that does this work, and then wont be included in the actual release

#

this is currently what I have, it feels kinda gross and cumbersome, but it certainly works

https://hatebin.com/kkabrfkztj

But it means whenever any property changes on GameState, the entire set GameStateDebug fields reloads, and inversely when any of the GameStateDebug fields gets set, it pushes to the entire GameState, would be nice if I could specify which of the fields it was and do expression stuff to make this a bit more specific

slender stag
#

I am making a tank game and am making a turret with a flamethrower (that will be eventually networked), how do I check what the flames hit? (Flames don't reach destination instantly, and particle system is used for decoration, not logic, I guess I could make a deterministic invisible particle system but not sure of the implications of it)

half swan
slender stag
#

Flames ha e a delay before they reach a point which the enemy could dodge

#

Ima probrably use particles and turn it into a minmax thingy

#

Is it efficient to grab particle positions and draw a raycast toward it... or make an overlapping sphere at the point of the particle?

half swan
#

I dunno about efficient, depends on how many raycasts

half swan
#

It sends one message per particle collision

obsidian coyote
#

woo, finally truely 0 memory allocation, looks like it was some unity stuff that went away when i profiled a build, but also there were a few .toString()'s being called on some numbers that were allocating strings, so i replaced them with a pre-allocated lookup table. Not sure if there is a better way to handle dynamic UI text for things like statistics etc that are being updated in real-time that can be done to prevent string allocations 🤔

untold moth
#

A little bit of allocations are not that critical you know 😅

#

Unless you're planning to run your app on a 20+ y/o hardware. At which point there are probably other more important problems.

obsidian coyote
#

lol, i know, its more of a flex then anything at this point, one of my bosses is really anal about memory allocations and the main game i work on at work is well past the point of being able to resolve most of them (over 5 year old code base with many devs working on it), so its fun to rub it in a bit when my game has 0 lol

slender stag
slender stag
obsidian coyote
# slender stag That's a good flex... my code crashed Unity a few days ago because of recursion ...

ah yeah, stack overflows can be a pain, they can prove quite elusive when introduced in a large code base. I remember one time, we had one that was never an issue except when you had debugging open, and when you tried to breakpoint in the class, unity would instantly freeze then crash... we found out it was caused by an unused bit of improper code public int Something { get { return Something; } } this sorta setup, where the return value was supposed to be lower case so when visual studio tried to evaluate it for the debugger everything would crash lol

half swan
obsidian coyote
#

it was a 7800 line file as well, and that getter was somewhere around the middle of it 😐

slender stag
#

(for other people reading, latency was discovered, not invented)

tall ferry
slender stag
#

But, also don't want playing seeing themselves start burning before the flame actually hit them

tall ferry
scenic forge
next marsh
#

What's the ""industry standard"" approach to circle-circle overlap resolution? I'm curious how the problem of infinite resolutions is solved

#

I.e. a circle getting juggled between two other circles to either side

#

(In 2D)

dusty wigeon
novel plinth
scenic forge
#

Span it up.

dusty wigeon
scenic forge
#

But yeah super micro optimization territory, pretty sure this amount of allocation is irrelevant for incremental GC anyways.

novel plinth
#

StringPool tho.. the alloc only on the 1st time when filling the cache

#

after that zero alloc for days

scenic forge
#

I see.

next marsh
#

(Depenetration specifically)

#

Or circle packing may apply somewhat

dusty wigeon
next marsh
#

Interesting, I'll dig around there-- cheers!

brisk spruce
#

And AFAIK you can't serialize full properties.

I can't serialize the backing fields as then the mutation events won't fire, have to do it via the public properties

dusty wigeon
brisk spruce
#

The object in question is a POCO, so I'm not aware of any way to get around the fact I still would need some MonoBehavior interface between the POCO and the editor, no?

dusty wigeon
#

Use a custom editor

brisk spruce
#

Custom editor is interesting, can you hook it up to INotifyPropertyChanged event?

dusty wigeon
brisk spruce
#

How does the custom editor "hook" into the specific POCO instance I am working with?

dusty wigeon
#

However, you do not need to hook yourself

#

Just read the value as is.

brisk spruce
#

Does custom editor already subscribe to if the property's value changes?

dusty wigeon
dusty wigeon
brisk spruce
#

It's not a component or an asset

dusty wigeon
#

However, there is no bidirectional binding.

#

It is a C# script

brisk spruce
#

You can't "GetComponent" it, it's a POCO

dusty wigeon
#

You can GetComponent something that has a reference to your POCO

brisk spruce
#

Yeah I need bidirectional binding, that's what my code does atm

#

When I modify the inspector, it updates the GameState. And when the GameState changes, it updates the Inspector

dusty wigeon
#

There is no need binding in the case of an Editor

#

You can still update or be update

#

Without binding directly

brisk spruce
#

I'll check it out

dusty wigeon
#

By example, you can set the current value in public static string TextField(string text, params GUILayoutOption[] options); then retreive the new value afterwards.

GameState.Value = EditorGUILayout.TextField(GameState.Value);
#

If I am not wrong, this is the IMGUI (immediate mode graphic user interface) paradigm.

upbeat path
upbeat path
#

because in your example GameState.Value will be set and the code will process for each character typed into the text field. What you want is for that to be processed when the typing is complete which is what Delayed does

dusty wigeon
#

Oh I see.

#

I was not thinking about that particularly

#

But, yeah, gotta be careful about those case.

brisk spruce
upbeat path
dusty wigeon
#

The idea is to use reflection to construct the EditorWindow

brisk spruce
brisk spruce
upbeat path
dusty wigeon
#

I mean, for your own little project, maintenance should not be high in priority.

brisk spruce
#

this is a pretty big object and everytime I add a property, right now I need to:

  1. Add a matching field to the DebugGameState
  2. Bind the GameState -> DebugGameState write for that Property->Field
  3. Bind the DebugGameState write for that Field->Property

Which is a fair bit if I am planning to have a lot of props on these

#

and GameState has "child" classes as you can see, and I have to make matching debug "child" classes too when I make a new GameState child

#

so if I can just use reflection to sort of auto populate the editor, auto bind between the two, then when I add a new field to my game state it will "just work" and automatically show up, working, in the debug inspector tool

#

step 1 is I am gonna test if Zenject is smart enough to inject into an EditorWindow, if so I think Ill start with that, rather than an empty object in my scene

merry moat
cloud crag
#

is it ok to use System.Linq ?

#

does it have garbage and should I avoid using it or ?

novel plinth
#

those are free pretty much

dusty wigeon
normal tinsel
#

I'm trying to write my first tests in a project that uses VContainer. I can't seem to find any good examples on the internet so I asked ChatGPT about it and the responses are kinda not helping because they are just wrong.
Here is the code he suggested:

public class GameManagerTests
{
    private IContainer container;

    [SetUp]
    public void SetUp()
    {
        // Create a new container in each test to isolate dependencies
        container = new ContainerBuilder()
            .Register<PlayerController>(Lifetime.Singleton)
            .Register<GameManager>(Lifetime.Singleton)
            .Build();

        // Register the container as the application root
        container.Validate();
        LifetimeScope.Root = container;
    }

    [TearDown]
    public void TearDown()
    {
        // Clean up after each test
        container.Dispose();
    }

    [Test]
    public void TestGameManagerInitialization()
    {
        // Arrange
        var playerController = container.Resolve<PlayerController>();
        var gameManager = container.Resolve<GameManager>();

        // Act
        playerController.Initialize();
        gameManager.Initialize();

        // Assert
        Assert.IsTrue(playerController.IsInitialized);
        Assert.IsTrue(gameManager.IsInitialized);
    }
}

The problem already starts with IContainer which does not exist even in the VContainer namespace so naturally it does not have Validate() and Dispose() but also the Resolve<> methods.
Can someone guide on this?

sly grove
fresh salmon
#

(+ asking or answering questions generated by AI isn't allowed here)

misty glade
#

Anyone have a DOTween script or snippet for a nice little "pop out of a box and bounce a couple times" tween? Like - something like this that looks like it respects gravity (pardon the mspaint):

#

My google-fu is bad

#

I think easeOut in the X direction and easeOutBounce in the Y direction, but with a "kick" upward..

#

Additionally, I'd like it to "respect" a bounding box (if it hits the boundaries, it changes direction). Physics/rigidbodies seems like overkill for this ..

brisk spruce
#

Sin wave with a height modifier using something like % pi or whatever should work

misty glade
#

Probably, yeah. Just minimally so, though. I'm using this for "resources" that pop out of a 2d tile when destroyed. Player would have to click on the resource icon to collect it. I think I might have some tiles that have multiple resources that pop out, so they should probably have some randomness to the parameters

#

Sin looks pretty bad - I used it before and it was robotic looking.. It definitely needs to be quadratic.. unless my math is bad and sin with damping is parabolic..?

brisk spruce
#

so prolly want

float distance
int bounceCount
float heightMulti
float chaos
#

for params

misty glade
#

hm, probably don't need all that, just an initial X and Y velocity (damping and "gravity" can be fixed)

brisk spruce
#

so prolly just a vector then

misty glade
#

Maybe rigidbodies is gonna be easier than trying to .. recreate gravity and handle bounding boxes and damping and all that nonsense

brisk spruce
#

is this a sidescrolling game or 3d or...?

#

cause if its sidescroller or 3d, yeah Id just use actual rigidbodies with very simple hitboxes (prolly just a sphere) with rotating disabled so it purely translates but wont roll around

misty glade
#

2d isometric tile game

brisk spruce
#

oh yeah rigidbodies dont have much overhead in 2d land

misty glade
#

isometric "maybe" - for prototyping we're just using 2d overhead

brisk spruce
#

particles maybe might even be what you want if they are purely visual

#

Im like pretty sure you could do like, a particle emit that spits out the sprites and they collide with your terrain layer

#

yeah actually now Im pretty sure you want a particle emitter now that I think about it, if its aesthetic only

misty glade
#

it's not unfortunately - the player would have to tap on the icon after to collect it.. I think the best way to describe it would be like minecraft mining/farming:

  • Player taps several times on a breakable tile to "mine" it.
  • One or more "resources" pop out - they're no longer tiles, but "floating" icons that a player taps to collect.
  • Once tapped, then we can use a particle effect (probably a particle attractor and sprite icons) as the resource "flies into" the players inventory.
#

I'm looking for a tween/solution for that second part.. I'm gonna try rigidbody2d and see if it looks ok

#

I'll see if I can find a video of what I did before in DOTween - I thought it looked kinda junky

#

I can't find the exact clip but the "jump" of the little slime in the middle was a DOTween "jump" tween and it doesn't look realistic for gravity at all

regal lava
#

I keep seeing dotween passed around a lot. Reading the site it seems like it lerps values for you? I'm not exactly understanding its usage.

sly grove
#

yeah pretty much

#

it's a fire-and-forget thing.

regal lava
#

hmm

sly grove
#

You can say like "Move this object to this position over 10 seconds"

#

and it does it

#

with lots of options of course

#

it basically does what beginners think the "Lerp" function actually does

misty glade
#

Yeah, it's just a tweening library. A couple years ago I wrote my own and after seeing dotween, I realized they just did it better. There's some hassles with it but overall it's pretty good.

#

My API surface for my own tweening library was so bad

sly grove
#

yeah it's nicely done

#

and performant

#

It's kinda one of those things that probably should be in every project. Like Cinemachine

misty glade
#

that was my tweening method

#

You'd make your own coroutine, enumerate over some timespan and update whatever float you cared about.. it was a mess. DOTween you just do something like:

float duration = 2f;
Vector2 end = new();
Ease easeType = Ease.OutQuad;
gameObject.transform.DOMove(2f, end, easeType);
regal lava
#

Looks decent for 3D text animation since I've been just coding that all in normally, and some using the timeline

misty glade
#

i think that's a paid feature, can't recall

regal lava
#

WELL

misty glade
#

Oh, no, it's not - DOText

#

I rolled my own but probably could have used theirs as well

regal lava
#

That's legacy, and it looks like tmp does require the pro version

#

but it does basically what my animation scripts do anyway it seems. Changes the vertices of each character one by one

#

I'll probably snag it though anyway for funnsies

misty glade
#
        public AnimationCurve AnimationCurveGravity;
        private const float PopDuration = 0.8f;
        private const float PopMinY = 200f;
        private const float PopMaxY = 800f;
        private const float PopMinX = -500f;
        private const float PopMaxX = 500f;

        private void OnEnable()
        {
            float y = NumberUtils.NextFloat(PopMinY, PopMaxY) + transform.localPosition.y;
            float x = NumberUtils.NextFloat(PopMinX, PopMaxX) + transform.localPosition.x;
            transform.DOLocalMoveY(y, PopDuration).SetEase(AnimationCurveGravity).Play();
            transform.DOLocalMoveX(x, PopDuration).SetEase(Ease.Linear).Play();
        }

Suggestions to improve it?

The curve is just a parabolic 0 -> 0.5 -> 1

random spruce
#

Anyone got any idea of how I could edit a scriptable object in build version? (Have a gui like the one in inspector to edit). Else do I have to create a custom GUI to edit it?

regal lava
#

You can edit a SO freely as long as you have a reference, but remember that editing will affect all objects referencing that instance.

upbeat path
regal lava
random spruce
random spruce
next marsh
#

Out of curiosity, what's the reason behind being unable to call Physics2D.OverlapCircleNonAlloc from outside the main thread?

#

I have many things in my scene which I want independently to call it, but any form of parallel computation is out the window because of it

flint sage
#

Part legacy, part consistency, part being a fuck ton of work when you have random people calling random things

next marsh
#

Are there any non-borderline-deprecated alternatives?

#

To clarify just in case, I'm trying to get all objects within a given radius of each object

flint sage
#

It's not borderline deprecated?

#

If you need to do so many physics calls to figure out whether things are nearby then likely that isn't the right solution

untold moth
flint sage
#

Most scripting layers at least

untold moth
magic badge
#

Is here anyone who have used unity cloud save?? I have used it and everything is working fine. But I want to access other players data using their id any idea hoe to do it??

fallow eagle
magic badge
#

If any one have experience with Unity Leaderborad UGS

I want to add these statements in try catch

var scoreResponse = await LeaderboardsService.Instance
.GetPlayerScoreAsync(leaderboardId);
Debug.Log(JsonConvert.SerializeObject(scoreResponse));

Which exception will work perfect to catch http 404 error

fair locust
#

I can’t believe I have to jump through hoops just to see logs…

#

And I don’t know what hoops to jump through

tiny pewter
#

the most stupid way is trying to reproduce the exception and catch it then debug.log to see it (it may be different from c# exception.....)

fair locust
#

There's no exception -- its just a blank project with one Hello component on an empty game object. I can't see the logs.

#

The real game is more complex with waaay more logging that I can't see.

magic badge
fair locust
#

Does anyone know how to see Debug.Log statements on a dedicated server build?

#

I have no idea what else to do

#

It doesn’t seem like it should be hard but… Maybe unity isn’t really meant for dedicated server builds if it’s complicated to get logs

#

What else can I do?

My real project has a bunch of log statements so I can know what’s happening.

My blank project except with the one component to see if I can see logs doesn’t work. What else do I need to do to see logs?

dusty wigeon
#

I know that you can access logs and see logs through the console, I've done it. For a windows and linux standalone server. However, I do not have access to the project at this time.

#

Maybe start by being sure that the logs are being correctly printed to the log files.

fair locust
#

When I redirect the logs to a file I only see the three lines I posted above.

You sure you were running a dedicated server build? That’s a new and different setting than building a standalone build and running it as a server

onyx blade
#

how would I check if the shape on the right fits into the shape on the left (the size of the tiles is not relevant).
I have a list of the white tiles, now I need to check if they fit in the larger grid. How would I go around approaching this?

#

I'm not sure what kind of logic I can use to make sure there is space to fit that shape.

sly grove
#

that's all

dusty wigeon
onyx blade
#

I was trying to figure out dynamically assigning that root, but that may be too hard/impossible?

sly grove
# onyx blade how would I check if the shape on the right fits into the shape on the left (the...

like:

class Shape {
  List<Vector2Int> positionsInShape; // the L shaped piece would be like: [(0, 0), (1, 0), (0, 1)] for example
}

bool DoesShapeFit(Shape shape, Vector2Int position) {
  bool fits = true;
  foreach (Vector2Int part in shape.positionsInShape) {
    var toCheck = position + part;
    if (board.SpotIsEmpty(toCheck)) {
      return false; // if any spot is not empty, the shape does not fit
    }
  }

  return true; // all spots were empty
}```
onyx blade
#

lucky for me the shapes are designed to be squares on a grid, so all my shapes are inside a single List<Vector2Int>

plucky laurel
#

you can use RectInt

onyx blade
onyx blade
#

not sure if I can define that root on the GUI that I have

plucky laurel
#

not sure, wont using a 2d array make it all less complicated?

sly grove
#

you can alsways consider the root as the bottom left or top left or whwatever of that 3x3

#

even if there's not an "occupied" tile there

plucky laurel
onyx blade
plucky laurel
#

wont these make it all less complicated?

onyx blade
#

the puzzle grid is a 4x4

plucky laurel
#

yes and

#

a 2d array makes all kinds of problems easier to reason about and solve

onyx blade
#

they arent necessarrily in the same position tho 🤔
wouldnt overlap checking on 2D arrays fail if I try to place an object on different coordinates

plucky laurel
#

you can always start the for x for y loop at any index

onyx blade
#

like, this would not be valid if my logic isnt stupid

plucky laurel
#

effectively offseting the starting position

onyx blade
#

oh like that

#

hmm

#

yeah actually

#

im not sure which method is better

plucky laurel
#

the method that will make reasoning about problems easier

sly grove
#

The cute/clever way to do this is use bitfields

#

but - I shouldn't even have said that 🤣

onyx blade
#

lol

sly grove
#

inspired by sebastian lague's chess video

plucky laurel
#

bitmap is a 2d array or im misunderstanding

sly grove
#

that whole board is just 16 bits

#

you can represent all of that information in a ushort

fair locust
sly grove
#

and if you want to check if two boards overlap you can do boardA & boardB and if it's 0 there's no overlap

#

so you can just take your piece, position it properly in the board, make a 4x4 ushort bitfield out of it

#

then just do pieceBitField & board and if the result is 0 there are no overloaps @plucky laurel @onyx blade

plucky laurel
#

that wont allow for easy offset

#

will have to write apis that create an offset

sly grove
#

eh

#

not difficult

#

anyway I'll move on from this as I provided a solution above that would work and the bitfield discussion will probably just add confusion for now

plucky laurel
#

benefit of bitfield is performance, the apis will be harder to reason about and harder to spot bugs, i understand its an elegant way to solve some problems but i would not use it for something so volatile

dusty wigeon
sly grove
#

Yes it would definitely be the most performant approach I believe

onyx blade
#

thx for the input @plucky laurel @sly grove I will use on of the 2 earlier implementations as the bitfield stuff isnt something im that familiar with and is causing me a bit of confusion as you said.

nevertheless, might do some research on bitwise stuff for the future as that seems like an elegant, albeit harder solution

fair locust
#

I'd like to see you try

dusty wigeon
dusty wigeon
#

I was just sharing the little knowledge I have on the situation you are experiencing.

fair locust
#

Cool cool

dusty wigeon
#

It is kinda long to do.

#

You would have better result trying to reach someone on the forum

fair locust
#

How long does it take you to make an empty project?

dusty wigeon
#

To build and setup everything. 15min ?

fair locust
#

Sounds like that's kinda long to do. Yea

dusty wigeon
#

Given that Unity is installed

fair locust
#

And given you have a computer

dusty wigeon
#

And that, without trying multiple configuration

#

Because It might not work out of the box.

#

As you seem to experience

fair locust
#

Does anyone know how to see logs on a dedicated linux server build of a unity project?

I have an empty project with one monobehaviour -- Hello. All it does it Debug.Log on Start and Update. I build a dedicated linux server build of the game.

When I run it in a linux container I never see logs (/app/game-server.x86_64). I've tried a few things (/app/game-server.x86_64 -logFile /dev/stdout, /app/game-server.x86_64 -logFile /app/server.log, flip the logging from "script only" to "full") but I never see logs in stdout or a log file.

All I see is this posted to standard out (or the log file) and then no more...

Mono path[0] = '/app/game-server_Data/Managed'
Mono config path = '/app/game-server_Data/MonoBleedingEdge/etc'
Preloaded 'lib_burst_generated.so'

It's an empty unity project from URP if that help. I'm confused why I can't see any of the logs in the Start and Update callbacks. I see them when I run the project from the unity editor.

sly grove
#

Debug.Log gets stripped out for production builds

fair locust
#

Source? Presuming that's true how do folks usually output logs?
Edit:

Unity produces log files for the Editor, package manager, licensing, development players, and Hub. You can use these log files to understand where any problems happened in your application.

Unity adds all messages, warnings, and errors from the Console window
to the log files. To add your own messages to the Console window, and the logs, use the Debug class.
https://docs.unity3d.com/Manual/LogFiles.html

Rereading that paragraph does imply it. Well shit because the dev builds don't work due to some esoteric error I'll have to resolve. It's probably related to running on an M2 mac.

sly grove
#

development players
yeah

worldly shale
#

I have a problem when I send data to my server using unity networking I get error received no data in response I tried to look for solutions but none seems to work this is the code:

using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;

public class RegisterSystem : MonoBehaviour
{
    public InputField emailInput;
    public InputField passwordInput;
    public InputField usernameInput;
    public GameObject panel;
    public GameObject verificationPanel;
    public Text statusText;

    public void RegisterUser()
    {
        StartCoroutine(SendRegistrationRequest());
    }


    private IEnumerator SendRegistrationRequest()
    {
        // Get the user input from the InputFields
        string email = emailInput.text;
        string password = passwordInput.text;
        string username = usernameInput.text;

        // Construct the URL with the parameters
        string url = "http://immortalgames.infinityfreeapp.com/RegisterUser.php" +
                     "?registerEmail=" + UnityWebRequest.EscapeURL(email) +
                     "&registerPass=" + UnityWebRequest.EscapeURL(password) +
                     "&registerUser=" + UnityWebRequest.EscapeURL(username);

        UnityWebRequest www = UnityWebRequest.Get(url);
        yield return www.SendWebRequest();

        if (www.result != UnityWebRequest.Result.Success)
        {
            Debug.Log("Error sending request: " + www.error);
            statusText.text = "Error: " + www.error;
            statusText.color = Color.red;
        }
        else
        {
            Debug.Log("Form upload complete!");
            Debug.Log("Server Response: " + www.downloadHandler.text);
        }
    }
}
fair locust
worldly shale
# fair locust You have to add a new DownloadHandler to the unity web request (aka `www.downloa...

still getting received no data:

Curl error 52: Empty reply from server

0x00007ff6aecaa1cd (Unity) StackWalker::GetCurrentCallstack
0x00007ff6aecaf179 (Unity) StackWalker::ShowCallstack
0x00007ff6afc78061 (Unity) GetStacktrace
0x00007ff6b03337b2 (Unity) DebugStringToFile
0x00007ff6af14e8ca (Unity) TransformCurlErrorToWebError
0x00007ff6af14bf18 (Unity) CurlExecutor::CurlExecute
0x00007ff6ae8098f4 (Unity) ujob_execute_job
0x00007ff6ae809007 (Unity) lane_guts
0x00007ff6ae80aeb4 (Unity) worker_thread_routine
0x00007ff6aea22ff7 (Unity) Thread::RunThreadWrapper
0x00007ff9eb7d7614 (KERNEL32) BaseThreadInitThunk
0x00007ff9ebc026b1 (ntdll) RtlUserThreadStart

#

idk whats happening it just works fine if I pasted the link in my browser

flint sage
#

Sounds like an issue with your server, it's executing fine but the server is not responding

worldly shale
#

But if I pasted the link that unity generates for the Get function it does respond with the expected response

#

That's why I'm confused

flint sage
#

Your browser and Unity are not teh same

#

Your server is doing something

#

Check the logs

dusty wigeon
#

That being said, the actual printing and logging may be disable. I do not really know, I'm using a wrapper around Debug.Log.

#

And also, you might be able to enable it with Logger.logEnabled

fair locust
#

So wait… are logs stripped or is it not?

dusty wigeon
# fair locust So wait… are logs stripped or is it not?

The function call is definitly not stripped. The Debug.Log(...) will still be evaluated meaning that everything you have written inside will be executed. However, they might be disabled (Not printing) depending on what is your configuration. By default, in a WindowsPlayer, they are printing if I referrer to older test I have done.

#

Usually, you have a file call Player.log inside appdata path.

fair locust
#

There’s no such file there…

#

I’m still dealing with QEMU related stuff to get the dev build working.

Glad this stuff is simple

#

I’d hate to just see logs and be done with this silliness. Sign me up for a couple days of deep debugging and thinking to solve something as lame as “I want to see logs when I run my backend server”

dusty wigeon
#

In an empty project.

fair locust
#

I’m steamed about it. Seems simple, it isn’t. I just need to slow down and solve it or move on.

west nexus
#

Hello guys, basically my unity physics gets messed up when I my computer charges

#
float vertical = Input.GetAxis("Vertical");
        float horizontal = Input.GetAxis("Horizontal");

        body.velocity = new Vector3(0f, body.velocity.y, 0f) +speed * (-Camera.forward * horizontal + Camera.right * vertical);

        ```
#

This code snippet makes the player fly

#

when chargin

#

and moves normally when not

#

I'm shocked

sly grove
#

It's not this

west nexus
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    [SerializeField] private float speed;
    [SerializeField] private Rigidbody body;
    [SerializeField] private float jumpDistance;
    [SerializeField] private float jumpDuration;

    public Transform Camera;


    private float jumpForce;


    private bool isGrounded;


    private void Start()
    {
        
        isGrounded = true;

        jumpForce = (Physics.gravity.y * jumpDuration);
        jumpForce *= jumpForce * body.mass;
        jumpForce /= 2 * jumpDistance;
    }

    private void FixedUpdate()
    {
        float vertical = Input.GetAxis("Vertical");
        float horizontal = Input.GetAxis("Horizontal");

        body.velocity = Vector3.Dot(body.velocity, Camera.up)*Camera.up+ speed*(-Camera.forward * horizontal + Camera.right * vertical);

        
        
        
        if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
            jump();

    }


    private void jump()
    {
        body.AddForce(new Vector3(body.velocity.x, jumpForce, body.velocity.z));
        isGrounded = false;
    }


    private void OnCollisionEnter(Collision collision)
    {
        isGrounded = true;
    }
}
cunning raven
#

Hey ya'll I wanted to know if anyone here could help me figure this out. I'm trying to code a procedural terrain but I'm having trouble figuring out how to handle collisions so that different objects don't overlap when spawning. How do large world games generally do this?

sly grove
# cunning raven Hey ya'll I wanted to know if anyone here could help me figure this out. I'm try...

Generally procedurally generated objects like trees etc use noise functions to determine where to place things, which naturally will tend away from overlapping objects.

There are also proceses like rarefication: https://gitlab.com/denispahunov/mapmagic/-/wikis/ObjectsGenerators/Rarefy

#

by the way that's a link to the docs for MapMagic which is a great tool for this kind of thing.

cunning raven
#

Sweet! Thank you <3. Noise function could also be an interesting way of doing this. I've tried grid based with my terrain but that also doesn't/won't work due to the size of objects being spawned being irregular, of course. but the use of noise should work, hmm

#

I'm having the same exact problem discribed on the doc you`ve linked lmao

cunning raven
sly grove
#

It can generate terrain from a seed, not the other way around

red atlas
#

Not sure where this would go, but a Google search only turned up 3 results and I figured this is a bit of an advanced topic. So I'm working a VR application and I was measuring the performance metrics to try and optimize everything. Unity's Profiler keeps throwing up the following:

#

What's with the StackTraceUtility.ExtractStringFromExceptionInternal()[Invoke]? From the looks of it, it has something to do with the errors and warnings that are logged on the console, which I disabled by right clicking on the console > Stack Trace Logging > Errors/Warnings > None.

#

It is particularly allocating a ton of garbage.

#

It has something to do with Physics.TriggerStays, but I'm trying to understanding what the StackTraceUtility thing exactly is, if it isn't what I mentioned above?

dusty wigeon
red atlas
dusty wigeon
red atlas
#

Yes preferably, or in general in regards to thinking about what next.

flint geyser
#

How do you usually implement projectiles? I want there to be projectiles which can damage only player, only (all) enemies, and only some kinds of enemies and the last requirement quite forbids using enums.
So far only silly decisions come to mind.

half swan
#

You could use enums that the projectile passes to the enemies, and the enemy will "accept" or "deny" damage from some types, inverting the responsibility

tall ferry
flint geyser
tall ferry
#

oh wait maybe i misunderstood

#

I assumed you are trying to have projectiles pass through objects it cant damage. Is this true or are you just trying to have it not damage certain objects on hit?

flint geyser
#

So far it looks to me like there's going to be some kind of inversion of responsibility anyway.

rare tulip
#

how can i use unity's profiler (what should i be looking at) to determine which areas of my game requires optimizations if at all?

flint geyser
# rare tulip how can i use unity's profiler (what should i be looking at) to determine which ...

(not really an advanced topic) you launch it while the game is playing (the shortcut is Ctrl + 7), look at how much time each frame takes. Usually, you want it not to go higher than 16.6ms because 60fps is the standard. If you want to see how much time each separate function takes, click on the timeline and you will see everything needed in the bottom, although I prefer to change the view mode to Hierarchy.

rare tulip
#

thanks

tawdry temple
#

hey guys, so im newbie in photon and i have a problem that when i play w/ two players the players swap the controls idk what is the problem can anyone fix that?

using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;

public class FirstPersonMovement : MonoBehaviour
{
    public float speed = 5;

    [Header("Running")]
    public bool canRun = true;
    public bool IsRunning { get; private set; }
    public float runSpeed = 9;
    public KeyCode runningKey = KeyCode.LeftShift;

    Rigidbody rigidbody;

    PhotonView view;
    /// <summary> Functions to override movement speed. Will use the last added override. </summary>
    public List<System.Func<float>> speedOverrides = new List<System.Func<float>>();


  
    void Awake()
    {
        // Get the rigidbody on this.
        rigidbody = GetComponent<Rigidbody>();
        view = GetComponent<PhotonView>();
    }

    void Update()
    {
        if(view.IsMine)
        {
            
            // Update IsRunning from input.
         IsRunning = canRun && Input.GetKey(runningKey);

         // Get targetMovingSpeed.
         float targetMovingSpeed = IsRunning ? runSpeed : speed;
            if (speedOverrides.Count > 0)
            {
             targetMovingSpeed = speedOverrides[speedOverrides.Count - 1]();
             }

         // Get targetVelocity from input.
            Vector2 targetVelocity =new Vector2( Input.GetAxis("Horizontal") * targetMovingSpeed, Input.GetAxis("Vertical") * targetMovingSpeed);

         // Apply movement.
         rigidbody.velocity = transform.rotation * new Vector3(targetVelocity.x, rigidbody.velocity.y, targetVelocity.y);
        }
    }
}
regal olive
#

does anyone know a way to rebake the navmesh system while the game is running? is that impossible?

glossy finch
#

I am using a 4K monitor and I have a DPI scaling in Windows set to 150%, unfortunately now with the tool I'm using I noticed that Event.mousePosition is scaled back by 100/150. is there a way that I can get this mousePosition scaled to DPI in a managed way or is there a way for me to get the DPI for my current screen (value can differ per screen)?

novel plinth
glossy finch
austere jewel
glossy finch
regal olive
#

the navmesh surface?

sleek terrace
#

How can I properly create a uv for 3d mesh so that it maps to 2d texture?

sleek terrace
regal olive
sleek terrace
regal olive
#

have u tried stitching it together to enlarge it then applying your texture

sleek terrace
#

wdym?

regal olive
#

like one workaround i did was when i wanted a rocky texture, lets say its 30x30 pixels

#

i turned it into 9 panels so it became 90x90 pixels

#

looked much better, if thats what ure going for

sleek terrace
#

ahh

#

essentially make the slopes their own mesh and apply the texture directly

regal olive
#

i havent slept btw so take everything i say with a grain of salt

dusty wigeon
regal olive
#

or u can do that workaround i said so it doesnt become elongated since it has more to slopes to work with if u know what i mean

sleek terrace
#

I got my current code off chatgpt, I have no idea how to make uv, please go ez on me

dusty wigeon
sleek terrace
#

lmao

#

uv are coordinates on a picture

#

they are used to figure out which pixels to color

dusty wigeon
#

So, you know exactly what I have just said

sleek terrace
#

yes

sleek terrace
dusty wigeon
#

Yeah

#

UV are 3D concept as well

sleek terrace
#

if it was 2d, I could simply divide by the max sizes

dusty wigeon
#

In 3D, you can do the same also

#

Do it at the surface level

#

Subdivide your surface

#

There is also tiling, however I'm not really familiar with that

regal olive
#

go to fiverr and pay 5 cents to a ugandan refugee to do it for u

dusty wigeon
#

Maybe you just have to set your UV higher than 1

sleek terrace
regal olive
#

3 ideas u can do right here man, fiverr, learn about uv, or increase ur pixels for applying the texture

sly grove
sleek terrace
#

I cant figure it out

flint geyser
#

When a class needs some functionality as dependency, you can just create an interface and say whoever implements it depends on you (in the sense that it will have no reason to exist other than for our class). But what if 2 classes need to know about each other? Say I want player to know where all the enemies are so that he can aim at them and also I want enemies to know where is player so that they can aim at him. How would you do it?

sly grove
#

I prefer to use a separate component for this kind of thing, rather than implementing interfaces, but the concept is the same

flint geyser
#

I thought of creating an interface which provided all the relevant targets. For player it would point to enemies and for enemies point to player, what do you think about such an approach?

sly grove
#

I don't understand what you mean

flint geyser
#

ITargetsProvider, EnemiesTargeter, PlayerTargeter

#

Something like that

sly grove
#

Well

#

why does that need to be an interface

flint geyser
#

The other option is an abstract class and it's more restrictive than an interface

sly grove
#

you don't need either

#
public class TargetProvider : MonoBehaviour {
  public List<ITarget> GetTargets(int team) {
    // return all targets of the specific team
  }
}```
or
```cs
public class TargetProvider : MonoBehaviour {
  public int team; // assign in inspector
  public List<ITarget> GetTargets() {
    // return all targets of the specific team
  }
}```
#

int is also just an example here

#

you can use an enum like:

enum Allegiance {
  Player,
  Enemy
}```
flint geyser
#

I think this approach is more limiting because there might be division not based on team allegiance

sly grove
#

this is just an example

#

without knowing the concrete requirements it's harder to be specific

dusty wigeon
flint geyser
dusty wigeon
#

Player -> Target <- Enemy
Enemy -> Target <- Player

#

See, they do not depend from each other

#

But depend on a common object.

#

Interface do thet same trick also.

#

This is the dependency inversion principle in fact.

#

However, in your case, it might be better to use composition.

#

To increase the modularity

flint geyser
#

Use composition in what sense?

dusty wigeon
#

In Unity, composition is simple as dividing into multiple MonoBehavior

flint geyser
#

Nowadays I use Zenject so there really is no need to keep everything MonoBehaviours so I try to use plain C# classes, is it bad?

dusty wigeon
#

I guess it would push you to do bad design choice by not defining the serialized data with the real owner of it.

#

You should not try to prevent the usage of MonoBehavior

#

It is not like you gonna change engine mid way.

flint geyser
dusty wigeon
#

Yeah, not

sleek terrace
#

How can I go about creating UV coords for a shape like this?

sly grove
#

depends which part of the texture you want to map to which part of the model

#

that's what UVs are - a mapping of positions on the model to texture coordinates

sleek terrace
#

I just want to map a whole texture onto it

sly grove
#

that isn't really an answer

#

there are infinite ways to do that

sleek terrace
#

I just need one

#

🙂

sly grove
#

and you have to explain what that way is

sleek terrace
#

Right now, What I got is meh

#

the vertical slopes are deformed

#
private Vector2 GetHexUV(Vector3 vertexPosition)
        {
            // Assuming hexagons are uniformly spaced in a Grid along the Z-axis
            // Calculate the relative position of the vertex within the hexagon
            float relativeX = vertexPosition.x / hexSettings.innerRadius;
            float relativeY = vertexPosition.y / (hexSettings.outerRadius - hexSettings.innerRadius);
            float relativeZ = vertexPosition.z / (0.5f * hexSettings.outerRadius);

            // Calculate UV coordinates based on the relative position
            // Using a custom range for UV coordinates based on the hexagon dimensions
            float uvX = 0.5f + (0.25f * relativeX);
            float uvY = 0.5f + (0.25f * relativeY);
            float uvZ = 0.5f + (0.25f * relativeZ);

            if(vertexPosition.y == Position.y)
            {
                return new Vector2(uvX, uvZ);
            }

            // Return the UV coordinate
            return new Vector2(uvX, uvZ);
        }
sly grove
#

This is for blender

#

but the concepts are the same

sleek terrace
#

these hex are done dynamically

sly grove
#

doesn't matter

#

the way UVs work is the same

#

the point of the video is to explain how UV coordinates map the texture onto the object

#

from there you can write the code to do it as you please

sleek terrace
#

so, there isnt really a general one piece of code fit all for this?
This has to be done on a case by case basis?

sly grove
#

there is one other option

#

alternative to UV-mapped textures

#

you can look into using a Triplanar shader

#

that's probably pretty appropriate for this case

sleek terrace
#

ok

sly grove
sleek terrace
#

more of a shader graph tutorial

sly grove
#

it shows how to make a triplanar shader

#

which would suit your usecase

sleek terrace
brisk spruce
#

I try and keep my monobehaviors as simple and minimal as possible, and they all should exist in a "glass box" totally unaware of anything else around them, their only job is to expose their events (collisions and clicks and etc), and expose their mutations (transform, animator state, etc)

My service keeps track of who/where/what everyone is and manages all these objects, doing all CRUD operations on em and keeping em sorted into groups if necessary

honest hull
#

Hey so is there anywhere that can show me how to send a compute shader I have in unity to say a plugin so I can send textures to the shader from the plugin?

honest hull
#

DX12 sorry

#

been searchihng for a way to do bindless textures for over a year at this point

sage radish
# honest hull DX12 sorry

You can use GL/CommandBuffer.IssuePluginEvent to hook your native plugin into the render thread just before the dispatch, but I think DX12 is tricky because I don't think you can easily get Unity's ID3D12CommandList to add your own commands into it.

#

You can get access to Unity's ID3D12CommandQueue and submit your own command lists

honest hull
#

heck

sage radish
#

I'm not very familiar with how DX12 deals with state, but it looks like texture binding is confined to the command lists.

molten fulcrum
#

Trying to make a custom camera for self learning purposes and was wondering if anyone knows how I could make this run faster? (as of right now it runs at about 15 fps while with a regular camera it runs at about 50 fps)

#
void RenderPixel(Texture2D texture, int x, int y)
{
    float screenX = x / (float)texture.width * sourceCamera.pixelWidth;
    float screenY = y / (float)texture.height * sourceCamera.pixelHeight;

    Ray ray = sourceCamera.ScreenPointToRay(new Vector3(screenX, screenY));
    bool success = Physics.Raycast(ray, out RaycastHit hitInfo);
    if (!success)
    {
        texture.SetPixel(x, y, sourceCamera.backgroundColor);
    }
    else
    {
        float lerp = (Vector3.Dot(sourceCamera.transform.forward, hitInfo.normal) + 1) * .5f;
        texture.SetPixel(x, y, Color.Lerp(color, depthColor, lerp));
    }
}
public void Render()
{
    for (int x = 0; x < renderTexture.width; x++)
        for (int y = 0; y < renderTexture.height; y++)
            RenderPixel(renderTexture, x, y);

    renderTexture.Apply();
}```
#

it renders about every second, it's meant to render on a tablet type object in-game so it's intentionally rendering slowly, however it slows down the game itself too

#

and the texture is 198x102

long ivy
#

well not setting the pixels one at a time and running those raycasts in parallel would help, but realistically you'll probably want to find a way to do this on the gpu instead. What are you trying to do? I feel like you should find a way to fake the raycasts (sample depth buffer, or use replacement shader?) and do all this in a pixel shader instead

molten fulcrum
molten fulcrum
#

another issue I just noticed that will help performance is that the custom camera still renders even when it's not being shown, so I'll make it where it'll only render if the player will notice

sly grove
#

Also things like float screenX = x / (float)texture.width * sourceCamera.pixelWidth; don't need to be done once per pixel

#

you can compute that once and reuse it 4 million times

molten fulcrum
#

oh yeah fair point

flint geyser
#

Hi! I have such a class which is supposed to be always on, so I don't really have a reason to make it inherit from MonoBehaviour, however that event subscription in constructor is kinda ugly, don't you think? How would you get rid of it in my place? Or perhaps you wouldn't?

public class PlayerTargetsProvider : ITargetsProvider {
        private MonoGameController _gameController;

        public PlayerTargetsProvider(MonoGameController gameController) {
            _gameController = gameController;

            _gameController.OnNewLevel += SetNewEnemiesManager;
        }

        private EnemiesManager _enemiesManager;

        public List<Transform> GetEnemies() {
            var list = new List<Transform>();
            foreach (var monoEnemyController in _enemiesManager.GetEnemies())
            {
                list.Add(monoEnemyController.transform);
            }
            return list;
        }

        private void SetNewEnemiesManager(Level level) {
            _enemiesManager = level.EnemiesManager;
        }
    }```
brisk spruce
flint geyser
#

Could you tell me what it is? 🙂

brisk spruce
#

Zenject is a popular DI engine, I have been using it and a few others.

You are technically doing DI already here:

        public PlayerTargetsProvider(MonoGameController gameController) {
            _gameController = gameController;

Specifically thats Constructor DI

flint geyser
#

Yeah, that much I know. I guess spending a week on reading a DI book wasn't in vain

flint geyser
brisk spruce
#

So the big thing is here:

foreach (var monoEnemyController in _enemiesManager.GetEnemies())

It looks to me like rather than changing your ref to _enemiesManager, couldnt your EnemiesManager object just return the correct enemies for a given level, and when level changes the return value for it just changes to reflect that?

#

Seems to me you wanna just move this logic here:

_gameController.OnNewLevel += SetNewEnemiesManager;

To be inside of EnemiesManager instead, and the output of .GetEnemies() will just be the "right" enemies for a given level

#

And then you can just DI your EnemiesManager as well, because now you only need 1 single EnemiesManager for your whole game

flint geyser
#

So the step you mentioned is to get your dependency and abstract from how it works, right?

brisk spruce
#

Should, hopefully, just look like this:

public class PlayerTargetsProvider : ITargetsProvider {

        private MonoGameController _gameController;
        private EnemiesManager _enemiesManager;

        public PlayerTargetsProvider(MonoGameController gameController, EnemiesManager enemiesManager) {
            _gameController = gameController;
            _enemiesManager = enemiesManager;
        }

        public List<Transform> GetEnemies() {
            var list = new List<Transform>();
            foreach (var monoEnemyController in _enemiesManager.GetEnemies())
            {
                list.Add(monoEnemyController.transform);
            }
            return list;
        }
    }
flint geyser
#

You forgot to remove the controller I think

brisk spruce
#

oh yeah looks like that isnt even needed anymore, good catch

#

and then it just sorta looks now like PlayerTargetsProvider isnt doing anything that EnemiesManager isnt already doing for you 🙂

flint geyser
#

However it just moves the problem to another place, because if I don't make the enemiesManager a MonoBehaviour I still don't know how to properly subscribe it to the game manager

brisk spruce
#

Zenject is fine with registering references to MonoBehaviors for injecting

flint geyser
#

Wdym? [Inject]

brisk spruce
#

where in your code do you call new PlayerTargetsProvider(...)

#

what you pass into its constructor is the act of injecting

#

or if you are using Zenject or another DI library, its handling the injection for you automatically

flint geyser
#

I mean that EnemiesManager itself still won't be an MB so it won't have OnEnable and OnDisable or Awake to subscribe to the gameManager

#

So I am stuck with ugly subscribtion in constructor again

brisk spruce
#

So you have an Update() to hook into

flint geyser
#

The installer, right?

brisk spruce
#

but then everything below that entry point can be a POCO

brisk spruce
flint geyser
#

I don't understand

brisk spruce
#

I called mine my "GameEngine" and its job is to just be a simply MonoBehavior that hands off work to my services inside of Update()

#

The Installer's job is to register all your dependencies

#

But to keep stuff seperate I think have a very very simply monobehavior that just injects my top level services and calls em in its Update and thats it

flint geyser
#

So how would you subscribe EnemiesManager to GameController in my case with that GameEngine of yours?

brisk spruce
flint geyser
#

By the way if your engine handles only updates, then you can remove it. Because Zenject adds a special interface for it - ITickable I believe it is called

brisk spruce
#

and then all my services do 1 of two things

A: Mutate the game state (literally by just setting property values on it) (This is the Pub, publish, half)

B: Listening for PropertyChanged event on GameState and reacting to it, the "Sub" (subscribe) half

#

and I have a couple very very handy methods I made to make it super easy to pub/sub to it in a type safe way

flint geyser
#

Yeah you did about that

brisk spruce
#

I didnt know about the ITickable thing though, thats super handy!

#

my guide doesnt utilize that but that definitely shaves off 1 step of the process nicely

flint geyser
#

Oo, that's fresh

vast shale
#

I've got a tool that auto generates some prefabs, but existing scene instances get a broken mesh ref. If I re double-click the scene, the references reattach automatically. Only having this issue on current Unity version (2022.3.4)

For now just wondering if there's an editor command I can run that's the closest thing possible to double clicking the scene?

basically, force a scene reload in editor scope (scene manage seems like runtime only).

Anyone know the magic command for this one?

#

nevermind!

#

of course chatGPT had the answer. always forget about that one

cinder raft
vast shale
#

UnityEngine.SceneManagement calls were runtime only, didn't occur to me that UnityEditor.SceneManagement package exists.

Couple different API calls too, but pretty much what I was hoping - just a hard reset on opening the scene
EditorSceneManager.OpenScene(currentScene.path);

#

weird and annoying that it's necessary, but 🤷‍♂️
keeps me moving fowards at least

tawdry temple
#

hello guys, so i am making fps game and i wanna make the skin and animations invisable to me and appears to the other guys in the game so what can i type in search to have a tutorial im using photon pun 2

sly grove
#

It's considered spamming

tawdry temple
sleek terrace
#

How can I merge textures together?

The triangular holes between the hexes, I want them to have a merged texture of all the connectings hexes?

tropic stag
#

I have a parent object that is transformed in worldspace, and a child object with an offset collider (so the collider on the child has a non-zero center, and size). Now I want to, given an orientation/position of the parent object, test if that collider would hit anything with Physics.BoxOverlap().
But box overlap expects a position/size (in world space) + a quaternion orientation of that box. And I have the orientation of the parent. So I think I can get the world space center to pass to box overlap as : parent.transform.position + child.collider.center * parent.transform.rotation; ( or just using child.transform.transformPoint(collider.center), but how do I get the orientation of the collider if it's offset?
(I think I can insert another parent between, child and original parent and have that offset, so the collider is centered on the child and I can just get it's transform.rotation? but now I'm curious what the straightforward way to do it is?)

vale nova
#

Any idea why this throws an exception?
Invalid memory pointer was detected in ThreadsafeLinearAllocator::Deallocate!
Unity.Netcode.FastBufferReader:Dispose ()

          
Guid instanceId = Guid.NewGuid();
if (serializer.IsWriter)
{
    using var writer = serializer.GetFastBufferWriter();
    writer.TryBeginWrite(16);
    writer.WriteBytes(instanceId.ToByteArray());
}
else
{
    using var reader = serializer.GetFastBufferReader();
    reader.TryBeginRead(16);
    var bytes = new byte[16];
    reader.ReadBytes(ref bytes, 16);
    instanceId = new Guid(bytes);
}

I'm not very familiar in native code... thanks!

viral vine
#

Would anyone be able to help me out?

#

I have a linux VPS with a game server loaded up via Dedicated Server/Linux build and then a game client loaded up via Windows on my local PC

#

The players spawn, but they don't register the other clients movements

#

Testing to confirm I'm not moving the same object by moving the plane lower***

#

Yeah no-- player 1 falls -- gets moved to the left

Second window opened, player 2 falls on top of player 1, moves to the right. First window shows player 2 idle on top of player 1's previous position

plush narwhal
#

Im using:
MeshData meshData = Task.Run(() => {MethodThatReturnsMeshData()});
But it throws an error reading:
Cannot implicitly convert System.Threading.Tasks.Task to MeshData

How do I have Task.Run(etc) to return MeshData instead of a task, or will I have to create a dedicated method for it? (I don't want to create a dedicated method as it doesn't fit my needs)

sage radish
obsidian coyote
#

is there any way to attach a generic monobehaviour to a game object, and specify its type there rather than having to create a class like this each time?

obsidian coyote
brisk spruce
round wharf
#

anyone know why this
public unsafe static void Register() => ClassInjector.RegisterTypeInIl2Cpp<MonoEnumeratorWrapper>(new()
{
LogSuccess = true,
Interfaces = new Type[] { typeof(Il2CppSystem.Collections.IEnumerator) }
});

gives me the error
[Error] System.NullReferenceException: Object reference not set to an instance of an object.
at Il2CppInterop.Internal.Logger.Instance.LogTrace(String Message)
at Il2CppInterop.Runtime.Injection.InjectorHelpers.FindGenericMethodGetMethod()
at Il2CppInterop.Runtime.Injection.InjectorHelpers.Setup()
at Il2CppInterop.Runtime.Injection.ClassInjector.RegisterTypeInIl2Cpp(Type type, RegisterTypeOptions options)
at Il2CppInterop.Runtime.Injection.ClassInjector.RegisterTypeInIl2Cpp[T](RegisterTypeOptions options)

sage radish
obsidian coyote
round wharf
sage radish
obsidian coyote
brisk spruce
#

Id have to see the goal @obsidian coyote for what your actual code is needing this stuff for, to do whatever its doing.

obsidian coyote
#

atm they are setup like this, but this will likely expand in the future

brisk spruce
#

Ah, I see

#

I think your implementation is upside down, and thats your issue

obsidian coyote
#

upside down in what way?

brisk spruce
#

You are trying to have "children" mutate/do stuff to the "parent" they are owned

#

Thats usually a code smell

obsidian coyote
#

nah, they dont mutate the parent at all

brisk spruce
#

You're tightly coupling the children to "who" they are owned by

obsidian coyote
#

they just need to be in the parent context for things like ui rendering, since a ui element must be a child of the canvas

#

if anything im decoupling the various things from the base "owner"