#archived-code-advanced
1 messages · Page 116 of 1
but everything has to be done through unity authentication service which is done on the client
Just don’t share the key with the client?
can i have multiple keys with different permissions?
i was under the impression that being authenticated was your "key"
Most certainly
Keys are per player, org, game whatever, you can set permissions what a key can access
It would be the most pointless API ever without that
yeah i just dont see any sort of key management dashboard
service accounts look promising
ohh wait
ahhhh i see
so the server instance would authenticate as a service account
to give the player currency
wait no
all these APIs (incl. playfab) use such a pattern. Server runs on a privileged account/key, players on a personal account/key
service accounts are for changing settings programatically
yeah nvm im back to being confused
i cant find anything to control what the player can an cant do
Usually account management is a whole separate service
The Economy service allows the game client to retrieve and modify a player's economy resources in the cloud.
the docs do imply the player should be allowed to modify their own resources 😂
i think in this context "game" is the entire live service, and each instance of your unity client is a "client" including the server
and definitely no key systme
its more like an all or nothing "is this available yes or no"
you gotta set up those policies yourself
there is a Economy admin API, which is a resource you can restrict in a policy
i could definitely keep using multiplay and just self host an sql database or something for player data
seems a lot less convoluted than this
my biggest concern is fucking something up since theres no dashboard to manage this
Never used something like this, but if there's no server, what stops a malicious client just take its own key and give itself infinite currency?
there is a role called "Economy Resource Editor"
I take that as you can limit what a key can and cannot do, in which case what stops a malicious client that spams something its key can do?
presumably the game client would only be allowed to read currency values, and anything involving writing them would be done by the game server
it would be ridiculous if that werent possible, the core of any managed cloud services is the account/premission management
But isn't the whole point that there is no need for a game server, or am I mistaken?
there always is a server, the point is that the runtime server for matches is not the same as the backend that stores persistent player data
Ah, so it's basically selling you a storage solution with permissions and what not, you still have to build your own server side logic.
no
the account management service gives you an API to set permission, per user/role on resources (other service APIs) that are offered
these other services implement features like advertising, matchmaking, provisioning of runtime servers and in this case, microtransactions and persistent player inventory
at the very least these services have a "view" and a "admin" permission set.
usually, on the client, you make a request to a public API, /set/money/USER-ID/10000000?auth=MYTOKEN
and if that token doesn't have permission, the money wont be set
its usually more complicated than than, not through a sniffable token, but in essence thats what happens
Sure, then how would you implement something like "player passes a level and should be rewarded some currency"?
the runtime server has a priviledged token that can give the currecny to the player
that server obviously has to be 'trusted'
the Economy API is basically just a counter (for currency) and a list (for items)
+permission on who can change what counter
all these backends are supremely trivial in what they do for a game
Where do you write the code for the runtime server, is it a separate Unity project?
which leads many to DIY these things, until they figure out that the permissions, security, availability, scaling bit is not so trivial and boring AF
(a counter that is very likely to be correct and available)
thats your regular unity netcode, if you go with the single-project for server + client you need to provide secrets only to the server and #if SERVER all other secrets
Interesting architecture.
thats basically how all live services work
i think its one of those 'aha' things to realize that your unity-server-app is just one component in the context of an entire multiplayer/online/live-service game
I guess you can think of it as different levels of trust and persistence
The game client is very non-persistent. I can shoot my computer with a gun whenever I want to (or turn it off, I guess)
It's also very non-trusted
Servers that run game instances are trusted, but not very persistent
And then you have a backend that's trusted and persistent
Unity is providing that backend here
Not the front and backend distinction, but that if I was to build something like that I wouldn't go "oh yeah my backend is also a Unity project" I'd just have it a regular web backend or whatever.
I suppose for cases where the backend does need to have more context about the game, it would enable logic sharing.
ofc your persistence is just a http API there is no point in making that a unity app
Make sure you're distinguishing the game servers from the rest of your infrastructure here
The game servers are much more likely to be an actual Unity application :p
(but they don't have to be -- you can do all of your server logic however you want, and then present the results to the player in a Unity game)
you can make your game server in node, and die a slow painful death of realization
nothing is as glorious as doing a competitive multiplayer game with json messages over HTTP
putting the lag in lag compensation
it also murders your bandwidth
thats the next realization, its not O(N), its O(N*N+1) for each message
presumably you would use something less obviously unfitting, like WebSockets
I mean, it's not like Node.js is incapable of doing anything other than JSON over HTTP, but I digress.
the one who picks node for this problem likely is not aware of that
i find node usually gets picked because the team isn't comfortable with any other server tech.
usually there is also a lack of awareness what it even means to do realtime networking
Presumably you are not locked to using Unity Netcode for your server to talk to Unity Services, right?
i think you mostly are~
you at least need to use unity transport if you want to use the relay service
don't think there is anything else to unity netcode that would be required
Yeah looking at the Unity Services docs, seems like things are documented and have OpenAPI specs so you can just plug that into whatever.
this is what i mean by it feels half assed btw
u cant even pass a player id to any of the economy methods
u have to bang rocks together with raw api requests
Increments the balance of the specified currency for the currently logged in user.
Man this really does feel like they want to let the game client directly set currency values
yup
looks like they're trying to on-ramp you to use cloud code with economy https://docs.unity.com/ugs/en-us/manual/cloud-code/manual/triggers/tutorials/use-cases/reward-top-players#Set_up_Economy
that's more like the pattern I'd expect to see: client code calls cloud functions, cloud functions do the currency stuff
ah, and I wonder if the cloud code gets the "context" of the client that caused it to run
yeah but this sorta blocks off a lot of multiplayer capabilities
The more the API does on its own the less you can use it to your own ends. Economy is not supposed to do anything. It’s just a database of raw values that you assign meaning to in your game
What it provides is reliability
So people trust your game, and items bought for real money or by spending time in the game don’t get lost because you thought you can DIY it all.
I find it funny that you can break down most game rules to changing counts of items in a list
my game is about a list of things
some of the things remove other things from the list
Yeah
I call them props (like props in a play)
my props are entities
they just don't do much thinking
unlike the player entity, that thinks a lot
so, it really seems like theres nothing stopping someone from spoofing their player id to play as someone else
the unity staff on the forums just say "send the player id to the server"
after authenticating
steam allows you to authenticate users so that this doesn't happen.
look into steamworks.
If you wanted to manage your own system, you'd have to keep track of purchases & user accounts, and somehow have the client send a short-lived web-server-generated token when he wants to connect to a game server.
If the game servers are 3rd party hosted, they'll have to contact your backend master authentication server and verify that short-lived token. It needs to be short-lived to prevent other players pretending to be other players, if the token ever got leaked somehow.
also don't ever send usernames/emails & passwords to game servers as authentication. bad idea. always use a token.
i use steamworks
and what i said still applied
but i was wrong on the approach
the correct way to do it is to send both the player id and the auth token
and use the get player api endpoint to verify that they match
on the server
i just send the player id and auth token via an rpc and encrypt with rsa just in case bc i dont know the specifics of how rpcs are secured and such
and once this is done, the server has the player's id
and i authenticate the server as a service account
so i can interact with things like the economy api
achieving what i was originally trying to do (server authoritative player data management)
now to waste my time writing an abstraction layer on this since unity couldnt be bothered to
Can i use steamwork api if the app isn't installed from steam?
I wonder if i can use steamwork api for android version of the app
what on earth for, considering steam won't be running on an android device 😛
If you manage to make the steam libraries compile and run on Android, maybe.
I need the matchmaking system so that player can play multiplayer with steam
is it even legal to do that? And how?
If it's possible and they can't detect it, probably. But most likely it's physically not compatible.
That doesnt sound like something that is legal
You'd usually have your own server for that and platform specific API only for linking the players to your server.
Yea i know, i just want to know if i can avoid the cost of having a server with steam api
You'll need to read the steam terms of service. Do they require you to implement steam API for networking? Or can you have a custom implementation?
i dont have a lawyer, i dont think i can read that
Anyone can read that. It's in English. And it's better than asking random strangers online about issues that can potentially get you into legal troubles.
steam matchmaking requires the players to be playing on steam accounts which you obviously can't do without steam, you can implement cross multiplayer by other means (there's better options but valve even offers their networking code as a cross platform library) but the matchmaking part will need to be a platform-independent service if you want it cross platform
I have a list of scriptable objects in an Authoring script and I want that to bake a similar list with entities in my component. My Component has public Entity[] EnemyPrefabsToSpawn; and the authoring has:
AddComponent(enemySpawnerEntity, new EnemySpawnerComponent
{
EnemyPrefabsToSpawn = ConvertToEntities(authoring.Enemies),
/// ....
});
}
private Entity[] ConvertToEntities(Enemy_SO[] prefabs)
{
Entity[] entities = new Entity[prefabs.Length];
for (int i = 0; i < prefabs.Length; ++i)
{
entities[i] = GetEntity(prefabs[i].prefab, TransformUsageFlags.None);
}
return entities;
}
But I get "The type 'EnemySpawnerComponent' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'IBaker.AddComponent<T>(Entity, in T)'CS8377"
and what is EnemySpawnerComponent?
I holds my enemy spwan wave information: ```cs
public struct EnemySpawnerComponent : IComponentData
{
public Entity[] EnemyPrefabsToSpawn;
public int NumOfEnemiesToSpawnPerSecond;
public int NumOfEnemiesToSpawnIncrementAmount;
public int MaxNumOfEnemiesToSpawnPerSecond;
public float EnemySpawnRadius;
public float MinimumDistanceFromPlayer;
public float TimeBeforeNextSpawn;
public float CurrentTimeBeforeNextSpawn;
}
Would it be more idiomatic to have multiple monsterInfo components in the spawner, that I iterate through with the monster info and prefabs?
Entity[] is not a non-nullable value type
That is why you're having problems here
I believe you need to create a "blob" here
It's been a hot minute since I worked on Entities
But I had a somewhat similar situation -- I was creating spawner data and needed to encode a variable number of "rules" for each of my tiles (I was doing wave function collapse)
If you have a Foo[] in your authoring data, you'll create a BlobBuilderArray<Foo> with a size equal to the length of that array
Okay, thanks. I'll look into blobs. Have not done anything with blobs yet, so that's a new thing
The idea is that a blob has an exact size for everything
exactly 17 things to spawn, for example
Hello, I have a save-load system. It is possible to save and load object information as well as animation data for objects with animations (such as layers, parameters, current state, clip time, and clip name). However, after the scene is loaded, the current animation state starts playing again, which causes animation events to be triggered and executed.
How can I prevent the animation from playing upon scene load? My current system does not save the duration of completed animations, so I cannot adjust the animation's timing. I would greatly appreciate your help.
Is it true that Vector3.zero and new Vector3(0,0,0) don't get optimized to be the same code in C# Unity? the docs say so: https://docs.unity3d.com/6000.0/Documentation/Manual/UnderstandingPerformanceSpecialOptimizations.html#:~:text=final binary application.-,Trivial properties,-Unity provides many
I always thought modern compilers are good so I wouldn't have to worry about smth like this
optimized to be the same code
Have you considered running it through ILSpy or something similar?
Hi i am stuck in the code can anyone help me ?
The task is to move the car and avoid any obstacles and follow the path
#💻┃code-beginner is where you want to ask. Also post your code and be more specific with your question. IE "when I write this line of code it doesn't seem to work" or "I am trying to do X but it does Y - here's my code"
Is there any way to load scene additively with no spike?
profile your game to see what's taking up the time -- but it's always going to take at least a moment to create all of the objects, even when loading the scene asynchronously
We're currently trying to do something about that at work! The plan is to have a custom Awake method on pretty much everything, then execute that manually over multiple frames following execution order rules, and only then activating the scene, which should be better as there would be no Awakes.
break up whatever is causing the spike into multiple frames
This sort of thing is an implementation detail, and up to the runtime, not the compiler.
The compiled dll will always have a method call for accessing properties. At runtime, Mono JIT might spot this and realize it can inline it, or it might not.
IL2CPP is a different runtime and so it can have a different behavior here.
Does anyone know a tutorial to a good wave spawner system?
Question on file saving and serialization. Currently my solution is text based, but I am having some mental block organizing classes. As it stands I have 2: a Serializer that just writes and reads from disk and a DataHandler that parses the data and converts it to more strongly typed internal datatypes.
Should these classes be static (the Serializer currently isnt) and am I way overthinking this?
Are you using an existing serializer like JsonSerializer? If not - why not?
You want:
- Some kind of manager for handling save files and/or profiles (if your game has them)
- An internal strongly typed data model for representing the game state
- A serializer that can serialize and deserialize the data model in #2
The save manager should be responsible for (when saving the game):
- invoking the serializer to serialize the current game state into text
- Saving the text to a save file
And when loading the game: - Reading the save data text from a file
- Invoking the deserializer to convert the text to your internal model
- Rebuilding the scene based on that model.
You can and should use an off-the-shelf serializer rather than writing your own from scratch usually
I already wrote mine, but im more concerned with whether the two branches (dealin with system files vs internal data models)
A: should be split into two separata classes and if
B: should be staic instead of instanced
B is really vague as to be almost meaningless. Should what be static?
A. Should what be split into separate classes? Are you asking if you should have a separate DTO for saving vs the class you use in the actual game? I would avoid that if at all possible because it's generally unecessary complexity and maintenance. If you can use the same class for storage and at runtime, that's ideal. There's usually a pre-save and/or post-load pass you can/should do to the data if you need to set up certain runtime references.
i avoided json because i personally like a simpler file system and have very low requirements for my data. Its easier for me to use my own than json, though they look very similar.
Almost nothing in this process should be static generally except perhaps a static singleton reference variable for the data manager.
I am asking if the serializer/handler class(es) should be static classes as they dont need to exist as an instance, but my searching shows me people really advise against statics. The methods on the class are largely functional and aunaware of an instance.
WHats your reason for avoiding static?
What's your reason for using static?
Static variables are generally bad because you are forced to manually manage their entire lifecycle
If you return to the main menu in your game, you have to remember to reset your static variables, for erxample
Make sure you understand the difference between static fields and static classes
why would you use statics in a save/load system. one they are allocated they are there for the life of the domain so why have a Load system which exists for the entire runtime?
Generally serializer entry points are static
the class needs no reference other than its helper functions, can be accessed by other classes in my codebases core namespace and persist across the entire runtime of the application and will only ever exist once.
THe design of my game calls for a single scene with no reloading. Data is loaded and objects are created/discarded rather than scenes
such as JsonUtility.ToJson
which class
is there any way to have a render texture that renders a cameras view but only with 1 material? i want to have a hologram of the map with everything having a hologram material (urp)
When the player makes changes to the scene, the scene is serialized so that changes are auto saved instantly
tbh both the handler and serializer exist this way
https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@10.1/manual/urp-renderer-feature.html
Can set an override material in the extra pass(es)
There's no bootstrap scene? No menu scene?
but how do i not change every material and just the view through one specific camera
With what I just showed you
you're overthinking this... if the serializer just converts from/to serialized and doesn't have data - it can be static 🤷♂️ worst case, you'll need to adjust later on - that's part of life, accpet it 😄

nope. Everything is loaded dynamically in a single scene using prefabs and gameStates
The camera has a field in the inspector for picking a renderer https://docs.unity3d.com/6000.0/Documentation/Manual/urp/camera-component-reference.html#Rendering
then it doesn't matter much either way
but if you ever add another scene you'll have some refactoring to do
The only thing you're gaining really is not having to add a singleton to the scene
If it's totally stateless, just use a static class, sure
gotcha thanks. I guess i did overthink it. Most of my projects are procedurally/dynamically loaded so i have fallen into a single scene design
Anyone familiar with the Item Services portion of Steamworks? Currently working on items, have the json def file setup, have code to GenerateItems for developer accounts but cannot for the life of me get the TriggerItemDrop function to return anything other than a zero item success even though I'm using the correct playtimegenerator item and bundles. Doesn't seem to be any info out there.
Respected Seniors, I have some confusion about the Google Play Services in the Unity game.
Please guide me when it will be easily possible for you.
1- Does authentication to Google Play Services occur only once per session, or does it persist throughout the game until the user removes the game from the background or quits the game?
2- For read/write operations (e.g., saving data to Google Play Games), is one-time initialization sufficient until the user removes the game from the background or quits the game?
3- If the user's internet is off, can data be saved locally and synced later automatically? Does Google Play Services handle this process on its own?
4- When enabling Google Play Services in the game, will users receive a notification about it on their device to successfully connect to Play Services, or is there any other way they are informed?
5- If I want to integrate Google Play Services, is a Google Developer Console account sufficient, or do I also need an account on Unity or any other platform? Could you kindly clarify this process for me?
6- Or any important tip for me to implement it.
Thank you
does the profiler by default only show Unity's methods like Camera.Render and Transform.SetParent, instead of the game's methods?
https://discussions.unity.com/t/character-flies-up-in-air/1566122
please help me here im a beginner
Oops! That page doesn’t exist or is private.
@somber swift how do i make sure its public?
i have a parkour game but my character keeps flying into the celing
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class PlayerController : MonoBehaviour
{
public float moveSpeed = 5f; // Speed of player movement
public float jumpForce = 5f; // Force applied when jumping
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
rb.useGravity = true; // Ensure Unity's gravity is applied
}
void Update()
{
Move();
if (Input.GetKeyDown(KeyCode.Space) && IsGrounded())
{
Jump();
}
}
void Move()
{
float moveX = Input.GetAxis("Horizontal");
float moveZ = Input.GetAxis("Vertical");
Vector3 moveDirection = new Vector3(moveX, 0, moveZ).normalized;
Vector3 moveVelocity = moveDirection * moveSpeed;
rb.linearVelocity = new Vector3(moveVelocity.x, rb.linearVelocity.y, moveVelocity.z);
}
void Jump()
{
rb.linearVelocity = new Vector3(rb.linearVelocity.x, jumpForce, rb.linearVelocity.z);
}
bool IsGrounded()
{
// Check for grounding to prevent floating or upward dragging
return Physics.Raycast(transform.position, Vector3.down, 1.1f);
}
void FixedUpdate()
{
// Extra safeguard to force Rigidbody's velocity in case of erratic behavior
if (rb.linearVelocity.y > 0 && !Input.GetKey(KeyCode.Space))
{
rb.linearVelocity = new Vector3(rb.linearVelocity.x, 0, rb.linearVelocity.z);
}
}
}
Keep it in #💻┃code-beginner
srry
if I run my game on meta quest 3, the process has 14gb virtual memory. Does that mean that my game can use 14gb of memory before it crashes?
that means it's using 14gb of memory now
but part of it may have been written to disk and offloaded from RAM
virtual memory is basically when the OS writes part of the memory of the program to your SSD or HDD instead of leaving it in RAM to save on RAM, at the cost of having to read/write it to and from disk at some point.
like this output from top command:
Tasks: 1 total, 0 running, 1 sleeping, 0 stopped, 0 zombie
Mem: 7944432K total, 7679704K used, 264728K free, 1784K buffers
Swap: 4718584K total, 748108K used, 3970476K free, 869144K cached
600%cpu 5%user 1%nice 6%sys 585%idle 0%iow 2%irq 0%sirq 0%host
PID USER PR NI VIRT RES SHR S[%CPU] %MEM TIME+ ARGS
14018 u0_a81 20 0 16G 3.8G 185M S 1.0 50.2 2:37.51 com.Icosa.OpenBrushPR795
VIRT is 16G
yeah I know virtual memory is ram + disk combined and the process doesn't have to care where the memory comes from
but in the above, is 16G the max virtual memory we can use or what we're using right now?
RES is the resident memory aka how much RAM it's using right now
but the process thinks it's using 16GB
and has 16GB worth of addressable data in memory according to itself
some 12GB have been swapped onto disk
16gb is the amount of virtual memory it's using right now
ok thanksfor the clarification
when you get memory errors like "out of memory", is that mainly done by the OS or the unity engine? I guess the OS will kill the process if there's no memory anymore, but does the Unity engine also try to prevent the player from asking too much memory?
It throws an exception whenever you attempt to allocate more memory. Sometimes you have a OutOfMemory exception other times you have not so clear exception. It depends on the console you use.
I have hit memory issue, multiple time on diverse Console (never PC though)
I am looking to optimize my car physics, but am not really sure how to proceed. Does anybody have any suggestions? https://paste.ofcode.org/BBC8zjhZyr7P4fAEwacazh
(I am also using it to train an AI to drive with ML-Agents. That is what a lot of the original functions are.)
Did you use the profiler yet? Definitely start there
Does anyone know how to make only the tiles from a tileset turn transparent when the player is behind them? I want to ensure that only the specific walls obstructing the player's view become transparent, not the entire tileset.
if I await something in Unity, is it handled by the UnitySynchronizationContext? ie it'll put the task on the queue and periodically run it
and Coroutines aren't handled by UnitySynchronizationContext?
await doesn't cause anything to periodically run. await tells the current code to pause until the thing being awaited is done.
Doesn't await make execution return back to the caller (Main), and the LongTask() is run periodically?
public static async void Main2() {
await LongTask();
}
public static async void Main() {
Console.WriteLine("hi");
Main2();
Console.WriteLine("hello");
}
im wondering if UnitySynchronizationContext will make sure that LongTask() gets executed periodically
Not at all.
well...
okay, you didn't await Main2()
tbh I'd just try it and see. I have a bit of a weak grasp on the intricacies here
sry i forgot the await
In that case, Main() would park itself there until Main2() completed
sry nvm
there wasn't supposed to be await
yeah so Main() starts, then Main2() starts, and the await in Main2() will make execution return to Main()?
My understanding is that running an async method without awaiting it means that the method executes until it hits an await
at which point control returns to the caller
yea i've done everything i could think of I was just wondeering if there were some other, more advanced methods that i didnt know of
Well, what did the profiler reveal?
i dont really know how to use it that well actually. idk why i said i had used it. i tried looking up how to use it, I asked chatgpt, and nothing really helped.
Start by looking at the manual.
If you have trouble interpreting the data, share a screenshot of the profiler with a frame selected and the profiler in hierarchy mode sorted by CPU time.
ive looked at the profiler before and it just told me basically that v-sync was causing most lag, then my scripts, and i dont know how that information is useful to optimizing my script
Share a screenshot of the data that made you come to that conclusion
If it's really vsync, then you could try disabling vsync. Optimizing your script is not gonna help at this point.
yea i disabled v-sync
alright give me a few minutes
how do i sort by cpu time
There's a column saying Time
This is not the hierarchy mode.
But what I can see from here, it is indeed vsync. You should try profiling a build and seeing if your GPU forces a vsync on the app.
Also, 4.6ms is really fast anyways.
i did a build and run that's what it's from
Seeing as i'm using it for machine learning i was just hoping to get it as fast as possible. I already 2.5x'ed the fps but I was hoping to get it faster if it's possible.
Then what I mentioned about vsync. Some hardware would hard for e vsync on. Check your GPU control panel. When that's fixed, we can look at the profiling data again.
Or, if you don't need graphics/visuals at all, you could build it as a server build and disable rendering
If you're trying to generate data for an ML system, why are you rendering anything at all?
I am pretty new to machine learning and the visual input helps me to fix any issues that are slowing down / stopping training since I am having some trouble with the ai just randomly undoing a bunch of progress.
i disabled v-sync in the nvidia control panel and it looks like this (found hierarchy mode)
Expand the top item in the hierarchy
^ sorry i took ages to respond
The 0.8ms is basically waiting for the GPU. It could be due to vsync still or simply the GPU rendering stuff.
There's probably not much you can do here without disabling rendering.
You could have several environments. One for debugging with actual rendering and one without for the training runs. It's not like you're gonna see all the stuff rendered during the training runs anyway. If you were to record it all, it's probably gonna be gigabytes and hours of video.
If you really need some debugging data, you could record crucial data, like positions, rotations and such and save them to a file in organized way. Then you could reconstruct what happened in each run from that data.
alright thanks for the help
im trying to figure out circular audio buffers (trying to make voice chat)
where im struggling is figuring out where (in my clip) to write the audio data to (because if there was no data recently then we should write to the current point in the playback, and if there is data we should write onto the end of it)
here's what i have currently, any thoughts or suggestions are appreciated
public void OnNetworkDataReceived(object o) { //called when network data is received (should be every ~0.5s)
if (o is NetVoiceData) {
NetVoiceData voiceData = (NetVoiceData)o;
//should only happen once
if(voiceData.sampleRate != playbackSampleRate) { RegeneratePlaybackClip(voiceData.sampleRate); }
float[] receivedData = voiceData.audioData;
//setup the write index
int samplesToWrite = receivedData.Length;
int currentSampleIDx = voicePlayback.timeSamples;
int writeIdx = currentSampleIDx;
if(Time.time < safeHeadWriteTime) {
writeIdx = lastPlaybackSampleIDx;
}else{
writeIdx += voiceData.sampleRate; //add a small buffer of 1 second
safeHeadWriteTime = Time.time + 1f;
//clear the buffer (it is a 5s buffer)
float[] clearData = new float[voiceData.sampleRate * 5];
playbackClip.SetData(clearData, 0);
}
playbackClip.SetData(receivedData, writeIdx);
lastPlaybackSampleIDx += samplesToWrite;
if (lastPlaybackSampleIDx >= playbackClip.samples) {
lastPlaybackSampleIDx -= playbackClip.samples;
}
Debug.Log($"Received {samplesToWrite} samples, writing to {writeIdx}");
safeHeadWriteTime += 0.5f;
}
}
How would I check if something is grounded no matter what surface its on?
would raycasts work? you might need to give more info about what you are doing
What do you mean by surface? As in "metal" or "wood" surface or just its angle?
Regardless, for detecting flat surfaces and angled ones the best approach is to use raycasts. Have a minimum ray size for flat surfaces and consider longer sizes for increasing angles (this avoids having the characters "hovering" on otherwise flat surfaces or soft angles.
If you are using collision layers for "surfaces" such as metal, wood and etc I strongly recommend you consolidate them all to a single layer and instead use monobehaviours to define surfaces
Like if you need a metal surface, you just attach a surface script or scriptable object, select it to be metal and you are done
How to make inputs transparent to the character? What I mean is that so I can control it with physical devices, AI controller, network controller, etc?
Right now I have in my Character component:
public InputActionReference Move;
public InputActionReference Action1;
Then in my code I read the Move and subscribe to Action1:
Vector2 CharacterVelocity = CharacterComponent.Move.action.ReadValue<Vector2>();
CharacterComponent.Action1.action.started += Action1_started;
And do things based on those action inputs. This is supposed to be decoupled from the player inputs, but how to control this from code?
I am thinking of making a clone of the built-in InputAction class with the same interface of what I'm using:
ReadValue function and the started event, and then create a CharacterInput component.
And then set those actions from a physical device or an AI controller.
So the character can be controlled using the same interface
I thought this InputActionReference and InputAction were the classes that are supposed to separate the actions that can be performed from physical inputs by the player.
The typical approach is make something like an "InputPacket":
struct InputPacket {
bool pressedJump;
bool pressedInteract;
Vector2 movementInput;
}```
Then you have your input processing code create these and feed them to your movement code:
```cs
void Update() {
InputPacket ip;
if (playerControlled) {
ip = new();
ip.pressedJump = jumpActionReference.action.WasPressedThisFrame();
ip.movementInput = moveActionReference.action.ReadValue<Vector2>();
}
else {
ip = AiGenerateInput();
}
Move(ip);
}```
Then you can have your AI code or network controller simply create an InputPacket each frame
The InputPacket struct can also be used for e.g. client prediction in a networking setup where you move your character locally with the InputPacket and also send it to the server in an RPC. The server then uses it to process inputs on the server side and you do rollback/reconciliation when the results don't match up.
Thank you
#1202574086115557446 to discuss the behavior package
It's about all of the AI tools, including the behavior package (which also happened to previously be called Muse Behavior)
a question, is using Time.deltaTime this much gonna cause lag
Probably not. But you still should cache it in a local variable.
It looks like you have a lot of repeated calculations there
For all performance concerns, you should use the profiler to check if it's a problem.
There's no way to know if something is a problem based on an isolated code snippet like that
alright
Things that are not a problem when called once per frame suddenly become a problem when you call them 10000 times in a frame
no i was just wondering if using multiple timers causes lag
since it's every frame
What you are doing here is not "using multiple timers"
but that's also not a meaningful statement in terms of performance
Performance has to do with how many operations you are doing, and how much GC you are allocating.
"using a lot of timers" is a totally different abstraction
usually you will run into performance issues when there are loops or recursion involved, not just by having many manually written lines of code (assuming each line is itself not expensive)
adding a value to a variable every frame counts as an operation, no?
yes but one operation per frame is a tiny, tiny thing
If you had 1,000,000 objects each doing one operation, that's when you have an issue
most of the timers are in if statements, so i don't think it's gonna lag as much
i just wanted to make sure
You're just wildly speciulating. Run your game and use the profiler, that's the only real way to know
I did, I'm running at a solid 60fps
Then there's no problem.
but i wanna optimize the game for low end computers
i'll have to run a virtual machine for that
Then run the game on your target hardware and use the profiler
Unity does so much stuff every single frame
Literally just use the profiler and see if you have any hotspot
Each operation is incredibly fast
"60 FPS" is not the same as using the profiler, in case you are not aware.
seems fine i guess
Looks like you have some spikes you might want to look at - but i would guess it's the typical editor overhead spikes
Doing it in a poorly written way will be slower than doing the same thing in a better way, but you also need to consider that you could be talking about a difference of 8 nanoseconds.
For the vast majority of cases, especially for a typical indie game, it being 8ns slower really doesn't matter whatsoever. An optimisation there would only be important if you happened to call that 8ns code 100000 times in a row.
Hell, even 800,000ns is still only 0.0008 seconds
Hello everyone, I have a question.
I want to divide a 2D top-down map into chunks. When a monster enters the area of a chunk, it should be added to that chunk's monster list.
The goal is to implement a tab-targeting feature like in MMORPGs, where the system only needs to scan monsters within chunks around the player.
The question is: how can I efficiently move monsters between chunks without consuming too many resources since positions need to be checked continuously?
Are there any documents or alternative approaches for this?
I'm trying to create a grid to allign my cards onto.
The grid takes in a prefab and generates a grid made out of those prefabs.
Problem at hand:
The grid is being generated at -1876.85 if the z value for the grid's vector3 is 0 and is moved according to the following function if the z variable of said vector is changed.
f(x) = x*20.854-1876.85
To get the desired z value of 0 I would have to input "89.9995204756881" which is not storable using a float.
That number does get close to the z value of 90 my canvas, which is set to "Screen-Space Camera", has.
Attached you find:
- Screenshots of the prefab
- Screenshots of my camera and canvas settings
- the scripts attached to those GameObjects
I'm open for anny suggestions and solutions,
kind regards, Emily.
I'm not sure I understand what the actual problem you're having is
It's also unclear why you care about the z position and aren't just making it 0.
You could also just be using GridLayoutGroup here.
I cant just make it 0 because it is created during the run time. The Script that's creating them is off-setting the z axys, which in the script should be 0.
Just use the z position of the parent object.
Again why not just use GridLayoutGroup anyway?
because I do not know what that is tbh "._. it also kinda fixed itself after i deactivated, reactivated and added it back to the canvas
it changed the offset to a fixed -90
instead of that weird function
Hey so quick question. If i load 2 scenes with async, and one scene is priority 1 and the other 0. Will the scene with priority 0 not load until scene 1 has been enabled?
Because from what i can tell this is the case. Scene 0 is at 0 progress until i enable the first scene and then both finish loading
what do you mean by "priority"?
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/AsyncOperation.html async operations can be assigned priority
this doesnt mention anything about the operation having to be 100% progress before it allows anything else to happen on any operations with lower priority
It's not super clear but my understanding is there is probably only one "scene loading" thread. I would try to verify experimentally
if i have multiple scenes load all at once with the same priority they all load async together, but it seems like if anything has higher priority it prevents any other scenes with lower priority to load completely until its enabled in the hierarchy. i.e 100% progress as progress will be at 0.9 when its done loaded and not enabled, and once its enabled then it will be 1.
i suppose it makes sense for it to function like this, its just annoying that it doesnt fully explain what it actually does as i wasnt expecting it to act like that. i was hoping it would prioritize the loading to finish it first, not to prevent other async operations
Howdy folks. So as best I can tell (from my own testing and reviewing bug reports from other users) Software Cursors are not supported by Unity's New Input System. I would greatly like to use a Software Cursor, because Auto/Hardware remove control of the cursor size from my control and push it back on the OS which breaks what I am using it for. Is there any other way perhaps to get the desired effect I want?
What do you mean by software cursors not being supported?
Also #🖱️┃input-system
Yeah I posted there last night but got no hits, so I'm trying a different tactic of how else could I do cursors. Since cursors and the input system seem like a tangentially related issue anyways.
I've been using SW cursors for over a year on Unity 2022.3 and have had relatively few issues. Upgrading to the New Input System however, it makes the cursor freeze in the first location it is rendered.
There seems to be many other people experiencing this as well, with no solutions other than to go back or use both systems.
i'll give this a try in my game
Seems fine for me. The cursor is visible and moving around after doing this duiring game startup
Cursor.SetCursor(cursorTex, Vector3.one, CursorMode.ForceSoftware);
(it's a very big texture oh no)
It works if I call it once. It does not work if called from Update.
Which I need, because the cursor changes based on what it is hovering over?
I'll try doing it in Update
I suspect each call to set cursor is resetting something. Also, what version of Unity are you on?
It may be this was eventually fixed and my version is too old or something.
hmm, still seems fine.
I'm running 6000.0.24f1 on macOS
It could be platform-dependent
It's more likely that ForceSoftware behaves differently on this platform
Notably, I can't tell if it's actually doing anything
Oh. Well, yes that may be true as wel.
The results are identical if I use Auto
Yeah I have a matrix of 50-something cursors in 3 sizes.
now this is a good cursor
You'd need to be resizing the cursor to see if its actually resizing it. But I doubt that would work since Auto generally forces it back on the OS.
Anyways, I did hunt and found other people having the same issue.
Thank you for testing with the setup you were able to.
@sly grove did you have any other thoughts on the matter?
This is a problem pink
not a code issue
As a stopgap "use both" systems, or see if you can hack something horrible together with https://docs.unity3d.com/Packages/com.unity.inputsystem@1.11/api/UnityEngine.InputSystem.Mouse.html#UnityEngine_InputSystem_Mouse_WarpCursorPosition_UnityEngine_Vector2_ 😬
hm, the behavior is changing when I use a different scale
on Auto, the cursor is not changing size, but it also disappears when it gets locked
It wasn't disappearing when locked when I used a size of Vector3.one
Performance issues limit my using both systems.
ForceSoftware doesn't disappear when locked in this case. But it's also not respecting the size either
note that I'm also setting the lock state immediately before calling SetCursor
i'll see if that matters
Warping also doesn't seem pertinent to what I need?
nm, I think I get it. Heh, worth I a shot I guess but damn what a hack if this is needed.
It's a replacement for the natural mouse movement lol
oh, i just realized that the vector3 argument is a position offset, not a size, haha
Oh, yeah the size is the size of the image.
The vector3 offsets the cursor "tip" point.
Its all really nice and works well until it doesn't
hm, it still doesn't do anything! It might just not work at all on macOS
not seeing any differences now (this might have been user error)
...ah, i was using a constant for the offset
I'm currently setting the cursor right after my game decides to switch the cursor lock mode. When using Auto, the cursor vanishes when it gets locked, but only if the offset gets changed from the value it had when I was using ForceSoftware.
Very weird.
Yeah I mean vanishing is the same thing. It basically gets moved offscreen and never comes back while the actual mouse and clicks and everything is processed normally. The two threads discussing it go through all the steps and thoughts I had pretty well.
for now I'll just keep using the legacy input system. I only made this leap as a result of pressure from members here haha...
Okay, so here's a really funny idea
what if you set the hotspot offset to a small random value every frame
Does the cursor show up?
I'll have to give that a try and see.
I know that I just had the cursor disappear when I did that, and it's in Auto mode...
but it's interesting that changing the offset has any effect at all
I have an array of XY points, here represented by spheres. This is a 2D cross-section of a radially symmetrical object. What would be the best way to turn a bunch of points defining a 2D shape into a 3D object?
If it's radially symmetrical then you probably have a center point. The easiest way to triangulate it would be to create a vertex there and trianguate to each of your points around the circle
if that's what you mean by 3d object
there are a whole heap of other ways to do it that might produce 'better' triangulations with more consistent surface area
This github lists a bunch of methods https://github.com/Habrador/Computational-geometry?tab=readme-ov-file#4-triangulation
Yeah, basically, just take the object about its center (you can see the origin selected there, the y axis goes right through it, it's centered at 0) and just like, radially extrude it into a mesh so it forms a sort of mushroom shape
Ah, if the center isn't inside the object then my first suggestion won't work, you'll have to try something more complicated
Searching "Radial Extrusion" isn't quite what I wanted but this sort of demonstrates it:
Like, spin the flat object 360 degrees about its center and make the resulting mesh
So you want to revolve these points and create an actual 3d shape with volume
Yeah, this is a cross-section of a 3D shape I've gotten from a bunch of math and I need to rebuild the 3D shape from that
Just spin it about the Y axis into a sort of deflated sphere
do you have these points in a sensible order already? Like, tracing the border of this object?
hey all,
I've been having issues with Unity's Transparency Sort Mode custom sort via y axis. I've tried using both Built in and URP. Neither do the job the transparency sort mode claims to.
doing everything right so far as I can tell:
- pivot sort axis
- same layer & sorting layer
- same order in layer
if anything it gets weirder bc the player was sorting with a background layer that wasnt anywhere CLOSE to being on the same layer. and it wasnt even happening on the y axis, it was on the x axis. this is resolved now by changing the material or something to default sprite or something haha but yeah, would love to have this sort function work visually
Yeah, the first point in the list is the top center, then it goes clockwise from there
I at least have that going for me
If so, then surely it's as simple as just revolving and creating triangles at the poles and quads everywhere else, bridging between two steps
is this a good chat channel for this?
It's not code related, so no
where should it go?
I'll paste it elsewhere and then put another issue im having here
Maybe #🔀┃art-asset-workflow, there's not really a perfect place. If it's for a 2D game then #🖼️┃2d-tools
So, get the array of points as A1, and then some offset. Rotate all the points about the Y axis by that offset into A2, then do quads with points of A1[i], A1[i+1], A2[i], A2[i+1]? With special handling for i==0 and i==A1.Count?
Yep
Now I just need to figure out how to do that rotation, which is almost certainly going to require quaternion multiplication so I'm going to have to just bash my face against the math until it's the right shape
If the vertices are already centered around y then it's just
vertexAtRot = Quaternion.Euler(0, rot, 0) * vertex
New Issue:
So im trying to create a dialogue system. this issue has 2 parts. happy to only focus on part 1 for now if thats ok.
-
the first page of dialogue is fine, but then DialogueBaseManager.finished = true and the next dialogueLine runs, and for some reason it seems to be called twice... as in, the text IEnumerator would say like "HHelloo wwoorrlldd". This continues for the rest of the dialogue lines, but not the first one.
-
Atm my dialogue system only allows for cycling through the children of one object DialogueManager. for a game with the potential for thousands of dialogue lines, this wont work. I'd need a totally separate system. Any ideas of how i might e.g. store dialogue info in a file and get that on certain triggers from a dialogueBaseManager? or idek just set different dialogues for different game objects, and have those change over time with different bools unlocked so to speak
i can paste code if that helps:
DialogueBaseClass:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
namespace DialogueSystem
{
public class DialogueBaseClass : MonoBehaviour
{
public bool finished { get; set; }
protected IEnumerator WriteText(string input, TMP_Text textHolder, Color textColour, TMP_FontAsset textFont, float textDelay, AudioClip sound)
{
textHolder.color = textColour;
textHolder.font = textFont;
for (int i = 0; i < input.Length; i++)
{
textHolder.text += input[i];
SoundManager.instance.PlaySound(sound);
yield return new WaitForSeconds(textDelay);
}
yield return new WaitUntil(() => Input.GetKeyDown("z"));
Debug.Log("Finished = true");
finished = true;
}
}
}
DialogueLine:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
namespace DialogueSystem
{
public class DialogueLine : DialogueBaseClass
{
private TMP_Text textHolder;
public DialogueManager dialogue;
//public bool hasStartedDialogue = false;
[SerializeField] private PlayerControl player;
[Header ("Text Options")]
[SerializeField] private string input;
[SerializeField] private Color textColour;
[SerializeField] private TMP_FontAsset textFont;
[Header("Time Parameters")]
[SerializeField] private float textDelay;
[Header("Sound")]
[SerializeField] private AudioClip sound;
private void OnEnable()
{
if (dialogue.dialogueIsOpen == true)
{
//StartCoroutine(DialogueRun());
DialogueRun();
}
else
{
ResetDialogue();
}
}
private void OnDisable()
{
ResetDialogue();
}
/*public IEnumerator DialogueRun()
{
for (int i = 0; i < transform.childCount; i++)
{
textHolder = GetComponent<TMP_Text>();
StartCoroutine(WriteText(input, textHolder, textColour, textFont, textDelay, sound));
yield return new WaitUntil(() => this.gameObject.GetComponent<DialogueBaseClass>().finished);
}
}*/
public void DialogueRun()
{
textHolder = GetComponent<TMP_Text>();
StartCoroutine(WriteText(input, textHolder, textColour, textFont, textDelay, sound));
}
public void ResetDialogue()
{
textHolder.text = "";
finished = false;
}
}
}
Kinda sounds like you're starting a coroutine twice. Maybe add some more logs or use breakpoints to confirm that.
I wouldn't say this is an advanced question, seeing how you barely done any debugging...
I would also mention that I don't know a good reason to not use one of the free and well tested dialogue tools like YarnSpinner or Ink
didnt knwo these existed! will check them out, thank you
public class DATABASE : MonoBehaviour
{
public Sprite[] savePortraits;
}
public class SAVEDATA : MonoBehaviour
{
//Updated by main menu to select which save indexing to read and write from save file
public int index;
// I.E. savePortrait = DATA.savePortrait[SAVE.file[SAVE.index].savePortrait];
public SaveFile[] file;
}
[Serializable]
public class SaveFile
{
public int savePortrait;
}
public class CALLEREXAMPLE : MonoBehaviour
{
[SerializeField] SAVEDATA SAVE;
[SerializeField] DATABASE DATA;
[SerializeField] Sprite sprite;
public void Start()
{
sprite = DATA.savePortraits[SAVE.file[SAVE.index].savePortrait];
}
}
is there any disadvantages to doing save files in this manner?
I don't see why the "database" or the "savedata" classes are monobehaviours
they're just bags of data
im not super experience din programming and this is easier for me to do atm. for DATABASE, it will also hold stuff like Prefabs and such
im wide open to feedback
hey, re this: unfortunately i dont think those are what im looking for. thank you for the suggestion though.
i think the best way would be to make it from scratch, even if it does take like years
I dont think this is advanced coding, but as we are here right now. It looks like you should do some basic unity tutorials about what monobehaviours and classes are. Right now, your whole save logic lives in runtime, as long as you dont really save it anywhere outside of the runtime scope.
its saved as json i jsut left it out.
i ended up talking somewhere else about this, but the reason i put it in advanced with that question is i wasnt aware if there was a disadvantage of havign a database script holding all prefabs, and other refferences in a single script being called by most other scripts
hi there, im looking for a way to access external webcam cameras on ios through unity on ios (ipad). i have no problem getting camera feed from the onboard cameras, but i dont seem to be able to access a usb camera. any help would be appreciated!
this may do what you need: https://github.com/gradientspace/geometry3Sharp/blob/master/mesh_generators/RevolveGenerator.cs
Yes there is.
Whenever you load your database, you would also need to load every prefab which means all the texture, meshes and audio clip. Those types of assets are heavy and will mostly not be needed in every situation. Instead, you should use weak reference to hold unto your prefab and only load them whenever you need them.
If you do not do this, you will mostly see a really long initial loading time with little to no room to manage memory. Obviously, if your project is simple, none of that will be apparent.
This is something I started realizing as I built a save/load system. Each inventory item referened the prefab it needed to spawn...which meant that all of my item assets would have to get loaded all at once
the next time I bump into that, I think I'm going to have a singleton that takes item definitions and gives you a game object (possibly loading assets in the process)
Use Addressable + AssetReference.
I usually utilize a "Definition" such as Item Definition which contains a weak reference to the actual items and/or image reference. Whenever I need the item, I load it from addressable through its asset reference.
Yeah, I was already halfway there with item definitions. They just had direct references.
Weak reference is a concept, not really a feature.
You can use a string to have a "weak reference".
Also, I believe you are speaking of something else entirely.
Which would be weak reference through code memory.
I initially thought of a literal WeakReference
Which is much closer to what you're describing here
That lets you store a reference that doesn't prevent a C# object from being garbage-collected.
Mm, yes, now I understand what this is.
https://dev.epicgames.com/documentation/en-us/unreal-engine/API/Runtime/Core/UObject/TWeakObjectPtr_1
i think unreal also has soft references which are something like an AssetReference?
i'm no unreal expert lol
What's the difference from you know, not dereferencing it completely?
You can still get at the object as long as it hasn't been cleaned up by the GC
sounds like a memleak waiting to happen
But the weak reference won't stop the GC from eating the object
It prevents a leak, in fact!
Ah, reading on them they sound like a neat way to just kinda clean up references but at the bottom of the page it's like:
Avoid using weak references as an automatic solution to memory management problems. Instead, develop an effective caching policy for handling your application's objects.
Something weird. If I have a rigidbody, and I want it to stick somewhere after hitting it with collider or trigger, I then change it to Kinematic for the physics to stop change it's position. Then I can specificaly set it's position in transform.position.
The strange thing is... if there is interpolation, it would end up in a different position.
I have to turn interpolation into None, before I can set it's sticking position.
Is this a known issue?
Yes, this is how interpolation works
The rigidbody sets the transform's position every frame, which clobbers whatever values you put in
When interpolation is off, this does not happen
Set the position property of the rigidbody.
You may be able to just set it and the transform position at the same time. That'll let you leave interpolation on.
this question might be impossible, but i wanna import my house into unity, like a model of my house (on a side note how can i get said model) (also on a related note how do i make a portal gun in vr) i wont see the responces until uh around 2pm on gmt-5.
How to import 3D models in Unity:
https://docs.unity3d.com/Manual/ImportingModelFiles.html
It doesn't matter if it's a donut, your house, or the mars rover.
on a side note how can i get said model
You would have to make it.
also before i go, can u recommend a guide on how i could go about making a portal gun
No I don't have one of those sitting around. Search on youtube or google
ok, thank you for this good advice, i will tommorow :)
There's an iphone app for this btw: https://www.youtube.com/watch?v=Wnuk58l4w9U
dunno it's it's any good
Otherwise you need the professionals: https://www.gp-radar.com/article/how-do-you-3d-laser-scan-a-building#:~:text=3D laser scanning delivers exact,design and project management applications.
I've got a issue on how to approach a problem. I'm making a card game roguelike. I've got the board and movement around the board set up(its a 2d arr). the problem comes down to when it moves, i want to call a script. I have a parent class, called minion, with this function
public class Minion : MonoBehaviour
{
public virtual void onMove(int dir, int row, int col)
{
Debug.Log("a");
}
}
then i have a child of the class, snake
public class SnakeMinion : Minion
{
public override void onMove(int dir, int row, int col)
{
Debug.Log("b");
//whatever the snake does
}
}
ive got both of these on the same object, and whenever this card moves, it calls onMove(minion script). i want it to call the snake card instead when it calls onMove. there will be more cards than the snake, so i cant just have a check on the minion script just looking for the snake class.
im not exaclty sure how classes work in c#, im more used to java classes. any help would be appreciated
does it not already do that? 
(in any case, this is not an advanced problem)
it should already do that by default, my best guess is that there is some sort of casting magic going on causing it to not work as intended
Well thats the thing, it does not do it
You might want to use addressables in that case. Any prefab just put in inspector is being loaded into memory otherwise as Simferoce mentioned.
What defines as an sdvanced problem? Sorry im unsure
If i call the minion script, it prints a, even if the snake script is attached to the same object, it does not print “b” instead
so you have the game object with BOTH the minion and snake scripts attached to it?
thats not even possible, you cant just call the base class method from outside if its overriden
well since you said you arent familiar with classes, something you learn very early in c#, it should be indicative that it isnt advanced. you should show more of your setup in #💻┃code-beginner.
you likely have a component of type Minion and are referencing that class rather than referencing an instance of SnakeMinion.
Fair enough, good point. However, i know im just referencing the minion class. Im asking if there is an easy way to organize this. If rather not have 50+ if statements to figure out which type of minion is attached.
you'd have to show or explain why you have so many different types that can even be referenced in the first place. With inheritance, you shouldnt need to have if statements to figure out what type it is just to do logic. the derived classes should provide the logic itself
it sounds really odd that you'd have a Minion and SnakeMinion on the same object, while specifically only wanting to get the snake minion
you only need the SnakeMinion component on your game object then
Minion minion = GetComponent<Minion>();
minion.onMove();
will find the attached component if it derives from Minion and execute the correct override method
your code does not need to know which Minion component is attached
thank you very much- that worked
ill ask these questions in the beginner or general from now on, thanks for the help
not to confuse the issue but using Interfaces are another common method to implement structures like this so you might want to look into those
I would like to inquire whether the ONNX file in the unity ML agent contains all types of learning or if it only retains the best results, Additionally, how can we filter it out if needed?
Hi everyone, I am working on some high performance required code in which I am trying to check if specific chunks in a procedurally generated game are within the render frustum, right now this is my current speeds.
This is my current testing order, (I have moved them around to make sure the speed is as fast as can be with the current code). I am going to be looking into quad-trees too but I was wondering if their are ways to speed these things up even more. For example, are their faster substitutes for bounds checks. (I am loosing 0.72ms just from copying a vector to the bounds.centre).
The hash set is also something I was hoping someone could potentially mention for a faster way of doing this, right now all I am doing is assigning chunks to this set when they are considered render able, however this is still unbelievably slow.
This is a bit more of a board question, as I am wondering if their is a way to access private fields (like the centre variable of the bounds) to change them directly without needing to create new strucks or objects and such.
This is something I would be using the Job system and Burst to optimize. I wouldn't be surprised if you could get 10-30x speed up with that, depending on how well you can parallelize the problem and how many cores your CPU has.
Ill look into jobs, good shout. Mainly just concerned with the amount of objects needing to be made, from my understanding of jobs you need to create an objects the pass it to the job system to be executed. Since slow down is happening on creating small structs like Vectors, I am worried that creating the jobs itself will also take up way more time then it could solve.
I was also wondering actually, are their any maths libraries that can be called through C#, to my understanding most of the maths stuff (though this may be wrong) is written nativly in C#, are their any super optimised ones written in C# or assembly in which I could call instead. (again this is a broader question for me potentially replacing alot more things down the line)
+1 for looking into job systems... also you can burst-compile specific methods, I hear, and call those and those would be performant...
unless you can do something smarter, that's just a lot of operations, and if you can do them in parallel and whatnot - it's gonna be order of magnitude better... otherwise if you share more code and whatnot we can perhaps optimize something, but it wouldn't be WOW
I can send the main function, I'm rewound it to before I made changes (though I will be going back to try the job system), is it fine to paste a block in chat or should I use a link? Like pastebin?
So to explain, the code is being used to queue up chunks for rendering, not to render them. I need to know if the chunks are already in the last frames render queue as I am uploading and disposing of data from the GPU only when it is no longer needed. So this is the actively observed chunks, which are then compared to the previous frames where it is split into 3 lists, common, new and old. (New gets uploaded to the GPU, old gets disposed of).
Does Unity not have a TestPlanesAABB test for planes jobs?
No, doesn't appear to have anything built-in. Here's an example of one:
https://discussions.unity.com/t/managed-version-of-geometryutility-testplanesaabb/666361/9
Ah brilliant, thank you. Just surprised me is all, I would have though the AABB collision detection would be a pretty contained function, given you are providing it with the planes and bounds to check.
not sure how ChunkCoordinate works, but perhaps the implementation can be better when it comes to hashcode and stuff
For best performance, you might not want it contained in its own method. You can make better use of SIMD if you split things up component wise. Take the min.x of 4 bounds, pack them into a float4 and then you can process 4 bounds for the cost of one (if you do the same for each component and operation).
For example:
Where the data comes in already packed for SIMD
From this talk:
https://www.youtube.com/watch?v=BpwvXkoFcp8
Burst will attempt to auto vectorize and make use of SIMD for you, even if you don't do it explicitly, but the slightest changes in how your code is structured can make that automatic process fail.
Thank you, I will have a look!
I'm not finished looking into things yet but I wanted to check with everyone about something, I did a quick test with things transitioned to jobs and its actually working out slower. The problem seems to be the reading and writing to native arrays being really heavy on compute time. I have tried to minimise this by caching the data I need on the job so I'm only calling getItem and setItem, when absolutly necisary, but this is still way to slow.
Reading further into the call stacks shows that a large portion of time is speant doing something called "AtomicSafetyHandle", given I know that the indeces arn't overlapping is their a way to turn this off on the NativeArrays?
i know interface might work better, but im much more experinced in inhertence, so ill stick to that. thanks again for the advice
I know that I've had to tell Unity that I promise to stay "in bounds" with parallel jobs. In that case, Unity was outright refusing to let me write, though
That involved the [NativeDisableContainerSafetyRestriction] attribute
It's been a hot minute and I'm not terribly experienced with the intricacies
Damn, so their isn't really a way to get passed this then with NativeArrays? Do jobs support different types of data then? I read online that ConccurentBags and such don't work with burst, but is their alternatives?
Alls good! I appreciate the help, I will give this a look into anyway. I'm pretty new to trying to get everything as optimised as this so just trying to get as much info as I can xD
Are you profiling an il2cpp build?
Turn off safety checks, usually the issue (on by default). Also looking at your previous code, seems brute force checking for x for y for z, surely you could try and figure out the edges and assume outside/inside. Also its useful to predict the size of buffers you need. If using a buffer/dictionary/hashset, give it a max possible or predicted size. Also as mentioned work with float4 amd the 'math' library. You can work with xyz(w) math in one formula. I love Tuples but can be hard for the compiler to optimise especially on Burst. Storing (int,int,int) is large for an index. Depending how many coords, you could use a byte4, but ideally you have a single index ie. Int that refers to a table that refers to a chunk with coord data (possibly)., therefore storing only whether chunk index should be in the queue. Could also go the entity route which is about separating objects and data.
Youre not particularly limited, but some things are limited by design or require [NativeDisable..] Underneath these things are pointers, figure out pointers and you will understand more about memory and speed 🙂
Safety checks are off during runtime, they are (IIRC) on by default in editor to help prevent errors, so those costs won't actually be there.
I cannot see your code to know what's going on, but if you have two copies of the data (one using regular managed C# array, one using native array) and you are treating the managed one as source of truth, while you are constantly copying to the native one, running the job, then copying the result back.
The ideal way is to just have the native array as the only source of truth and everything operates on it, so there's no back and forth moving data around.
Ah, yes I was doing this. I'm not sure why but I figured it wouldn't be feasible to use NativeArrays and such elsewhere and only use them specific for this job. Ill give what you suggested a go and see how things go :D
I will have a look at transfering from tuples, I was originally using them as keys in the hashmap representing the coords in world space, but as you said a byte4 would be better, thoug hI am unsure on if that would give me enough space. I may try and see if an int3 works too from Mathematics.
No this is all in the editor, the build works well, but since this is just a small part of a larger project I can't let this part hold up all the usuable GPU and CPU time.
i've worked on some editor code that needed to read/write native arrays a lot and the way i got around this was using NativeArrayUnsafeUtility.GetUnsafePtr and unsafe code, but of course that's a fun way to crash the editor if you get it wrong 😄
iirc you can more easily convert NativeArray/NativeSlice to C# Spans these days and off the top of my head using the copy methods on spans seemed faster too but i don't think i profiled it much
Hellou, I'm using jobs for a node system that includes many job scheduling. Right now i have a big array that jobs read and write to it in parallel in a nice ordered manner (no overlapping, no errors).
The problem with this system is that i need to precalculate the array size before starting and select the different places each job can write and readfrom. It's not a big problem because it's what i have.
But I wanted to improve readibility and instead of one big array have many small ones that get passed around as pointers. That way each node can create it's arrays, add or write and pass the pointer down the line for others to read.
Is there any major performance impact in a change like this? Or anything that I should know before that can help me judge if it's worth it or not before doing all the changes it requires?
this removes all performance benefit you would gain from data locality and you would probably loose most benefits of the parallelization too. you have to figure out how to implement your updates incrementally in as few batches as possible, otherwise jobs are not helping you.
By this you mean moving from one big array to pointers?
yes
so better the one big array
yes
alright, thanks!
but not a big array of big structs
nono, its a big array of floats
my idea of pointers was to get the pointers when scheduling the jobs only for the specific case where there are N arrays that have to be combined
also you should not jump around in the array
nope, always accessing 1 index at a time, but starting at diferent offsets
if you don't use jobs, and implement your parallelization with low level sync primitives, you can design a system that is fast without the constraints that jobs put on you
but that is extremely difficult
Yeah, the good thing with Jobs is that it's quite accessible to anyone and it's something I would like to keep
not in the sense that the code is difficult, just making it perform well requires a lot of insight
exactly
and it coaches you into the right approach that is fast and manageable
Is anyone good with Photon?
because im having a problem where ascript cannot acsess CustomProperties
scratch that when i set the custom properties it doesnt
for more info
please @ me or dm me for help cuz im going bed
i have all my animations ready but i need to script them to perform combos and stuff in my game but i tried all AI's and provided them with maximum information but they are still not working as expected i need help pls if someone can i have most of the code so if anyone can help me fix anything from it i will be glad i need it to work as quick as possible so please help me if u can
yea
Hi!
1- Doesn't sound like code-advance, probably better fit for #💻┃code-beginner
2- Can you say exactly which features are we talking about? and how deep do they go? For example healt bar ui can go from simply adding a texture that gets squishy to having to create a world canvas, the required scripts to update health, placement of those ui bars that follow or not the enemy, etc...
3- Depending of 2, 15 dollars seem way to low. If it's so simple that 15 dollars are enough, you can probably do it with ChatGPT and learn along the way, otherwise i don't think so
and please don't crosspost.
of course
I've encountered a strange problem with changing materials of an object in build. If it has a baked lightmap (being static is not required), everytime I change material in build it just changes to pink and makes the game very laggy when I look at it. I checked if there was something wrong with shader or material with Debug.Log(), but everything seems to be fine. Interestingly, it appears only in build, everything works fine in editor. So, does anyone know what is happening?
I wonder if the new material has a different shader that wasn't compiled with the lightmap keywords
both the original material and the new one are just the same with same shader (URP Lit) but different texture
it's possible that you wound up with a combination of shader keywords like
USES_FOO
USES_FOO LIGHTMAP
USES_BAR
But if materials literally only differ in albedo texture, then I wouldn't expect this
(I'd also expect unity to spend 5 hours compiling every single possible combination of keywords)
okay, I'll try to research about this, thanks for trying to help me!
Unity should also try to fall back to a shader variant that's "pretty close"
unless you turned on strict shader variant matching
nah, it is turned on 😦
or this is the issue?
I mean, materials are really the same, so there shouldn't be any shader variant differences
If it's turned on, any mismatch in keywords will cause an error shader
Importantly, if the second material is not used in a scene, it won't have gotten the lightmap keyword
at least, that'd be consistent with the problem
Turning off strict matching would prevent the error shader from appearing, but I'd expect the material to still be lightmapped wrongly
(or, well, it won't be lightmapped at all)
You can test this by sticking the material on something in your scene that gets lightmapped
Yeah, sure, I will be expirementing with this
So, yes, this is the issue, so I rewrote my code to change texture, not whole material, thank you for helping!
I'm creating a floating capsule type of movement system similar to half life and I'm having an issue where for some reason the Y position on the player's rigidbody is slowly reaching the target instead of instantly snapping to it. I've attached the code in the pastebin alongside a video to show the unwanted smooth effect (if you cant visually see it just look at the transform)
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Solution was to divide the distance between the target height and the player by fixeddeltatime
if i have an array in a job that is run on multiple threads, and I know that any given Execute() isn't going to write to the same indices as another Execute(), is that still going to be undefined behavior?
It should be fine theoretically
In most cases, if each thread is guaranteed to write to distinct, non-overlapping indices of an array, it should not result in undefined behavior. However, it's crucial to ensure that there are no concurrent write operations to the same indices, as this could cause data races and undefined behavior.
Here are a few key points to keep in mind:
No Concurrent Writes: Ensure that no two threads are writing to the same array index simultaneously.
Thread Synchronization: While not strictly necessary if there are no overlapping writes, you might still want to consider synchronization mechanisms to manage access to shared resources.
Array Bounds: Ensure all threads respect array bounds and do not access indices out of range.
If you ensure each thread is working on separate indices, and your array bounds are respected, you should be in good shape. It’s always good practice to review your concurrency logic and test thoroughly to catch any potential issues. 😊
Is that an ai generated reply?🤔
Do I sound like an to you, if so then I'll take that as an compliment.
It did sound like something chat gpt would generate. These are general advises in multithreading context, but they don't touch at all om the jobs nuances. Unity might be imposing extra restrictions in the jobs.
Cool game in you bio also (i just tested it)
Well thanks I guess?
And just because I gave more context then you dose not mean I used ai
being accused of an AI response isn't a compliment. It stands out because your key points are all worthless given the context of Unity jobs and the question, so it looks exactly like you regurgitated an AI response without knowing what you're talking about
So because I give more context you all assume I use ai
I don't understand your logic here
Simply trying to help never asked to be investigated
or falsely accused
I mean, it's fine. Even if it was an ai generated response. Was just curious.
Move on, don't turn this into a thing, thanks.
I'm sorry my glorious king
hey guys, I have a question. Let's say i have a server url and wanted to fetch data from a databasein my unity windows game. Is there a way that the player could know my API for fetching data? or could see my server URL?
Yes, it's trivially easy to find the URL. And no, you can't hide it
your computer needs to know the url/ip in order to actually make the request. and if your computer knows, then the user can know too
what would be the best practice to avoid player from cheating if thats the case, like there's a chance the player uses it to send (via rest API configuration that I had in a script) manipulative score?
cheating what exactly? there's no one-size-fits-all solution here
like lets say sending score to save via database
You can prevent people doing it casually by adding a checksum into the payload, that can still be manipulated but it would require decompling the game which most people wouldn't bother with. The only way to prevent it (almost) completely would be to have the server validate the entire playthrough
It's not an actual problem for most games. If someone cares enough to mess with the highscores you can take that as a good sign
makes sense, imma try the checksum method. But may I ask some opinions, what if i encrypt the score and then send it to server where it would be decrypted?
rather than just PUT a plain score to the server
the thing is, the score kinda important since its for buying things in the game
well it'd be subject to like, pattern recognition
you can never make it fully safe
It makes no difference. The game must include the encryption key for it to be able to encrypt the score
is the game multiplayer?
Hello! One quick question: I need to send a .txt file created by my Unity app to one folder in other PC via Local Network (there is no internet connection)
Whats the simplest way to do that?
nope, its single, but i want to save the game's data for each user in database
ah yes, I forgot about that
then i mean. what's the harm in a player getting an unfair advantage against the AI
send it over the network...?
if you're not sending it via the internet, then not having an internet connection doesn't really matter
if you have that local network you can use that to communicate between devices
@drifting solstice thanks! i want to do It from Unity, whats the library I need to use?
Or just copy it / save it to a folder?
any ftp or http solution would work
okay thanks guys
@drifting solstice ok So I need just to find FTP tutorial for Unity to send the file isn't it?
sure
Thanks a lot!
Hello! Could you please help me with serialization in editor?
I have interface IScoreView and two different views - TMPScoreView and DefaultTextScoreView implementing it.
I have class ScoreManager that is monobehaviour. I want to assign those two views on my ScoreManager, but I want ScoreManager to work with Interface and not implementation.
Unity [SerializeField] or [SerializeReference] not working (one not showing in editor, another giving errors) for IScoreView, only with TMPScoreView or DefaultTextScoreView .
I've tried with Odin, but not sure how to properly do it with it (can't find it in docs). Could you help me with it?
Backend Score Validation
there is no reliable way to reference interfaces in the editor, you can find some serializers on github that promise to do it, in practice it breaks down very easily under refactoring/git-use/prefabs. You can also try OdinSerializer which is at least a well supported solution for many serialization issues that come up with unity. Generally its best to not get fancy with serialization in unity. Its decision to keep it simple is more helpful than inconvenient in practice.
i was trying to make a module for character controller. Used MVP pattern. Ended up with this (see picture). I don't like the long chain of events invokation (lines) from input reader to presenter to model to spell caster. Can someone help me loose the coupling?
All starts when player gives input and then the logic goes according to diagram
You can expose your spellcaster as public as one of options and subscribe this way.
not sure it's best approach though.
I hope it's not in any way inappropriate mentioning my own packages... but I have one that includes a tool for selecting what implementation to use when doing SerializedReference + interface / abstract class: https://github.com/pulni4kiya/unity-editor-tools
What you'd do is [SerializedReference, TypePicker] private IMyInterface field; and it just works.
You could indeed mess it up a bit if you start renaming serialized classes and whatnot (solutions for some of it exist), but still, I'd say it's well worth the freedom that you get. I use it in all my projects, and we also use it at work all the time. 🤷♂️
Im creating a Texture2DArray in a scene, without saving it to the disk, but it's a private field. However, when I save the scene this one gets saved with it. It shouldn't be because it's regenerated so i don't understand why its being saved?
And if it will be saved no matter what, is there any way to detect a save event to destroy it?
There is the ISerialization interface callbacks you could use but if, as you say, it should not be serialized in the first place, perhaps you should look into that first
Does the private field have SerializeField on it?
Nope
Are you just running the game again without a domain reload and without reloading the scene or something
Just to be clear, im creating the texture2d array in editor mode
sure, and the domain reload question is still relevant
okay, then no, im never running the game.
so what are you doing?
Loading a different scene?
Restarting Unity?
the field is basically going to be retained until a domain reload happens
But when I press on my keyboard ctrl+s at least with other private fields, they never get saved
Again what do you mean by "saved"?
Can you answer the clarifying questions?
I just don't understand exactly what you mean by some XD. but I can explain the last one. By saved i mean that I right click on my .unity scene object and check the contents on it. And i see my Texture2DArrays there
Im trying to build a small script that can replicate it. Managed to do it for meshes, but it might help me understand why is being saved. By default Texture2darray doesn't seem to be saved
Solved
I can use this event to delete unnecesary data before a scene is saved
https://docs.unity3d.com/2019.4/Documentation/ScriptReference/SceneManagement.EditorSceneManager-sceneSaving.html
For large dialogue/story systems is it smart to use coroutines for a bunch of callbacks? I have a node system at the moment and some nodes have options to ensure they are completed before continuing.
I feel that it's unlikely to be a problem, but can't say for sure. On an unrelated note, can you send a screenshot of the node system? Just curious how it looks, I was improvising a dialogue system myself recently.
i wouldnt bother mine aint exactly decent yet
im hoping to migrate to Unity 6 due to it having an actual node system in the behavior package
because the old unity node graph system has been "experimental" for years now and it really shows
(i tried to employ a save/revert setup with scriptable objects and i ended up reverting it after months of trying)
You should try out Ink.
if its strictly dialogue it wont be useful for me
What else would you need it for?
i use the same node system to script the general sequence of things
you could use async/await (potentially via UniTask) and save yourself from dealing with a cumbersome construct (raw coroutines) that does not understand what "sync" means
yeah i essentially use Unitask right now for a bunch of it
i have to make sure everything works together though
ink, btw, has a very coroutine-ish execution model.
and stops when i need it to
i thought of potentially having a main task
for everything to branch off of
its really not complicated, and depending on your other tooling, you can reinvent ink, in a way more suitable to your use case, yourself. Ink has an editor however that can simulate dialogue flow, this is something that can be very helpful
yeah its a complicated system especially as we are working with videos
unavoidably
(1080p frame by frame animations)
(As a side note, if you are already using async/await then you shouldn't mix it with coroutines. It's much better to use exclusively one or the other, rather than mixing the two)
if you have a commandline interface (like in a text adventure) you can do everything with coroutines with very little overhead and issues
Ink has c# bindings.
Regardless, if you are suggesting to have a coroutine constantly running just to see if a condition is met, that isn’t a smart idea. Just make it so a function is run whenever a condition is met, check all the other conditions, and trigger an event when all the conditions have passed.
it was less about that but rather having to handle a bunch
i have node processors for each node type
they handle the actual execution of the nodes
and are in charge of stalling if it needs to wait for something
You likely have messed up the styling properties.
ngl hardest part of this system is working with videos
(especially when crossplatform support will be needed for mobile at some point)
Stuff like your flex side, growth, margin, etc
Wdym?
because its using unitasks when a node that needs to wait is processed it tells it to delay
the dialogue system runs in its own task
Oh you’re using the old ui system?
how to design complicated inventory system and crafting system like Dayz ?
That's a very vague question. You design complicated systems by thinking a lot, planning it on paper, trying to implement and adjust on the go.
i tried but this way it is not possible to extend it for new items and weapons. if i have to add new item i again need to write code and adjust my all switch statements and if else blocks
What way?? I don't think you shared any code or implementation details.
no i am thing it right now like i have 100 items and each item has its uniq perpose and each item can intrect diffrentl with other item . so i have to use swithc stement to check where this item is intrect with other item and if i make a new entry i again need to adjuct my switch stement. is thr any bttr apporch to make such huge inventory system like dayz,rust
No. You don't have to use switch statements. You'd use polymorphism and composition patrern in this scenario usually. You should know that if you're asking in this channel.
yo
To add to this, you can also use async/await with Unity's Awaitable class now. works nicely and good perf
that is true, and probably recommended when dealing purely with async. UniTask has some convenience methods that offer lightweight Reactive-style primitives that can be very useful when dealing with dialogue. Iz also makes it very easy to convert between all these async patterns via UniTask which comes in very handy when using 3rd party libraties that use other APIs. So its worth considering.
Haven't looked into Unity's Awaitable, but UniTask also has stuffs like SwitchToThreadPool/SwitchToMainThread.
In the past, UniTask is a stable of doing async/await in Unity because it provides things like NextFrame/WaitUntil/etc, so it covers everything coroutine can do so you never need to mix the two. I assume Awaitable probably has most of these as well so the gap is probably pretty close.
Awaitable has these:
Oh nice
Kind of surprised it has BackgroundThreadAsync/MainThreadAsync but not WaitUntil.
doesn't support cancellation tokens (you cancel the awaitable) and its a pooled class, so beware of that
it don't think it really replaces UniTask in a meaningful way
suppose Awaitable is just a way to unify all these async handle objects that unity has
Well not having cancellation token support does seem less than ideal.
well, its pooled, so the token pattern would not work
idk why its a pooled class an not a struct like in UniTask
Yeah, well tasks being structs do have some issues, but the tradeoff is imo worth it.
You can use cancellation tokens in many of the calls, ive used all 3. Awaitable is a decent solution and its expandable. Seems to fall into the Unity approach of giving you just enough and letting you expand it if you want.
what could cause Unity Editor writing 20mb/s to disk during a domain reload?
cache/build files
Check the profiler
it's the scene file being super large: 1.2gb!
so it happens when I enter play mode because it writes a backup to Temp/Backupscenes
same happens when I just save the scene
is that really a large scene file? or can it be expected depending on the project?
that seems gigantic, is it an extremely complicated scene?
I saw you were working with meshes, are you saving mesh data into the scene perhaps?
In any case that is massive
I have an editor script that splits a mesh into multiple smaller meshes. It creates a new gameobject for each new mesh. The way it works right now is that the only difference between a new mesh and the original is mesh.triangles. Could the problem be that for the new mesh, we set newMesh.vertices = originalMesh.vertices? (even though it doesn't have all the vertices)
For example, I have a dragon mesh that has 60k vertices, and it's split to 150 smaller meshes using this GetMeshSubset() method:
public static Mesh GetMeshSubset(Mesh OriginalMesh, int[] Triangles) {
Mesh newMesh = new Mesh();
newMesh.name = OriginalMesh.name;
newMesh.vertices = OriginalMesh.vertices;
newMesh.triangles = Triangles;
newMesh.uv = OriginalMesh.uv;
newMesh.uv2 = OriginalMesh.uv2;
newMesh.uv3 = OriginalMesh.uv3;
newMesh.colors = OriginalMesh.colors;
newMesh.subMeshCount = OriginalMesh.subMeshCount;
newMesh.normals = OriginalMesh.normals;
return newMesh;
}
it shouldn't be the issue though because isn't newMesh.vertices just a reference to OriginalMesh.vertices? it's not going to make a copy of 60k vertices right
.vertices creates a copy array, so no, the new mesh doesnt share the vertices with the source mesh
Same with uvs, triangles, colors, normals etc.
In other words, all meshes have unique data, not shared data
Yeah -- all of the mesh data lives somewhere in Native Code Land
This is the case for quite a few unity objects
is it somehow possible to get the source code for the line renderer
i am really wondering how they handle the corners.
LineRenderer itself is closed source unfortunately
because i am using it for my city builder game and it works but i wanted to make my own procedurally generated road instead, i managed to get it working but the corners look ugly, that is why i asked.
Have you looked into the splines library? They have some useful stuff. https://docs.unity3d.com/Packages/com.unity.splines@2.7/api/UnityEngine.Splines.ExtrusionShapes.Road.html
i have not but i will do that rn, thanks
the spline library has a line-extruder component, have a look at that, it doesn't do corners well (at all) but its a template you can use for making any kind of shape extruder. Its capable of being really fast too. You can find resources for how to do various types of corners (rounded, bevel, miter) on the net.
Has anyone had any experience writing a custom node for a visual scripting ?
anyone able to help with figuring out how to get my current movement script to work with Sebastian Lagues Spherical Gravity implementation?
https://hatebin.com/bvpdpsbkkd
https://www.youtube.com/watch?v=TicipSVT-T8&t=192s
Hi there, welcome to this tutorial on creating a simple first person controller that will function on spherical planets.
Updated source code for Unity5: https://github.com/SebLague/Spherical-Gravity
Original source code: http://pastebin.com/YBbFGZzD
Download the world model package by @danielsound here: https://www.dropbox.com/s/ul53h1g3nb5b9e...
i tried to just make my moveDirection be
moveDirection = transform.forward * verticalInput + transform.right * horizontal input;
to make it work in the local space but it comepletely ignores my camera so sometimes my W key wont actually move me the way im currently looking in the local space
I also have a bit of a problem with how jumping works, it doesn't seem to detect if my player is grounded or not once it reaches a certain point on the side of the planet
Also my camera gets all messed up too as i dont think it rotates with it and is clamped currently so i cant infinitely look up and go in a circle
This is my player look script https://hatebin.com/scmvfqyqty
and this is my move camera script https://hatebin.com/qufvkhgmwj
This is also my current setup in the hierarchy for my player and camera objects
not sure if this helps too but i have a dashing script also on my player that handles some of the stuff with my player dashing which im pretty sure also uses the world direction to launch itself forward
Any help on how to get this working would be greatly appreciated!
what object is 'transform' referring to? the player?
i think so yea
here's another screenshot that shows more of the components on my player and what part its on
haven't looked at the scripts but does the player rotate (with camera)?
uhh i dont think so, i have all the freeze rotation constraints turned on
so i think it just moved in the direction of the world space that my camera was facing or something
you can still rotate the player even with the rigidbody constraints (in code). if you're using the player's transform.forward but don't rotate the player, then 'forward' will always be forward on the Z axis.
on a side note, your ground check's raycast is using Vector3.down. your screenshot show the player in a 'planet', which looks like a sphere. the raycast won't find any ground unless the player is on 'top' of the sphere.
is vector3.down the relative down from the rotation of the player or the worldspace down direction?
the rigidbody should be rotating with the planet gravity in the code i added from sebastian lagues guide
no, Vector3.down is a constant
oh alr
looks like there is a 'gravity body' script (from your screenshot). you'll need to get what 'down' is from that (i'm guessing)
i'm also guessing that gravity script turn off Rigidbody.useGravity or modifies Physics.gravity ... otherwise you'd fall off the planet.
ooh im not sure what that would be, theres also this gravityattractor script that is on the planet https://hatebin.com/pjehephzlq
Yea the gravitybody turns off usegravity and freezes rotations
and then in fixed update it calls the attract method from the gravityattractor script that is on the planet
I gotta get off for the night, but any chance u can help out again sometime tomorrow?
thanks for the help so far
any reason you chose to use that controller? a physics-based controller with custom gravity is advanced stuff. as an alternative, there's a free asset you can use: https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131
it's more of a framework than a plug-and-play solution - programming is required but there are lots of examples included. supports custom gravity (i.e. walk around planets) and moving platforms.
is this better than any Unity example ones these days, I wanted to get back to characters? Unity used to provide a ready character controller but example stuff seems to quickly become outdated now, it was dodgy on slopes anyway...
Their character controller samples are still up-to-date and work super well (and easy to drag-and-drop into your scene to quickly get going). But I will say this kinematic character controller that Sean mentioned is very nice.
Hi everyone, I've been looking into converting a large portion of my codebase to work with burst and jobs. My game is currently storing chunk data (a procedural grid) in within a Chunk class, however this means that for large actions where I am going to want process chunk logic I cannot use it with jobs (since its a class, unless i'm mistaken on this).
I've been trying to convert this class and its surrounding code to work as a struct. However this means that anytime I am trying to access it (from the dictionary where the chunks are stored) they are copied instead of modified. I can't seem to figure out a clean way of being able to pass in the Chunk data as a struct while also having the changes be kept only on the original object.
I have been looking into GCHandle and IntPtr to store a pointer reference to the chunks, though this seems like a terrible solution, and I'm not even sure this is going to work.
The only other though I had on this was to just pass in the values of the class version of Chunk independenly to the job, however this seems very convoluted to me, any suggestions on how I should be going about doing this kind of thing would be appreciated.
(Though if this is the intended way of using the Job System then I will go with this, I just want to check with people more experienced with optimisation code)
you have to discard the idea of having objects when you want to use jobs efficiently. Your architecture should revolve around small groups of values that change together, put these into structs, these small structs into lists, and iterate those list. Treat the output of these updates as input for subsequent updates. If you need to keep this stuff accessible via regular objects you can create Query/access functions that index into these optimized structures.
Would copying the data between the structs and the creation of new objects not cause additional slowdown?
objects are just not compatible with the optimization philosophy behind jobs
naturally you can use jobs just to implement a complex calculation and reduce the output to simple states that get copied into your objects, but copying the entire data (say all vertices of a mesh transformation) back and forth through the OO API is wasteful.
Also keep in mind when you shove things into a native container like NativeArray<T>, that container is a pointer, so if you have a struct containing a native array of 10,000 elements and you copy that struct, you are not copying all 10,000 elements, only the pointer.
Right, so if I understand you correctly then, with the Chunk class itself I should instead of looking for ways to pass the whole thing and then inside the job access the parts I need, I should instead just be sending in the data itself. For example within my chunk I have a native array of CellData, instead of passing in the chunk to access this, I just pass in the celldata array?
Or do you mean to create a temp struct (say ChunkJobData), that I copy the native array to (like you said it wont copy all data just the pointer)?
What is it that you are trying to prevent?
I feel like there might be some disconnect in our communication, or understanding with how things like structs and native containers work.
Sorry, my fault for this as I am multitasking atm with things though finished now so can properly ask, The main thing I am trying to do is convert the architecture of my game to flow better with the job system, right now in a general example of things I need to do this:
-> Generate Chunk Column (contains data on biome and surface height)
-> Generate Chunk (contains data on individual cells within the chunk)
-> Process Neighbour Chunks
-> Generate Cells with Chunk
-> Generate Cell Meshes
And a few other things, but this is the main jyst.
The architecture at the moment has all chunks exist in a dictionary, where they are accessed based on a int3 coordinate or int2 coordiante (for chunk and chunkColumn data respectively).
What I am trying to do now is convert most of the process described above into Unity Jobs with Burst. However given that the chunks are classes I cannot directly transfer them to the job for execution.
My question mainly comes down to, how should I go about passing in data like this to a job? Should I try and force the classes, like Chunk and ChunkColumn into structs; should I create a new temp struct, pass in a copy / references to the data in the chunk and then send that to the job, or should I pass in each property of the class seperatly.
Does that make more sense for what I'm trying to accomplish?
thanks alot
If the goal is performance, then you would want only one copy of the data, eg use structs and native containers for the entirety of your project. Otherwise if you have two copies where one is the source of truth, eg you have data in C# managed land, then whenever you need to process them in jobs you make a copy to pass to jobs then after the jobs are done, copy the results back, that would positively kill your performance.
How should the struct exist outside of the job system then? Given accessing structs in dictionaries creates a copy of the data, storing it in the managed part of the code becomes a bit of a mess.
Your struct can contain native containers, which are just pointers.
Ah right, so let the struct be copy-able but the data inside wont be, thank makes more sense
Thanks
Correct, native containers are like keys to a warehouse, the actual data is over in the warehouse and you are only copying the key around.
That alone should be performant enough, but large struct copying still has costs, which you can optimize with ref/in. However I would not recommend jumping straight to that unless you positively identified struct copying is a performance bottleneck and you understand the nuisances with passing by ref/in.
Ooh I’ll look into that, I got recommended to use that asset by someone a bit ago but was a bit hesitant before to try it cause it seemed pretty complex to try and code over a custom controller since I’m a bit of a beginner still
Are there any big things I won’t be able to achieve by not using a rigid body character?
if you want anything else besides a phyiscially pseudo-correct force simulation the force simulated approach (what you call rigidbody) will be exceedingly complicated and annyoing to handle. A kinematic controller starts with the assumption that you want fully custom physics and then adds in the expected features you want, like ground and obstacle collisions. But it also assumes that things like snappy jumping, flying, movable platforms, stairs, corners and platform edges are all handled by you exactly to your project's needs (and not based on what would be realistic). Usually these concepts are difficult to implement with force simulation.
Alr that sounds pretty good then, I’ve already had some pretty annoying problems with friction and slipperiness not feeling right in my rigidbody controller
Basically everything that a rigidbody character can do can be added to the kinematic character just by coding it from scratch without physics?
Like if I wanted to implement my own custom crouch/slide/dash/wall jump I would be able to?
Of course
unity have updated their first and third person controllers on the asset store but they're still quite basic. this asset is way better. uses an interface so you write your own controller but you can hook into everything. there are examples for a range of things (eg. swimming, crouching) to give you an idea of how it works.
I found the KCC to be pretty nice
Notably, I could swap out the motor as needed to switch locomotion modes
I enjoy the "visitor pattern", where third-party code calls your code
that asset will do some physics interactions (i.e. when the player hits a rigidbody object) but not the other way around. you would have to code that yourself. if you're doing a physics-based game then using a rigidbody-based controller (e.g. human fall flat) would make sense but it's quite difficult to do.
if this is still a bit too difficult for you, then maybe a more 'play-n-play' solution would be better - e.g. Game Creator 2. it breaks up the player controller into modules. each module is backed by an interface so you can write your own modules if you want. it is very 'visual coding' based though. you can write your own stuff for that too. it's not free but you can buy more of their modules to add onto it (e.g. quests, inventory) if needed, so you don't have to do it yourself. https://docs.gamecreator.io/gamecreator/
Documentation for the Game Creator tools
Hello, I'm trying to simulate a balance effect with the SpringJoint component as the Youtuber Dave shows in this video :
https://www.youtube.com/watch?v=HPjuTK91MA8&t=151s
What I'm trying to achieve is clearly visible at 3:32 of the video.
Although I followed this tutorial and used exactly the same values as in the YouTube video, I can't get a good balance effect. You can see in my video I've attached that, instead, I slow down a lot.
The video is short because otherwise I'd exceed the file size limit that can be uploaded to Discord, but if I continued to stay tied, you'd see that the character swing extremely slowly until he's below the SpringJoint attachment point represented by the blue cube.
I've tried changing the parameters joint.spring, joint.damper and jointG.massScale but it doesn't change anything.
Here is my code (temporary) :
StateMachine.cs : https://codefile.io/f/vEqUEoohSS
SwingingState.cs : https://codefile.io/f/Jrpa22yemn
Also attached is a screenshot of my SpringJoint configuration for the video shown (Ignore SwingSpeed, it's not used).
Can anyone help me please?
Thanks to anyone who took the time to read this!
ADVANCED SWINGING in 9 MINUTES - Unity Tutorial
In this tutorial I'm going to show you everything you need to know to code an advanced (omni-directional) swinging ability in Unity. I'll also show you how to combine this swinging ability with the grappling ability from last tutorial and how to implement proper aim prediction.
If this tutorial h...
Create collaborative code files online for your technical interviews, pair programming, teaching, etc.
My assumption is that your rigid bodies mass is larger than the values in the video. Physics has a lot of moving values so it may just be that some numbers are set wrong. I personally think it would just be better to write your own physics system if you want better game feel, as it is far easier to tweak. Unity’s default physics are good for simulations, but I wouldn’t use them if you wanted to make your own spider-man style game.
By the way, why did you encapsulate your variables if you made them public?
Hello, thank you for taking the time to reply. I changed the weight of the character but it didn't change anything.
Concerning the physics of a swing, I could indeed code it myself but besides having no idea how to code that, I would really like to understand why, although I reproduced what's in the video, it doesn't work
The code is a mess right now. I'll clean it up as soon as I finish this last step lmaoo 😂
It could be numerous issued that could have caused the weird behaviour. It is difficult to tell just by reading the code itself.
No problem! I totally understand it. At the moment, I don't have time to take a good look at it before 4 or 5 days, but I'll keep looking. Apart from the weight of the rigid body, do you have any other reasons in mind for what might be creating such behavior ? You or anyone else of course ?
It could be you setting velocity in your script somewhere
Thank you very much for the tip, I'll look into it
i got the kinematic character contoller asset working in my project now, but the only problem is the collision with rigidbodies seems a little off than what it showed in the demo video. For some reason if i jump into a cube or walk into a cube at a semi fast speed i just clip through the cube
on the KinematicCharacterMotor script, what is "Rigidbody Interaction Type" set to? try setting it to Simulated Dynamic
uh let me check one sec
its on kinematic currently lemme try simulated dynamic
thanks, that pretty much solved it, the clipping is fixed now only thing is there is still a small noticable gap between the player and objects that its pushing or being pushed by
that screenshot is from mid being pushed by a moving platform
Im also having this error get constantly printed out in the console while its running:
Rotation quaternions must be unit length.
UnityEngine.Rigidbody:set_rotation (UnityEngine.Quaternion)
KinematicCharacterController.KinematicCharacterSystem:PreSimulationInterpolationUpdate (single) (at Assets/KinematicCharacterController/Core/KinematicCharacterSystem.cs:176)
KinematicCharacterController.KinematicCharacterSystem:FixedUpdate () (at Assets/KinematicCharacterController/Core/KinematicCharacterSystem.cs:131)
is there a gap in in the demo scenes?
oh wait nvm thats just a problem with the planet rotation script
not that i could notice
lemme check again to make sure
which version of Unity r u using?
yea no i didnt notice anything
this is the vid and it shows it at 1:31 https://www.youtube.com/watch?v=SDgwexgeZb0
What is Kinematic Character Controller?
Kinematic Character Controller a relatively low-level character controller solution that is not tied to any specific game genre and is mad...
Unity 6
i just updated my project from unity 2022 with my old rigid body controller to unity 6 and everything imported well except for the ambient lighting, but i did have to hit a button to make changed to the scripts because of API changes
it also gave me a prompt to make changes to a script in the asset pack due to API changes
so i just hit to make changes to this script and all future ones it finds
the script changes are to change Rigidbody.velocity to Rigidbody.linearVelocity - that's all
oh alright cool
what's "Capsule Radius" set to?
0.5
what's the scale of the capsule gameobject? i.e. on the player
there's a yellow ring around the player capsule that's slightly bigger than it, not sure if that's what's doing it or not
i'm using it in a project now and i have a small gap as well. the yellow ring is showing the radius + 0.1
ooh
check the demo and see if the character model (capsule) scale is different. other than that all i can suggest is to copy what's in the demo scene and modify it one bit at a time to get what you want, making sure it works after each change
Hello again, I finally solved the issue ! It was because my rigid body had a drag of 2. I set it to 0 or 1 and now it works perfectly ! 😁
11 seconds hiccup shortly after play on assetdbv2 out of date asset processing. What causes that?
It's waiting for an amplify shader editor to finish background tasks(on other threads). Probably compiling shaders or something..? Could maybe have a look at what these threads are doing at this point(not sure if unity profiler shows threads started by third party libraries though).
It also seems to be partially triggered by profiling itself I think. Is that with deep profiling on?
You can see the EditorPerformanceTracker call in the middle of the stack.
Yes it's a deep profile. non deep shows a 2 seconds hiccup
I'm thinking HotReload is the cause
It's probably one of the triggers indeed. But it's not the direct cause of the freeze. The direct cause is what I said: waiting for the amplify plugin to finish doing something.
I'd guess it's either marking some assets(shaders?) as dirty every time or something like that.
ah ok the templatemanagerinit
Yeah. The real question is why does it need to run it every time.
ASE is old crummy code, I pinged the devs
It's either a bug/inefficiency in the plugin or simply by design.
hotreload used to have a major problem forgetting many small changes and they probably bruteforced it in the last release
Perhaps
Could be the inbuilt padding for collisions
I forget exactly what it’s called
But if you look in physics tab of projects settings you can change it
Default contact offset
Its 0.01 units by default which is definitely not unnoticeable
Especially if you have small colliders in your game it can be a big margin
Ooh ok I’ll check that out thx
Hi everyone, I was wondering. Does ParallelWriter not work with NativeHashSets? I keep getting mixed info online but I can't seem to replicate this on myside, only NativeLists seem to work with them (this is with Unity 6 with the 2.4.3 colletions package)
There is a separate NativeParallelHashSet class
Awesome! Thanks, I'll give it a go ^-^
Everything in Unity.Collections is afaik
I'm generating large meshes at runtime which are bigger than the vertex limit. Does anyone have a good blog or advice about how to split this properly into a submesh?
the 32-bit vertex limit, not the 16-bit vertex limit?
4 billion vertices would be a lot of vertices!
Ah I'm on 16.... but I feel for collision, I will probably want smaller colliders anyway
MeshCollider itself has a max of like 255 vertices anyway
well - for convex colliders
*triangles I believe
I forgot about that!
I wish you could tell it to just...idk, do its best
decimate the model some more
I would like to inquire whether the ONNX file in the unity ML agent contains all types of learning or if it only retains the best results, Additionally, how can we filter it out if needed?
You probably want to look into quadtree structures (or octrees for non planar meshes)
hello, is it possible to have a script automatically get added to any scene when playing ?
i.e don't have to manually add it to an existing gameobject
Yes, you can respond to a "scene loaded" event
Of course, you'll need to subscribe to that event first
And use this to sub on game start https://docs.unity3d.com/6000.0/Documentation/ScriptReference/RuntimeInitializeOnLoadMethodAttribute.html
You could use RuntimeInitializeOnLoadMethod to do that -- https://docs.unity3d.com/6000.0/Documentation/ScriptReference/RuntimeInitializeOnLoadMethodAttribute.html
jinx!
Snap
my entire game starts with
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
private static void OnLoad()
{
Instance.Initialize();
}
on my game controller singleton (which loads itself from Resources)
With BeforeSceneLoad is it called once or for every scene loaded?
so why do i need scenemanager if i can do RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)
Might be a handy replacement for the global singleton I have so I can just play at any scene instead of loading into the menu
this is my question too
Reading docs is hard
The load type just determines exactly when in the startup process the code is run
because it sounds like you want to add an object to every scene
so if you reload scene, it doesnt fire again?
No, because RuntimeInitializeOnLoadMethod is used to run a method as the game is starting
BeforeSceneLoad just means that the code executes right before Unity starts loading the first scene
what i want is something like c#'s main method()/program.cs class
just to initialize some things for the whole game
not sure whats the best way
okay, so that's what you wanted :p
then just use RuntimeInitializeOnLoadMethod
got it ty

I'm going to have multiple menu's in my game that all need to stop the character from looking around with mouse look and unhide the mouse cursor. This is going to be shared code between all of these UI's that needs references to a bunch of different objects, what's the best way to structure that?
A singleton is fine
I guess something has gone really really wrong if I have multiple UI controllers. Alright. I can do that.
Thanks @sly grove
Consider a "counter" if many menus can be open at once
Each menu increments the counter when opening and decrements it when closing
Just don't mess up 😉
That's a good idea. I haven't thought about what would happen if a player opened the escape menu ontop of something like the inventory.
“Stack” would be a more appropriate term
eh, you'd have a stack of menus if you had to close the menus in the reverse order that you opened them in
this doesn't imply a stack -- it's just "how many menus are open?"
It does make some sense to store a collection of objects that are locking mouse look/keeping the mouse visible though.
It makes it easier to keep track of which UI is keeping mouse rotation locked and is a little more resilient against accidentally calling the lock mouse method twice or something.
I agree that a stack isn't nescessairly the right choice though. I can't picture a case where you would open up a new menu and close the menu behind it before closing the new menu but I could imagine it happening.
oh yeah, a set is a decent idea
it also means that, when you mess up, you can figure out who's locking the damn screen!
It's more relevant if you have floating windows that you can move around and interact with simultaneously
My game has a strictly stack-based menu controller system (and only one menu controller is allowed to be active at a time)
I do have other UI elements that also need to unlock the cursor, but they're handled separately
you can do something like this (see code). The notion of a stack is irrelevant to releasing a resource, a stack is only useful if you want to pass control back in the same order as you handed it off, all you care about when it comes to things like cursor-unlock etc. is whether something blocks/claims it. A collection of claimants is irrelevant if you don't use it for anything besides counting them: https://nombin.dev/90d6951mljg0gpph4kswn9wr
A website to host temporary code snippets.
sheesh that makes me feel icky lol. why would you do this rather than say like, having a bootstrap scene that additively loads your landing scene post-initialization?
It's more convenient in the editor, since I don't have to start in a bootstrap scene
I don't see a huge conceptual difference between "there's a special scene that starts everything" and "there's a special prefab that starts everything"
It can't be turtles all the way down 😉
true. separation of responsibilities i suppose, you can get some parallelism a little more easily but i suppose you're right. maybe i'm just conditioned to play nice with unity lol
i don't tend to have centralized controllers so it's less of a necessity for me. the singletons I do have usually have static event registration so i just need a little prewarm so i don't get dry fires on script execution order
I'm trying to get a source generator working, but for some reason its failing to include the namespace it needs. The generated code looks like this:
using OwlTree; // namespace proxy factory is from
using System;
public class ProjectProxyFactory : ProxyFactory
{
...
}
I'm getting the error:
OwlTree.Generator\OwlTree.Generator.OwlTreeGenerator\ProjectProxyFactory.g.cs(1,7): error CS0246: The type or namespace name 'OwlTree' could not be found (are you missing a using directive or an assembly reference?)
The cs files that contain everything in the OwlTree namespace are in my Assets folder. It works just fine if I use it in a script myself.
This is what my generator dll looks like in the editor:
What could be causing this? I followed the steps explained here: https://docs.unity3d.com/2022.1/Documentation/Manual/roslyn-analyzers.html
are you using assembly definitions in your project? and if yes, is your generator dll within the same assembly definition path as the namespace definition?
I still haven't fixed this. I found some resources on how to properly set up the csproj for the generator. I was doing it wrong, so I fixed that, but that still didn't fix the errors. I can also see that the generator is working correctly in the language server in vscode. So it's only when unity compiles is it an issue.
I would like to format my codes before commiting
For example, it should format a class like below
First serialized field, then props, readonly fields, fields, abstract methods, unity event functions, etc.
Rider can do that
Yes but how should I define a hook for it?
It’s a checkbox somewhere. Format/cleanup on save or similar. There is a search feature in the settings menu
If you find the cleanup/layout settings you should find the option do automatically apply it too
I don’t think you can trigger it by a commit but you can run it on any folder recursively on other triggers, like save/pre-build.
hey guys, i don't know if this falls under advanced but there were other people asking questions in the other channels and i didn't wanna post over them, if it's a problem, tell me and i'll move the request.
I'm trying to setup a "gravity switching system" but i'm having some problems with switches from -y and +y axis to -x, +z and -z axis, while for some reason +x works fine.
The problem is that my player comes out rotated in wrong direction, the objective should be to keep the player facing always the same direction after the switch but as said for the 6 out of 24 cases i highlighted above this thing doesn't work.
I know it might sound confusing so i also have a video of the problem in case that's helpful, here's my code so far:
i should also mention that i use controller.move to move the player: