#archived-code-advanced
1 messages · Page 71 of 1
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.
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
Ok I will check it
Oh and UniTask has "UniTask Tracker" in editor, you can open that and check if you accidentally leak tons of tasks running forever.
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
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.
yeah
this would be caused by:
- an infinite loop
- a deadlock (unlikely)
- doing I/O in the main thread
- doing any other blocking operation in the main thread
Could it be caused by intensive memory/GPU use?
no
what error you get if you get to memory 100%?
i mean theoretically if rendering takes a really long time that's blocking
OutOfMemoryException?
something along those lines
or a hard crash
ok
if it's in the unmanaged section of the engine
how can i change the width of an image (in pixels) via a script?
like :
myimage.width = whatever;
I think like this:
_image.rectTransform.sizeDelta = new Vector2(width, height);
Also, I would ask this in: https://discord.com/channels/489222168727519232/497874004401586176
Please don't cross post. You asked this in all three code-x channels.
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?
Camera direction is its transform.forward
I dont understand why not the camera follow the player but the player follow the camera
I think they want the camera to not move at all. Then when you get to the edge, you get a completely different camera position and angle.
Like it jumps there
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.
another good example: The camera is anchored to the corner of this room, but no matter where I move, up sends me forward, right/left sends me thus, etc.
That's the effect I'm trying to achieve.
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.
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?
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)
It's a simple solution I'm overthinking, or I just don't know how to set up the code in this particular case.
get and copy the direction and set its .y to zero then you get the direction vector projected on xz plane
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.
Vector3.ProjectOnPlane
ah, that is a new function for me
cant you just straight up use LookAt in this case?
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 ...
For the camera or the player ... ? I already have the camera looking at the player.
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
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.
ohh I see the issue, aight
I can't call the functions can you guys help me?
Your !ide isn't even configured, this is not an #archived-code-advanced question, it's a "start at the beginning" question
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.
Okay thanks
The quaternion goes first on the multiplication. It's not commutative
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. 
I usually separate data & logic from visuals if data or logic will be used also by different scripts. If it's used only by one script, then I suppose it can be stored inside.
If we are talking about preference, I would want a self-contained system that has no reference to anything then itself.
I generally just make sure UI is relying on the implementation and not the other way around. Worth noting that you could just disable the visual aspects of the menu without disabling the menu itself.
@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".
Oh, that's nice to hear, I didn't figure it out yet, kind of coming back to Unity seriously after a long time not using it. I'm using setting the visual elements's active status in the hierarchy to manipulate their visibility.. is there a way to do this without disabling the GameObject?
Just separate the menu from the visual stuff.
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
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?
can see in the UI the three fields show up at least
They are probably not correctly serialized and only live in memory.
You should try to look into how to correctly apply/create a serialize property.
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.
none of that applies to these guys, they are a different class and different implementation
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.
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
So, I guess the serialization was the issue.
yeah but in the wonderful "silently fails and docs dont mention anything about it" sort of way, wheee
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 :/
#🧰┃ui-toolkit is wild
That is real dumb
this feels like if css and XAML had a frankenstein baby, but in a back alley so its not documented much at all :x
That worked! I knew it was simpler than I thought. Thank you for helping me!
Did you get FlatSharp to compile in mobile platforms?
I doubt it works out of the box since you're likely using il2cpp
And it does code gen which is not supported
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?
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
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
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)
There are many serialization protocols libs you can try
Anything does build time codegen would make most sense for IL2CPP
I saw this Unity plugin https://assetstore.unity.com/packages/tools/network/flatbuffers-tool-for-the-editor-159043#content
Which has an option to generate the c# definition
but I don't know if that would work if I'm building on Android
based on this I guess it won't work
That's about flatc which compiles the protocol into each language
You don't need flatc on Android
The platform you need to care about that is the one you are using Unity on
So that is not a problem
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)
That's probably C# managed lib
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
oh okay, so basically it should be included just fine in an Android or iOS build
because it will get compiled into c++?
Yeah
cool, thanks I'll try it 🙂
If it's about advanced programming concepts, sure. Else find the most appropriate channel at #🔎┃find-a-channel
Yes
so talking tom voice record and playback are Hard ?
because i am making talking tom Clone
I saw your questions when you were muted yesterday for spamming. This is the wrong channel.
Then don't spam or call peoples mothers names
you are spamming again lol
@torpid birch Did you read the #854851968446365696 ?
Id recommend reading it again
WHAT THE MEANING OF SPAM
first of all you type 1 full sentence in like 4 lines.. how's that not spam? 😄
You are spamming right now
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 😄
Sending multiple messages in a short succession is spam
repeatedly sending the same statement over and over, sitting there asking "is anyone there" in a few different ways is spam
@torpid birch There's no off-topic here. If you are not asking questions or answering them - you're spamming.
Ohhh i am sorry about that 😅
also all caps is considered rude and disrespectful / shouting, and is another good way to get muted
Does anyone here have Gradle experience?
100% of my gradle experience is pretty much always "get some other 3rd party lib to do the gradle part for me"
my bad
😭 Idk what the hell is wrong with my Gradle but it refuses to work
this also has been my experience with gradle pretty much everytime I try and work with it @_@;
100% of my Gradle experience is :BUILD FAILED lmao
^
are you using android
Yeah im using android
is there another way for me to run a build on my phone without using Gradle?
if you are using android download new gradle
actually fun fact, the one time I had success with gradle was natively compiling android apps... on android
It only broke when I updated from 2020.*.* to 2022.3.5f1
I am using the newest version of gradle
on gradle website
As well as the newest LTS release
you probably have like 30 things you need to download and update, knowing gradle
Yeah literally
Im not sure what else I could use though
i also had this problem but i fixed them
something something java runtime SDK openjdk gradle foo bar phi package builder tools android google something something
to fix it you need to add user keystore to your game
Trust me
Check out this thread if you wouldnt mind 🙂
god speed and best of luck
i hope she work
Im not sure if I really have to do all that tbh
do it
Upgrading major version you should regenerate Library folder and recheck all the settings. If settings objects were changed they could reset,
Good sanity check is to create a new project and test if it will compile with needed settings empty
now you are spamming
!mute 980625836875063348 7d Ignoring warnings. Spam
issamiyad#0 was muted.
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
I don't have any experience with gradle. You might want to try forums for more long term questions.
Alright thanks man, much appreciated
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
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
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?
Is this for netcode that happens frequently?
yes
well, the game I'm doing is point and click so it's not like an FPS where you're constantly sending data
Okay so the format can be just Json then?
I feel like Json would be really slow
I read somewhere that compared to Flatbuffers is 40x slower
There's BinaryWriter that can write to any Stream, you choose what to write like in your example
It is slower for sure but if your usage is unstructured data then it is maintainable option
They're using C++ server vs C# client so may need some more tuning than BinaryWriter
Well it works on the encoding side at least
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
The thing that worries me is that if the server has several hundreds of users, and it has to read deserialize that many Json data, I think it might be too slow
maybe it's not that bad to use Flatbuffers 😂
Add more API servers 😄
What about something like messagepack? It's compact so it uses less bandwidth, and it's a global standard with a lot of implementations
MsgPack is not bad but might have some friction with IL2CPP
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
I'll check that out
Anyways I would recommend defining message format, it’s worth doing it
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);
}```
Pretty sure FlatBuffer can do union types.
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.
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.
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.)?
Finally figured out a wicked clean way to type safe pub/sub to INotifyPropertyChanged, and boy does it feel good
I get what you mean
but let's say that from the server you receive an array of bytes, how do you know what schema to deserialize it to?
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.
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) => ...
Union types are typically tagged, it’s just like the example I gave where the first byte indicates what type it is.
use Protobuf, itll make your life way WAY easier
protobuf was pretty much entirely designed for this exact use case
combine it with uh, whats it called... mediator pattern
and/or strategy pattern
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.
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
and how do you know what type it is when you deserialize? can you maybe do a switch based on the type?
you have a "root" object that has multiple OneOfs on it, and one of em will be not null and the rest will be null
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
have you tried FlatBuffer? I think it's similar to protobuf
I have not, theres a few solutions, protobuf is just the one I am familiar with
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>
I wrote it above, youd have 1 single class for all payloads, but it would have multiple properties for all the possible "types" it can be.
When you use OneOf for protobuf, one of those properties will have its value set, and the rest will just be null
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;
}
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 ?
yeah, prolly would be a good idea to subdivide those up into "category" classes as needed
You’d create a schema, the classes will be codegen’d for you.
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
so you only have 1 schema and inside that schema all the different message types?
thats where Mediator pattern and/or Strategy pattern can come in to help your sanity out for organization
exactly yeah
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
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.
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
it does not because protobuf has some kind of voodoo magic byte marching stuff going on
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
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.
effectively it "re-uses" bytes and does some wild compression stuff too
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
would this be the right way to do it? this is the flatbuffers schema
I have no idea about flatbuffers
it's the same concept as in protobuf definition
hmm I don't know if flatbuffers has the oneof property
protobuff doesnt have a need for the enum part effectively, it automatically generates it
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
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
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?
Looks like you can use gRPC with flatbuffers as well if you want to automate that stub part
I think this is to be able to call a function from the server in the client?
not sure how that would work tbh
Well I haven't tested gRPC on IL2CPP
But RPC is just basically exchanging packets
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?
By looking at the CPU Timeline
i was, there was 0 mem allocations in it
The hierarchy section should have a column with GC.Alloc
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
switch to deep profiling
Also, 6kb sometimes is not something unusal.
looks like its caused by this
deep profiling will show you exact method that generates
You also have the option to add Profiler.BeginSample to refine the search if Deep Profiling is not an option
@jolly token I created a template to avoid repeating the same code over and over, I can reuse it for multiple packet types now 🙂
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
Unity does a lot of questionable allocation.
graphic is a base type for a lot of third party components
tmp etc
i still consider tmp a third party, just realized
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
are you reparenting them when releasing to pool?
Canvas can be tricky If I remember correctly.
You want to look into https://unity.com/how-to/unity-ui-optimization-tips#pool-ui-objects-smart-way
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.
my thought was more about the transform type, i am not sure but reparenting a rect tr to a normal tr can cause allocation?
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
scrub it maybe some spike will show something
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.
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
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 😐
i feel the same way
and here i wanted to flex a 0b allocation game to the other game devs i work with lol, oh well :S
well your code is 0, it counts
are you profiling an actual build? profiling in the editor is more like a guideline and can contain phantom problems and other inaccuracies
It was just in editor , so that's fair, I'll have to check vs a build later
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?
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?
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);
}```
lmao, I'll try running it
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?
There's an overload with ParallelOptions
ah thanks
By default, methods on the Parallel class attempt to use all available processors
im assuming thats including the threads used by unity cause it is causing some lagspikes, so im gonna limit the threads allowed
async/await isn't multithreading
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#
Their goal doesn't seem to be off load the work to a different thread but rather parallelize the work
oh ok
The easy way, you can use factory method for this and set TaskCreationOptions.LongRunning it will create a new thread (this iirc, is undocumented)
oh they seem to update the doc. Yeah, see LongRunning part there https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.taskcreationoptions?view=netframework-4.8
just becareful when using factory method
Ill look into that for the other parts i need to multithread but so far, just parralising my foreach loops was enough. Thanks
hey! is there way find mouse position on mesh without collider?
You gotta do the collision detection yourself.
There is not really a reason to not have a collider on something that you want to collide with or detect.
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
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;
}
I am not making a game. I have model who is 1:1 to real life. And i want to make measurements. Gameobjects are to complicated. I have reason for that.
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.
how i can be sure that i put collider right? and how i can put collider right if that isnt regular shape?
By using a mesh collider
lol ty XD
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
~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)
1.6.5 -> 791MB.
1.8.4 -> 680MB.
Task.WhenAll() is your friend
Something like
var tasks = foos.Select(DoTheThingAsync)
return Task.WhenAll(tasks);
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?
Task.Run runs things in a background thread
don't start it with Task.Run
I don't think it supports an asynchronous/background thread approach
Ok apparently it does:
https://arongranberg.com/astar/docs_rvo_fix/class_astar_path.php#a41c928232446156b4b13e097c18918d2
Looks like it's a "pro" feature
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?
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
Hey guys, I am trying to build the .dll from https://github.com/google/flatbuffers/tree/master/net/FlatBuffers
But when I add this dll to Unity I get the error The type or namespace name 'FlatBuffers' could not be found (are you missing a using directive or an assembly reference?)
should I do anything else besides opening FlatBuffers.net35.csproj with visual studio and building?
and copying this 2 files to unity
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
any reason not to use Unity's built in 2D physics?
I am unable to use it because the movement is not physics-based.
Why does that make you unable to use it?
Give your object a kinematic Rigidbody2D and a BoxCollider2D
then you can use Physics2D.BoxCast to detect obstacles
but I also need to get a vector movement that will correct the collision
so?
What would be stopping you?
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
100% the case for BoxColliders and Physics.BoxCast or Physics.OverlapBox
i used Physics.Overlap before but it doesn't return a vector to fix the collision, am I missing something?
BoxCast will
though im not actually sure what you mean by that
what does "a vector to fix the collision" mean?
for example when the physics engine detects overlap betwen colliders
Actually you know what
i agree
This is exactly what you want:
https://docs.unity3d.com/ScriptReference/Physics.ComputePenetration.html
it corrects their position
damn how did I not find that
thanks man
can you help me with something i cant find an appropriate channel to ask
please
ty
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
}
It depends on what each CreateContextMap is doing, because it must be thread safe. Normally, it's not possible to use classes in jobs. It's impossible if you want to use Burst, but can be worked around if you only need jobs.
thanks for the answer i have an idea on how to fix my issue.
You can't use managed types in jobs. That includes your float arrays, your lists, and probably baseBehaviour and AIData depending on what those are. You definitely won't be able to use anything involving abstract classes.
you should probably go through some simple "getting started with the job system" style tutorials first to get an idea of how it works
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
I'm not sure this is true. I think what they meant to do was something like:
(evade[i], interrest[i]) = Behaviour.CreateContextMap(evade[i], interrest[i]);``` in a loop
but maybe
But the method in uml return two array
Can anyone help me recreate the viewfinder mechanic in unity?
Though array is a reference type, no need to be returned, the length of return array should be same as input i think
thanks for the tipp i will do that.
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
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)
Could make a collider the shape you want and check for collisions
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?
You can. But you can also scale the collider out slowly
I dunno about efficient, depends on how many raycasts
Looks like there is an OnParticleCollision method actually.
It sends one message per particle collision
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 🤔
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.
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
That's a good flex... my code crashed Unity a few days ago because of recursion of a heavy function (Patched it but dunno why I had a heavy recursive function to begin with)
How would you network that though, cause there's no way to make a particle system emit following a seed so it could be that a person gets lucky and flames go a certain way but on the person receiving the damage the flame went to opposite way (dodged in a way)
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
Didn't know networking was involved (edit: i'm super dumb, you said it was). Don't know anything about it, sorry.
it was a 7800 line file as well, and that getter was somewhere around the middle of it 😐
That's fine, your not an AI chat bot lmao (and yeah networking is an asshole sometimes, whoever invented latency was also an asshole)
(for other people reading, latency was discovered, not invented)
you wouldnt really need to if the server was handling collisions anyways. Just make sure the flames are visually accurate for clients
But, also don't want playing seeing themselves start burning before the flame actually hit them
if this is a #archived-networking issue then u can find relevant discords pinned in there. though something like this really shouldnt be that much of an issue, if you notify the client that they're burning, you shouldve already started the flame visuals by then
You can use StringBuilder, won't be zero alloc though but small enough.
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)
To be honest, I'm not sure I understand the need of such structure. What you are trying to achieve here ? What is the end goal ? Why can you not directly use GameState ?
Ditch out stringBuilder and use communitytoolkit's StringPool instead 🥹
Span it up.
I have no idea what you are referring too. I also doubt that someone here would truly know what is the "industry standard" for such things. After all, we are using Unity, not making our own engine. (I also found no reference online)
TIL this is also a thing https://github.com/Cysharp/ZString
But yeah super micro optimization territory, pretty sure this amount of allocation is irrelevant for incremental GC anyways.
this is not zero alloc in certain scenarios btw, I tested this
StringPool tho.. the alloc only on the 1st time when filling the cache
after that zero alloc for days
I see.
There are quite a few folk around here with a fair amount of programming experience, specifically in C# and in game development. If there's going to be someone who knows in a server it'll probably be here.
As for ""industry standard,"" see to the double quotation marks on ""industry standard.""
The proper term is collision resolution if you're googling for it.
(Depenetration specifically)
Or circle packing may apply somewhat
If you interested, Unity use Physx which implement Physics.ComputePenetration (PxGeometryQuery::computePenetration) I guess whatever method Physx use would be the industry standard.
Interesting, I'll dig around there-- cheers!
It's a debugging tool on a game object that I can use the editor to directly manipulate any piece of the gamestate to test stuff and verify its wired up as expected.
GameState processes mutations via a method on the setters of its properties, and is a POCO, so I need some kind of intermediary MB to interface with it
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
This seem so complicated for a debugging tool... I usually have a console where I can simply type command to execute. There is also the possibility to write your own Custom Editor (No need for the object to be serializable) or even overwrite the default inspector to print/format all the value of a given object.
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?
You do not need a MonoBehavior nor need that it is serializable.
Use a custom editor
Custom editor is interesting, can you hook it up to INotifyPropertyChanged event?
Custom Editor are C# code. So I guess
How does the custom editor "hook" into the specific POCO instance I am working with?
Does custom editor already subscribe to if the property's value changes?
You are the one defining that. It can be by resolving the reference with static, or GetComponent, or even AssetDabaseStuff
You can check if a property has changed in the inspector or a custom editor. (If it has been changed through the editor)
It's not a component or an asset
You can't "GetComponent" it, it's a POCO
You can GetComponent something that has a reference to your POCO
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
There is no need binding in the case of an Editor
You can still update or be update
Without binding directly
I'll check it out
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.
actually no, this can generate errors, you would need to use a Delayed field
How so ?
The slider works perfectly fine.
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
Even the documentation use the same approach for https://docs.unity3d.com/ScriptReference/EditorGUILayout.TextField.html
Oh I see.
I was not thinking about that particularly
But, yeah, gotta be careful about those case.
noted, Id have to look at how this actually looks in the code because it seems like it might result in even more code
it should result in less validation rather than more because you will have a stable state
The idea is to use reflection to construct the EditorWindow
mostly Im just interested in making that code easier to maintain
yeh if this is possible then I am interested
wtf, this is game dev, who cares about maintenance?
I mean, for your own little project, maintenance should not be high in priority.
this is a pretty big object and everytime I add a property, right now I need to:
- Add a matching field to the DebugGameState
- Bind the GameState -> DebugGameState write for that Property->Field
- 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
my guy just flies in the air instead of sticking down to the ground. help
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
this is the inspector btw
Depends, if it's not frequently accessed/queried it should be fine. but it's your pick
also NOT ALL Linq methods create garbage, e.g : AsEnumerable, ElementAt, ElementAtOrDefault, Single, SingleOrDefault
those are free pretty much
Do not use Linq in frequently update code and you should be fine.
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?
I don't really know what to do for you here other than point you towards the documentation / getting started guide:
https://vcontainer.hadashikick.jp/getting-started/hello-world
It sounds like you've tried little other than asking ChatGPT for help, which predictably resulted in nonsense.
(+ asking or answering questions generated by AI isn't allowed here)
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 ..
Are you wanting to be able to configure stuff like distance, bounce count, first bounce height, etc?
Sin wave with a height modifier using something like % pi or whatever should work
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..?
so prolly want
float distance
int bounceCount
float heightMulti
float chaos
for params
hm, probably don't need all that, just an initial X and Y velocity (damping and "gravity" can be fixed)
so prolly just a vector then
Maybe rigidbodies is gonna be easier than trying to .. recreate gravity and handle bounding boxes and damping and all that nonsense
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
2d isometric tile game
oh yeah rigidbodies dont have much overhead in 2d land
isometric "maybe" - for prototyping we're just using 2d overhead
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
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
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.
hmm
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
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
yeah it's nicely done
and performant
It's kinda one of those things that probably should be in every project. Like Cinemachine
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);
Looks decent for 3D text animation since I've been just coding that all in normally, and some using the timeline
i think that's a paid feature, can't recall
WELL
Oh, no, it's not - DOText
I rolled my own but probably could have used theirs as well
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
I probably don't even really need a bounce... shrug This looks maybe ok? Realized I can't use Rigidbody2D cuz I'm doing all this in the UI layer so I'll need to do it by hand.
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
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?
You can edit a SO freely as long as you have a reference, but remember that editing will affect all objects referencing that instance.
Ah, sorry glanced over your question on my phone, but yes, you'll probably want to make your own debug menu for the build and create a gui for it.
not exactly what I had in mind, but thanks for the help!
Yeah, that's what I thought. Sucks there's no easy way to do it, guess its never easy haha
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
Part legacy, part consistency, part being a fuck ton of work when you have random people calling random things
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
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
Most unity API would fail outside of the main thread. In fact that's the same for most game engines. Mainly because you want to avoid race conditions.
Most scripting layers at least
You can look at DOTS physics if you want parallelism, though it might require you to remake a huge part of your game.
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??
Might be outdated but google tells me this : https://forum.unity.com/threads/accessing-other-players-data.1187131/
Another post talk about Cloud Code script https://forum.unity.com/threads/how-to-get-other-player-data-using-unity-cloud-save.1465370/
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
I can’t believe I have to jump through hoops just to see logs…
And I don’t know what hoops to jump through
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.....)
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.
okay
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?
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.
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
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.
your shape should have a "root" element (one of the tiles). For a given position on the left board, loop through all of the tiles in the shape (as offsets from the root position) and see if they are empty
that's all
Yes, I was running a dedicated build on GameLift services. https://aws.amazon.com/gamelift/
I see, I want to use the positional data I have now in the 3x3 grid but select one as the root
I was trying to figure out dynamically assigning that root, but that may be too hard/impossible?
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
}```
lucky for me the shapes are designed to be squares on a grid, so all my shapes are inside a single List<Vector2Int>
you can use RectInt
doesnt using RectInt make this more complicated than I need it to be?
that would work yeah, I will just need to adjust the position from the 3x3 grid to be relative to its root that I will need to define
not sure if I can define that root on the GUI that I have
not sure, wont using a 2d array make it all less complicated?
realistically you don't necessarily need to adjust any positions in your 3x3
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
my root data is a bool[3,3]
wont these make it all less complicated?
the puzzle grid is a 4x4
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
you can always start the for x for y loop at any index
effectively offseting the starting position
the method that will make reasoning about problems easier
The cute/clever way to do this is use bitfields
but - I shouldn't even have said that 🤣
lol
inspired by sebastian lague's chess video
bitmap is a 2d array or im misunderstanding
that whole board is just 16 bits
you can represent all of that information in a ushort
What did you have to do to see debug log statements?
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
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
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
Nothing particular as I remember. But again, I was not only developper on the project.
Yes it would definitely be the most performant approach I believe
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
So you're saying you can produce a dedicated server build with a single component that produces logs and then see the log statements?
I'd like to see you try
I said, that I have worked on a project that had logs printed. Not that I could do it from scratch.
Gotcha. Think you could try?
I was just sharing the little knowledge I have on the situation you are experiencing.
Cool cool
It is kinda long to do.
You would have better result trying to reach someone on the forum
How long does it take you to make an empty project?
To build and setup everything. 15min ?
Sounds like that's kinda long to do. Yea
Given that Unity is installed
And given you have a computer
And that, without trying multiple configuration
Because It might not work out of the box.
As you seem to experience
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.
is it a development build?
Debug.Log gets stripped out for production builds
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.
development players
yeah
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) +
"®isterPass=" + UnityWebRequest.EscapeURL(password) +
"®isterUser=" + 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);
}
}
}
You have to add a new DownloadHandler to the unity web request (aka www.downloadHandler = new ...)
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
Sounds like an issue with your server, it's executing fine but the server is not responding
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
Your browser and Unity are not teh same
Your server is doing something
Check the logs
Debug.Log call do not get strip in release. String concat is still happening.
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
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.
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”
Hve you tried with a Standalone Windows Player ? Because it was working for me a couple of week ago.
In an empty project.
I’m steamed about it. Seems simple, it isn’t. I just need to slow down and solve it or move on.
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
show the rest of your code.
It's not this
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;
}
}
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?
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
MMWG (http://u3d.as/oDY) wikis, issues, and most recent patches and betas. Plugin Tools are required along with this repository to make MapMagic...
by the way that's a link to the docs for MapMagic which is a great tool for this kind of thing.
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
question, maybe you'd know this. Can map magic generate "seeds" to the terrains it creates by default?
It can generate terrain from a seed, not the other way around
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?
I would expect that you are experiencing an exception that require to gather the stack trace.
That looks like it, from its name. What would ideally be my next step?
Solve the exception ?
Yes preferably, or in general in regards to thinking about what next.
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.
Collider on projectile. Three layers for projectile types. Set up the collision matrix properly.
Or tag based checking with the oncolliderenter.
There's probably better ideas, that's just what came to mind first
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
what kind of projectiles? this likely isnt an advanced topic. you can just raycast and fake the projectile visuals. The raycast logic will take care of what objects can be hit while the visuals just follow along for the ride.
Like really visible, slow projectiles. And the enemy can move from the target position while the projectile is on its way.
You can possibly just use a trigger then on the projectile. The OnTriggerEnter function would take care of if the projectile should stop or not. No need to deal with the collision matrix, as this would use up a lot of layers anyways and be fragile anyways
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?
I didn't specify previously, but I want it to be both ways. First is for behaviour like ghosts, second is for behaviour like an enemy with a shield
So far it looks to me like there's going to be some kind of inversion of responsibility anyway.
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?
(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.
gotcha, ok i'm assuming we ignore the resources taken up by EditorLoop?
thanks
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);
}
}
}
does anyone know a way to rebake the navmesh system while the game is running? is that impossible?
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)?
to get the current dpi https://docs.unity3d.com/ScriptReference/Screen-dpi.html
exactly what I need, thanks, life saver! 🙂
https://docs.unity3d.com/ScriptReference/EditorGUIUtility-pixelsPerPoint.html also works for editor applications
ah excellent, this returns 1.5, good stuff 😄
which part am i looking for on that page?
the navmesh surface?
How can I properly create a uv for 3d mesh so that it maps to 2d texture?
the flat part(2d) part of the mesh is rendered fine, but the slopes/hills are elongated
looks like piles of shit lmfao
LMAO
have u tried stitching it together to enlarge it then applying your texture
wdym?
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
i havent slept btw so take everything i say with a grain of salt
You need to keep the same distance between UVs.
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
I got my current code off chatgpt, I have no idea how to make uv, please go ez on me
Start by learning what UVs are...
lmao
uv are coordinates on a picture
they are used to figure out which pixels to color
So, you know exactly what I have just said
yes
im dealing with 3d here tho
if it was 2d, I could simply divide by the max sizes
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
go to fiverr and pay 5 cents to a ugandan refugee to do it for u
Maybe you just have to set your UV higher than 1
lack of sleep is one hell of a thing
3 ideas u can do right here man, fiverr, learn about uv, or increase ur pixels for applying the texture
Read the methods on it. BuildNavMesh() for example
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?
One way would be to add a property to your interface to help distinguish one from the other. A simple example:
interface ITargetable {
public int TeamNumber { get; }
}```
Another way is make sure you're distinguishing them during discovery. For example if you're discovering enemies by physics queries, use a layer mask that excludes your own team.
I prefer to use a separate component for this kind of thing, rather than implementing interfaces, but the concept is the same
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?
I don't understand what you mean
The other option is an abstract class and it's more restrictive than an interface
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
}```
I think this approach is more limiting because there might be division not based on team allegiance
this is just an example
without knowing the concrete requirements it's harder to be specific
In your case, the best is to divide into multiple component. Have the player GameObject owns a Target Component and the Enemy have the same. Player depends on Target, Enemy depends on Target.
Usually, circular reference is sign of bad division of responsibility.
Is it in this case? It isn't like the enemy and player directly rely on each other
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
Use composition in what sense?
https://en.wikipedia.org/wiki/Composition_over_inheritance#:~:text=Composition over inheritance (or%20composite,from%20a%20base%20or%20parent
In Unity, composition is simple as dividing into multiple MonoBehavior
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?
It limits the amount of serialization you can do as you need to have MonoBehavior for serialization
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.
Should NOT?
Yeah, not
How can I go about creating UV coords for a shape like this?
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
I just want to map a whole texture onto it
and you have to explain what that way is
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);
}
https://www.youtube.com/watch?v=eiDrRa6JvQ0
This is a decent primer
This is for blender
but the concepts are the same
these hex are done dynamically
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
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?
yep
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
ok
more of a shader graph tutorial
after doing some research triplanar is definetely the way to go, I will look to implement it
Just have a service that keeps track of everyone and you can call stuff like .GetEnemies() and .GetPlayer on it
Also have that service be in charge of all CRUD operations for all the entities, so it always knows where/who everyone is. IE it will be what you use to SpawnEnemy and DeleteEnemy and etc
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
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?
Which graphics API?
DX12 sorry
been searchihng for a way to do bindless textures for over a year at this point
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
heck
I'm not very familiar with how DX12 deals with state, but it looks like texture binding is confined to the command lists.
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
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
Yeah, I should probably use a Color Array and use SetPixels after. As for faking the raycast, that'd be difficult since I'm needing the normal of the surface.
yes SetPixels will be much faster
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
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
oh yeah fair point
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;
}
}```
you're about 1 step away from proper dependency injection setup 🙂
Could you tell me what it is? 🙂
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
Yeah, that much I know. I guess spending a week on reading a DI book wasn't in vain
However could you expand on the last step you mentioned?
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
So the step you mentioned is to get your dependency and abstract from how it works, right?
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;
}
}
You forgot to remove the controller I think
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 🙂
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
how are you injecting dependencies at the moment?
Zenject is fine with registering references to MonoBehaviors for injecting
Wdym? [Inject]
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
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
you do naturally end up having 1 single MonoBehavior alllll the way at the top of your injection tree as your "entry point"
So you have an Update() to hook into
The installer, right?
but then everything below that entry point can be a POCO
nah thats seperate, that one runs before that process
I don't understand
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
So how would you subscribe EnemiesManager to GameController in my case with that GameEngine of yours?
In my case I utilize a special middleman class I call my GameState, and it utilizies a pub/sub model with INotifyPropertyChanged event on a buncha properties, all representing the "state" of my game
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
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
I believe I pinged you about that here 🙂
#1134198357758320670 message
Yeah you did about that
I have a blog post I made that shows an example of all this at play and how to implement it, you can check it out if you like:
https://blog.technically.fun/post/unity/building-a-gamestate-with-zenject-in-unity/
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
Oo, that's fresh
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
what was the answer?
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
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
Cross posting is against the rules here
It's considered spamming
sorry idk where to put it
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?
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?)
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!
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
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)
To get a value from a task like this, you have to use await in an async method. And then MethodThatReturnsMeshData would have to return Task<MeshData> instead.
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?
No
Ah rip 😦
Why do you feel the need to have to do this at all?
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)
No one here is going to know about IL2CPP modding
just so i dont need to define the implementation each time, would be cool if generic scripts could just turn into w/e by specifying the type in the editor
i dident know where else to ask
Can you not have a Type field?
Isn't there a Discord server for whatever library you're using?
this is what the actual base class setup looks like, not sure i understand what you mean
Id have to see the goal @obsidian coyote for what your actual code is needing this stuff for, to do whatever its doing.
basically i have prefabs like HealthBar, and Info, etc that link to some aspect of the tank and tie to its lifecycle in some way, but they need to be attached to varying parents, like as children of different canvas's, or in the base scene, etc
atm they are setup like this, but this will likely expand in the future
upside down in what way?
You are trying to have "children" mutate/do stuff to the "parent" they are owned
Thats usually a code smell
nah, they dont mutate the parent at all
You're tightly coupling the children to "who" they are owned by