#archived-code-advanced
1 messages · Page 83 of 1
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(InputHandler))]
public class TopDownCharacterMover : MonoBehaviour
{
private InputHandler _input;
[SerializeField]
private bool RotateTowardMouse;
[SerializeField]
private float MovementSpeed;
[SerializeField]
private float RotationSpeed;
[SerializeField]
private float LookSpeed = 180f;
[SerializeField]
private Camera Camera;
private void Awake()
{
_input = GetComponent<InputHandler>();
}
// Update is called once per frame
void Update()
{
var targetVector = new Vector3(_input.InputVector.x, 0, _input.InputVector.y);
var movementVector = MoveTowardTarget(targetVector);
if (Input.GetKey(KeyCode.Mouse1))
{
RotateTowardMouse = true;
}
else
{
RotateTowardMouse = false;
}
if (!RotateTowardMouse)
{
RotateTowardMovementVector(movementVector);
}
else if (RotateTowardMouse)
{
RotateFromMouseVector();
}
}
private void RotateFromMouseVector()
{
Ray ray = Camera.ScreenPointToRay(_input.MousePosition);
if (Physics.Raycast(ray, out RaycastHit hitInfo, maxDistance: 300f))
{
var mouseTarget = hitInfo.point;
mouseTarget.y = transform.position.y;
//transform.LookAt(mouseTarget); //Using this works great, but I am trying to add a rotation speed/lerp so I tried Quaternion.RotateTowards below
//This rotates over time as expected, but as soon as I use horizontal/vertical WASD input it throws everything off...
var rot = Quaternion.LookRotation(transform.position + mouseTarget);
//rotate towards mouse hitpoint over time
transform.rotation = Quaternion.RotateTowards(transform.rotation, rot, LookSpeed * Time.deltaTime);
}
}
private Vector3 MoveTowardTarget(Vector3 targetVector)
{
var speed = MovementSpeed * Time.deltaTime;
targetVector = Quaternion.Euler(0, Camera.gameObject.transform.rotation.eulerAngles.y, 0) * targetVector;
var targetPosition = transform.position + targetVector * speed;
transform.position = targetPosition;
return targetVector;
}
private void RotateTowardMovementVector(Vector3 movementDirection)
{
if(movementDirection.magnitude == 0) { return; }
var rotation = Quaternion.LookRotation(movementDirection);
transform.rotation = Quaternion.RotateTowards(transform.rotation, rotation, RotationSpeed);
}
}
• I used transform.LookAt(mouseTarget); and this worked great, but I wanted to add a LookRotationSpeed.
• So I switched to using a Quaternion.RotateTowards method and it works... just as long as I dont press WASD to move.
• Once I press WASD the Quaternion.RotateTowards gets thrown off... and I can't figure out why.
While the bool RotateTowardMouse = false, I want the WASD to manage rotation. When it's true, I want the player to look at the mouse location. And I would like to be able to use WASD and MouseLookRotation at the same time, but when I let go of Mouse1 it switches back to WASD Rotation and vica versa.
Anybody notice what's causing the rotation to be off when pressing WASD?
#💻┃code-beginner for this kind of question
It took about an hour of back and forth with ChatGPT, it didn't solve it as simply as you would expect an AI to do it, but I finally resolved the issue. 🙂
Oh ok, Im sorry I figured this was more advanced coding...
it is not. If you are a beginner, stick to the beginner channel to get the best answers
Will do. My bad...
https://forum.unity.com/threads/d3d11-texture2d-blitting-framerate.562552/
Can someone with knowledge about rendering please help me with the last post in this thread.
I could not figure how to get m_SrcTexture.
CopyResource's first parameter takes SharpDX.Direct3D11.Resource.
But if I were to get the texture from game, it is going to be UnityEngine.Texture
i'm no expert on this at all but it looks like that code already contains an example of how to wrap the native pointer of a texture in a SharpDX texture?
i have a theoretical question for my multi scene tools package. ive talked to people who say i should be using cancellation tokens for async loading. but unity doesnt support that by default. so my question is:
Is cancellation tokens even usefull in async loading? should i bother finding a workaround and implement it?
Sure it's a good practice to cancel when e.g. the user cancels an operation or does an incompatible thing, but if the api you use doesn't support it then you don't have much of a choice
You can wait until that's done and then cancel
thing is, once an async loading operation is started with the SceneManager, it cant be cancelled. it must be loaded in or unloaded. if loaded then a loaded, but not enabled scene cant be removed without being enabled, and then unloaded (as far as i know). which is why im questioning if i should find a workaround. I know i can add cancellation tokens if i use UniTask, but i dont know if that enables me to remove half loaded scenes which is the main issue
if i have to wait until its done anyway then it kinda defeats the purpose of a cancellation token right?
Under what circumstances will a disabled monobehavior on a gameobject still run (without being enabled)?
It only affects the Unity methods (Start, Update etc.)
Awake is always called
Other code inside the MB will run normally if you call it
Also OnCollisionEnter runs on disabled MB
Collision events will be sent to disabled MonoBehaviours, to allow enabling Behaviours in response to collisions.
Ugh. So how DO you disable a script with OnCollisionEnter in it if you WANT to disable it?
Short of removing it?
if (!enabled) return; in OnCollisionEnter?
sorry if this is not the best channel to ask, i know how ot populate in my code a dropdown with values from some list, but how can ii save this dropdown in the editor to avoid filling this dropdown everytime?
Usually depends what you're trying to save. If it's data you're trying to save yourself from implementing every single time, you usually have some type of data container like a Scriptable Object.
I have a list inside an scriptable
And when I press play if my drop-down option are empty then it populates with the option’s inside the scriptable
But is not better to save after this the options inside the drop-down to avoid doing this every time I press play ? How can I do it ?
So the list should always contain the information of your scriptable object?
and that you've got it populating from Start() or some assignment method?
If that's the case, sounds like you shouldn't expose the list on the editor.
Why ?
if the list is serialized it will actually be saved. Maybe you should populate it in OnValidate() though ?
Anyway, let me explain better sorry for my English, I have an empty drop-down with 0 options, then I press play and is populated or filled with the content of one list saved in one scriptable gameobject
How can I avoid do that in every play and save the content of the scriptable in the drop-down in unity editor ?
oops sorry @regal lava I replied to the wrong person
Hey folks, I've got a project from china that uses this package, but my version of unity is using the European / US version of unity.
Is this package completely locked to chinese unity only or can the rest of us also access and download it somehow ?
(I recommend google translate)
https://docs.unity.cn/cn/Packages-cn/com.unity.autostreaming@0.1/manual/
ask your colleagues to copy and paste the autostreaming package from their Library/PackageCache folder to Packages/, then check it in
Thanks
Task.Yield is not the same as 1 frame in Unity, you'd need a custom wrapper on top of CustomYieldInstruction to be able to properly awaiting frames in Unity. Async/await in c# does not respect Unity's frame timing/gameloop at all thus they made the new Awaitable api.
Hi, I'm caching WaitForSeconds to avoid GC allocation, but thing is, I don't know the time delays in advance. They will be determined by gameplay.
Might be a matter of syntax, but I can't figure out how to set the time delay in my coroutines when referencing a cached WaitForSeconds.
Anyone know how to do this?
yield return myWaitForSeconds(5) - for example - throws an error "Method name expected"
you can't
not without reflection
we literally had this discussion in here earlier today
haha no way. well thanks
dang, i actually started with a timer but tried the waitforseconds method thinking it'd be easier. 20-30 minutes wasted!
well it's easier but not if you care about garbage collection 😉
right exactly
I also have the 'infinite coroutine' thing going on like the other poster, so I do care
which i realize may be a stupid thing to do in general, but i'm just trying to get my prototype done
If you simply wanna "get" a reference each frame, is there a significant performance diff between looking it up in a Dictionary vs. an Array?
My lookup "keys" are ints that increment linearly throughout gameplay. I just prefer dictionaries for convenience. I heard dictionaries are quite fast, but not sure in this case..
Dictionaries are fast but not as fast as arrays.
Whether that difference is significant depends on how many times you do it, your hardware, the hashcode and equals implementation of the key, the occurrence of hash collisions, etc.
Not usre if this is advanced or not. I'm trying to set a models material via the ModelImporter and so far My google fu and documentation is failing me. Anyone have any examples of this? Is it possible? https://docs.unity3d.com/2023.3/Documentation/Manual/FBXImporter-Materials.html
Thanks!
doesn't seem like a code question of any level
Are you saying you can't set this by script?
I wanted to know 2 things. I just can't seem to find much info online about this stuff and I don't know how it's done. So, I assume it's a more advanced question but not sure.
How do I edit multiple terrains in c# in Unity, without making a seam? Like, basically how the terrains behave through the editor when you use a brush. If you edit them it treats them as as 1.
I'm working on a City generator. That modifies the terrain so that buildings and roads can sit on the terrain without making it totally flat. I can edit them already and I can put them together but when I put them together sometimes it leaves a little hump.
Currently I depend on an Asset called GeNa Pro to do it and I can do it well with that. But I want to learn how on my own. Also, I know how to make the roads as single segments but I don't know how to put them together so it looks good. Basically it's just a bunch of straight lines for the roads and they are disconnected segments.
It does though. I don't know if they changed anything recently when they introduced the CustomYieldInstruction, but for a long time Task.Yield was the way to do async(on the main thread) in unity.
If you look at the task yield docs in C# docs, it yields to the synchronization context. And unity overrides it:
Unity overwrites the default SynchronizationContext with a custom UnitySynchronizationContext and runs all the tasks on the main thread in both Edit and Play modes. To utilize async tasks, you must manually create and handle your own threads with a TaskFactory, as well as use the default SynchronizationContext instead of the Unity version. To listen for enter and exit play mode events to stop the tasks manually, use EditorApplication.playModeStateChanged. However, if you take this approach, most of the Unity scripting APIs are not available to use because you are not using the UnitySynchronizationContext.
https://docs.unity3d.com/2019.4/Documentation/Manual/overview-of-dot-net-in-unity.html
I couldn't find anywhere explicitly saying that the unity synchronization context waits for the next frame and the source code seems to be interlinked with the C++ side, so it's not quite clear.
But I've been using Task.Yield in the same way as coroutines yield return for a very long time now and never noticed any difference.
think awaits are always next frame, even in cases where i know the work is already done like a addressable is preloaded it comes back in on the sync context the frame after
so would assume Task.yield is the same deal
though i find i only use tasks when waiting on a long operation and stick to coroutines when i want to do stuff over time or frames
Yeah, it's mainly a matter of preference I guess.
yeah we got pathfinding on its own threadpool and and a bunch of network io stuff like rest api calls that we await
and that is about it
private void OnAnimatorMove()
{
if (player.applyRootMotion)
{
Vector3 velocity = player.animator.deltaPosition;
player.characterController.Move(velocity);
player.transform.rotation *= player.animator.deltaRotation;
}
}
Anyone have a clue why this might be keeping my root motion animation in place
The bool does indeed return true correctly
Does the animation actually have root motion data?
It does
The OnAnimatorMove void isnt being called though, and the animator is not on a child
If i use update instead it works perfectly, which is what im really confused about
Nvm i figured it out
i did player.applyRootMotion instead of player.animator.applyRootMotion
Hello, I'm currently creating custom Timeline track. How do I rename this.... string text using code? I don't know what is that thing called.
I just realized I accidentally posted it in code-advanced.
Guys. I'm trying to convert an existing C void* pointer to a NativeArray using NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray, but I'm getting an exception from Unity.Collections.LowLevel.Unsafe.AtomicSafetyHandle.CheckReadAndThrow even when using an Invalid allocator. How am I supposed to do that?
https://forum.unity.com/threads/trying-to-create-readonly-array-with-atomicsafetyhandle.800976/
never used it before
Can't we disable the AtomicSafetyHandle for a specific NativeArray or even disable it entirely?
i think no (i use unsafe list so doesnt know much on native collections) since this is required for job system to lock the collections
Anyone know if there's an easy way to sign in through existing microsoft account details in unity?
In other words you just enter your email and password and it checks if the details match an account
why microsoft account out of curiosity?
Hi! I'm creating a procedural 3d world. I've alreay done most of the things and I'm looking for improving my biome systems. I currently have both perlin noise for plains and forests (and the sea), and I'm implementing voronoi noise to add more biomes. The world is infinitely procedural so voronoi is made with a grid, in which the point inside the box depends on the grid's coordinates (via a seed in the random number generator). I'm looking for ways to create: 1) biome size: how many close points in the voronoi grid are the same biome. The points should be spread in an "organic" way, not just squares inside the grid. 2) Frequency of the biomes. And blocking biomes of the same type to form close so they can't "merge" into a single huge one.
I think I'm looking at something similar to ore generation in terraira or in any 2d grid. Anyone has any tips on how to do that?
currently the map looks a bit like this (it's a texture map that uses the same generator engine as the in-game world). The world is created with perlin and the gray areas (rocky biome) are random points in the grid, with borders squared with the voronoi's technique (I still need to make borders "organic")
I was thinking about using perlin noise for voronoi generation too, but this would be a problem because ores can have an average size but can still be only one voronoi's box (minimum is 1) and two zones can still merge together creatinga big one. Also, I'd have to do perlin noise for every biome, using one above another, potentially overwriting previous biomes
I'd like to have something that can ideally have a minimum quantity of zones packed together (a minimum biome size) and a maximum one, without overlapping zones together with other biomes
Company already has a microsoft organization with existing emails so if possible i would like to sign in thorugh that rather than creating users for every individual and a whole other authentication method
All my analytics events go to the default "production" environment and refuse to send gameStart or custom events to my "betatesting" environment.
Hey, so i made a a* pathfinding algoritm using heap data structure, on simple paths it works well, but on complex ones, i have extra nodes, any hints on what i should change?
I found out that when getting the neighbors again they didn't had the prev cost and that was one cause, and that fixed it, but some points are wierd. In this image is the one from the older message
but i have no idea how to handle this point
you dont need some special logic to handle the vertex, just explore until reach the target
yes, but the path shouldn't be correct, is not the shortest 
wrong heuristic
it looks like "avoiding" some vertex when exploring, have you reset all setted vertex in previous search?
I suggest you dont draw the vertex, instead draw the edge (though successful search should not be ambiguous)
Your code is most likely wrong. What cost function you are using ?
this is how i do it:
const newMoveCost =
currentNode.gCost + this.getDistance(currentNode, neighbor);
if (newMoveCost < neighbor.gCost || !openSet.contains(neighbor)) {
neighbor.gCost = newMoveCost;
neighbor.hCost = this.getDistance(neighbor, targetNode);
neighbor.parent = currentNode;
if (!openSet.contains(neighbor)) {
openSet.add(neighbor);
} else {
openSet.updateItem(neighbor);
}
}
getDistance(first: Node, second: Node) {
const disX = Math.abs(first.x - second.x);
const disY = Math.abs(first.y - second.y);
if (disX > disY) {
return 14 * disY + 10 * (disX - disY);
}
return 14 * disX + 10 * (disY - disX);
}
Typescript?
Btw it use integer for faster computation but i wont suggest it, it may loss precision then produces wrong result
What is the getDistance... ?
Yeah, i know is not Unity 😅 , the positions are not floats, as i use grid position and than i have a diff method which gets the real position based on that
i sent it as the second snippet
Normaly, you use Manathan distance for grid base a*.
to get the distance from the current selected node towards the target
i tried manthan, but i get way worse paths
Then, you have an issue somewhere else
Yes since manthan distance not work if diagonal movement allowed
Oh, the get distance should return the distance between neighbour and target
But it returns current to neighbour now
I misread (since my a star is slightly different from standard one) and i have to sleep now
The heuristic looks correct though this is not the heuristic i use
If you guys want to check the whole code, i have it on github, tho, look only at the files with the termination .ts and don't mind the cloning stuff as in JavaScript object have referince and i need to clone the grid when searching for a path to set the costs inisde that grid
For get distance
i switched to this method
private getChebyshevDistance(first: Node, second: Node) {
const disX = Math.abs(first.x - second.x);
const disY = Math.abs(first.y - second.y);
return 10 * Math.max(disX, disY);
}
and the result seems better
the path is not that long for the wierd nodes
Only this i find it a bit wierd
maybe adding a moving penalty for zig zag moves?
this seems definitively not Unity related
Yes 😅 but i have no idea how to ask about this kind of stuff
Has anyone here done OAuth 2.0 in Unity with Azure? I have a .NET Core backend. How do I retrieve the token from the redirect URI to microsoft?
Google, A star is probably the MOST documented algorithm.
Also, you can simply debug your code. (Code Trace, Isolation, Simplification, etc.)
Many have probably tried and decided to rather go for an extended walk and hope someone else does it. 🫣
The same way any other application would do I would guess. The last time I had to setup something similar, I did the authentication process with a server than use it as an intermediate. (server-server communication instead of client-server) The first step is to make it works with Postman.
There is extensive docs on the subject: https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow (and yes, it is complex)
this lets you POST a username and password to a URL. the response will be a token
are you asking the same thing as @neon wraith ? you can use this too
what do you mean an existing C void* pointer? do you mean from a plugin?
can you show the snippet of the plugin side and the unity side?
a C# void* isn't the same thing as a C void*
even in unsafe
I see, but I've already fixed that. Ty anyway 🙂
I just had to add the Editor collection checks instance:
#if ENABLE_UNITY_COLLECTIONS_CHECKS
NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref nativeArrayWrapper.NativeArray, AtomicSafetyHandle.GetTempMemoryHandle());
#endif
But I guess this could be considered a Unity bug, bc instead of simply alerting the user or giving a more specific erro,r when the NativeArray m_Safety value is null, it throws a NullReferenceException without much details
you can use AtomicSafetyHandle.Create() instead, if you want a real handle
Why would I use a handle on a data allocated externally (on a native dll)?
And it is a read-only data, in theory, I don't need it
it would help to see the snippet
public static unsafe NativeArrayWrapper<T> ConvertExistingDataToNativeArray(
IntPtr data,
int length)
{
NativeArrayWrapper<T> nativeArray = new NativeArrayWrapper<T>(NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<T>(data.ToPointer(), length, Allocator.Invalid));
NativeArrayUtils<T>.SetupNativeArray(nativeArray);
return nativeArray;
}
i'm saying on the native side
And it is a read-only data, in theory, I don't need it
it might be read only, but it might need to be moved
Ah, it is just a struct array allocated with new []
maybe best to just do what it says
also Allocator.None might be the better option
The idea of the Temp allocator is that it will be Disposed at the end of the frame
And I don't think it doesn't do anything when allocator is None or Invalid, but I'm just guessing...
yes but you're not allocating anything
yeah
i don't really know either i am just following the docs
I guess Unity needs a method like ConvertExistingDataToReadOnlyNativeArray
the only thing atomic safety handle does is ensure jobs are written against the data correctly
it doesn't enforce anything when those editor checks are disabled
so it's "just" a feature of "hpc#" aka the burstable jobs code
best to just make one correctly
no consequence to it
go ahead and make it and enforce your belief that it is read only, at least in editor
👀 new[] in 2023
like in C++?
or something like
int length = 5;
int* data = stackalloc int[length] { 1, 2, 3, 4, 5 };
which you can do in C#
almost everyone always wants to allocate in C#, then pass a marshalled pointer to C++
because allocating in C++ for use in a managed language is like buying all the rope in the rope store, then fastooning it around your house in various hoops, loops and what have yous, and then jumping on a floor made of trampolines
In CPP, it is an external dll
are you saying the code is literally new[] or like new[], but is actually normal modern C++
anyway
i think you know what you're doing and you're just trying to make something work in unity
My struct arrays can become quite big, I don't think it would be safe to allocate them on C# stack anyway
yes you don't have to allocate them on the stack
i would allocate an ordinary NativeArray (or Span) on C# side then pass it to the DLL
if possible
if you didn't write this library
don't sweat it
it's a video game
Yes. I'm experimentating with NativeArrays now, the native libraries might wait a bit
A model loading library
you're familiar with trilib?
That is my library...lol
I've added FBX SDK support to it
you'd think they'd have a C# binding for it already
But I'm trying to squeeze more memory with the current approach as well
They do, but I don't recommend using it, not bc I've made TriLib, but bc there is some overhead on converting FBX SDK data to DOM
the more burst the better
So I've created a backend system for it that allows using external libraries like FBX SDK, Assimp, etc
that's cool
have you looked at the alembic package and how it does things?
alembic is a much simpler format
Not yet
but sometimes very high data rate, and it uses burst
Yes, things like data array processing can benefit from multi-threading
And another backend alternative I'm adding to it does uses multi-threading internally to parse such things
i mention it because of all the mesh formats i've used, this is the only one where it does realtime playback correctly of stream-of-meshes
Interesting. I don't know much about the format, but maybe it is the most suitable to do such things
see https://appmana.com/watch/virtualrunways <--this was a mesh sequence export from MarvelousDesigner
An AppMana Streaming Experience
Imported at runtime?
Pretty fast
yeah when you toggle between the outfits
Ah, so it is not runtime Alembric loading, rather a pre-processed Alembric file?
i think the heretic also used an alembic asset - https://appmana.com/watch/theheretic
An AppMana Streaming Experience
Pretty impressive for a WebGL app
And yes, formats like FBX are pretty tricky to insta-load at runtime
Not made for that purpose
the virtual runway assets are 8GB
also you can't do HDRP in webgl. you can barely do shadows
Yep
in this platform you can load into trilib at runtime, from a drag and drop. it would just be imported in a multithreaded, very powerful computer.
@dusty wigeon i found the issue in my code, i had to clone the first item when removing the first from the heap 😂
Thank you i'll try that out
That's unfortunate to hear. I think I may have found an existing solution, without having to use ROPC like @undone coral is suggesting. ROPC seems to be what AWS Cognito does though so maybe it's not too bad, but it's definitely less secure as stated in the doc https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth-ropc.
The solution I found seems to facilitate this flow (authorization code flow) @dusty wigeon: https://github.com/cdmvision/authentication-unity. I'm trying it out now, but haven't gotten it to work. Trying to figure out the deeplink portion.
Edit: Goddamn it, deeplinks don't work for standalone PC builds.
any idea about this error ? Unity Web request failed to load from cache. The cached AssetBundle will be cleared from the cache and re-downloaded. Retrying...
retrying is never be successfull. i take various errors
Close all of unity, Log out of the hub, close it fully, log back in
Fixed it for me last time
Hey guys,
I have a question about VContainer.
I have a Player gameObject that Instantiate a Character prefab which contains LifetimeScope.
Instantiated Character gameObject has CharacterController facade which Instantiate a few ScriptableObjects.
These ScriptableObjects have a Constructor method (Method Injection). One of the classes which should be injected is already registered by Character LifetimeScope.
The issue is, it can't find registration of that type. My first guess is, I should specify the LifetimeScope parent which is Character LifetimeScope for these ScriptableObjects but no idea how and even I don't know if it is a right guess.
could someone help me remake the effect in stardew valley where a player walks thru crops they move.
or just break down how to do it.
I know how to code but got no idea whether to do it with animations, or a lerp
Bit if an advanced topic but how would you guys implement asset loading for mods?
I don't want the files to be in Assets/Ressources so have to come up with a different solution
One I came across might he assetBundles
What do you people here think and how would you tackle this?
My advice would to NOT directly support in your game. Game can be modded without any support. Unity games are particularly easy to mod as they are realy popular. https://wiki.nexusmods.com/index.php/How_to_create_mod_for_unity_game
If you truly want to do that, and want to support user content without access to Unity you can use: https://docs.unity3d.com/Manual/StreamingAssets.html. Alternatively, you can use AssetBundle/Adressable but that would require the use of Unity.
I sctually think that using unity for asset creation would be a good idea. I just want them to be actually loadable eithout being in the asset directory
My current layout is this and it would be nice to keep it
BaseFolder:
-Game.exe
-Databases/
-Mods/
-... (All the build unity stuff)
Just reading the ressource of the given filepath is what I want
Does anyone have a lot of experience with DataContractSerializer?
I've been making updates to the class I'm seralizing and deserializing, and I want to future proof it by allowing it to deserialize only parts of the class, if say, one element has been changed or is now deleted.
I'm getting some errors with existing account and I want to make sure that any updated I make to the account profile files in the future don't break or require me to delete and remake the profiles, since progression is linked to them.
I've been scouring the documentation but I haven't been able to find any concrete examples of partial deserializiation.
i am trying to use the burst compiler with the jobs system and right now i am getting an error that it doesn't support multi dimensional arrays is there a simple fix for this Ex: Float[,,] this doesnt work
Convert it to a 1d array.
Btw, you should probably be using native array anyway.
the job system doesn't support managed arrays of any kind
Yes, use NativeArray
I never tried use pointer of managed array in job, idk if it works
I'm pretty sure it does, but kills the performance
and you can't pass them to or from jobs, can only make allocations inside
According to the docs, only statically allocated C# arrays are allowed, since they're allocated at compile time.
I want to track the total time of a player in my game.
what is the best variable type to track this?
i thought of a long?
I dont think you would need a long if you are just tracking seconds
int would be fine
Time span..?
uint is enough even if you measure in seconds (4*10^9/10^5=4*10^4 days)
but you may need long if you are measuring in millisecond
or other readable data type
Total time in the current session?
In the current level?
All time?
All time i serialize the total time of the entire play session each time
Ok just save that number to a file and add the current session's time to it each time
double or long is fine
You could also serialize a TimeSpan if you want
Hi everyone, can someone give me comments on my tenant/app and auth setup for Azure?
I have a B2C tenant. I have a Unity frontend with an app registered in this tenant. This app has no scopes defined, and supports All users. I also have a Web API that will access resources from Azure on behalf of the user/Unity frontend. This app has the scope access_as_user defined, and only supports internal users (within the tenant).
- Server authenticates itself with Azure with some daemon authentication scheme. So the web app is now authorized to retrieve/post resources from/to azure.
- Unity proves to server that it is real by sending certificate/secret?
- User registers by clicking a link in Unity which will prompt them to register on a browser.
- User enters credentials in Unity which will be sent to my Web API. I know this is frowned upon but as I mentioned, extracting the token from an external browser to Unity is a pain in the ass. Anyways, the server will then request the token on behalf of Unity. Server passes token back to Unity.
- User is now logged in on Unity and use token for ever request thereafter.
Any comments/suggestions on this setup?
Hi everyone, can someone give me
i only have experience with protobufs to solve this problem. i am not sure if DataContractSerializercan really support your use case, even if it says that it can
I have fixed it by labeling members with the [DataMember] attribute, which seems to allow it to skip some variables
No more deserialization errors as far as I can see
These two function are inside the TileData struct, is one of them 'better' than the other one?
I would guess that the bottom one just calls the top one
my guess is the first compares both if they are neighbors
and bottom uh
oh is the neightbour local to the tiledata
then it compares that to another tiledata
the static method is a general utility function
the top one would be called like:
TileData.IsNeighbour(someTileData, someOtherTileData);and the bottom one:
someTileData.IsNeighbour(someOtherTileData);The question is, is there an advantage to one of these over the other?
no
it's just how you want to call it. Use the local data, or use both references
are there any collider options that allow you to set a series of points (like edge collider) but update the collider without resetting every single point? i need to frequently redefine the collider but i'm only adding or removing one point at a time and it gets really slow to reset every single point.
how are you "resetting every single point"?
Are you reusing a list or array?
or creating new ones all the time?
i have a set of the points stored in my class, and i add and remove points to it as necessary
how it works now, in order to ensure the correctness of the collider, every time i add or remove a point from the set i have to reset the edge collider points
and that mega lags
@sly grove
Guys, when calling the Mesh.SetIndexBufferData method using a List<int> as the data argument, Unity is crashing, and the only thing I can find in the log file is:
Assertion failed on expression: '(int)lastVertex < data.GetVertexCount()'
I'm making sure I'm not referencing vertices out of the vertex buffer data range, and it doesn't seem to be the cause.
That expression certainly seems like it's comparing the last/biggest index in the buffer to the number of vertices in the mesh.
Yep, but they are all in range
Are you only setting the index buffer or also vertex data at around the same time?
The vertex data, right before setting the index buffer
Mesh.SetVertexBufferParams(VerticesDataCount, attributes);
var streamIndex = 0;
if (VerticesData.Stream1 != null)
{
VerticesData.Stream1.SetVertexBufferData(Mesh, ref streamIndex);
}
if (VerticesData.Stream2 != null)
{
VerticesData.Stream2.SetVertexBufferData(Mesh, ref streamIndex);
}
if (VerticesData.Stream3 != null)
{
VerticesData.Stream3.SetVertexBufferData(Mesh, ref streamIndex);
}
Mesh.SetIndexBufferParams(IndexCount, IndexFormat.UInt32);
Mesh.subMeshCount = GeometriesData.Count;
var indexStart = 0;
var subMeshIndex = 0;
foreach (var geometry in GeometriesData.Values)
{
if (geometry != null)
{
var descriptor = geometry.GetDescriptor(indexStart);
geometry.VertexDataIndices.SetIndexBufferData(Mesh, 0, ref indexStart);
Mesh.SetSubMesh(subMeshIndex++, descriptor);
geometry.VertexDataIndices.TryToDispose<IIndicesList>();
geometry.OriginalVertexIndices.TryToDispose<IndicesListWrapper>();
}
}
SetIndexBufferData and SetVertexBufferData are located inside the lists generic methods, and they call Mesh.SetVertexBufferData and Mesh.SetIndexBufferData internally
There's a lot of parts here. Indirections that could be hiding some bugs. I've never seen this assertion appear as a false positive. It's most likely that there's something wrong somewhere in your code, and you can't figure that out without going everything. Add some debug logs, validation checks.
What are the details of this?
Also how many points are in the list?
somewhere in the hundreds, roughly, but it depends on the list (there are 5 or 10 objects with this script). each time i add or remove a point from the set, i call edgeCollider.SetPoints(pointSet.ToList())
on average this happens very infrequently but when it happens, it happens many times in a few seconds
i tried using a list instead of a set so i wouldn't have to convert to a list, but that just moved the lag to a different part of the script that used the set as an optimization
i was asking about this in the other code channel but had no luck, I have a prefab with a script that has an array on it, when I try to change the size of the array using the inspector, the array disappears completely and I'm getting this wall of text pop up in the console. It’s a recent thing that started happening and it happened right after I tried to see if I could use nested arrays and put an array with [,] in the code, when that didn’t work I tried [][]. That didn’t work either so I went back to just []. Nothing sticks out to me as the cause for it to happen, can someone take a look to see if you can figure it out?
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.
@sly grove nevermind, i think i found an alternate solution, no more massive colliders lol
@sage radish strangely, SetTriangles works using the same input index list
What algorithm would I have to use, or how would I place rooms and paths like this?
Really it's just a statemachine with a bunch of conditions.
Doing ToList() is bad
Oh sorry missed the other part
Where can I learn about it a lil bit more?
Pathfinding algorithms
Roguebasin probably has a lot of info for this stuff if you dig around
i see, maybe that was really the issue, thanks for the tip. found another solution anyway tho
https://www.jamisbuck.org/mazes/
Check this site out too. It's pretty cool
Thank you!
we talkin' mazes? https://bost.ocks.org/mike/algorithms/#maze-generation
for the unity asset database how do you set the search filter to search by type and a name? i tried:
string filter = "t:TestScriptableObject " + name;
but it never finds anything
t:PieceConfig Battle with the .FindAssets gives me the 6 entries that the project view gives me. So it works fine on my end.
*Script Error Loading* Theres a roller coaster script
Might have to include the namespace?
in scene view edit we can scale UI Image on just one side, but when i looking at the method available its just size delta, and scale that one, will scale its on two side, i realize during test on scene view, the width AND the pos x are changed simultaneously, can anyone direct me how to code so i can scale just on one side??, either only left, right or only up etc...thanks
offset max or offset min of rect tf
I'm facing a very weird issue regarding Firebase Cloud Messaging and AppsFlyer SDKs in my multiplayer game. I initially had only FCM plugin and Firebase.Messaging.FirebaseMessaging.MessageReceived was fired whenever a player clicks on a push notification and the game is started. I used to get the payload data from the event's listener method.
Then I've integrated AppsFlyer SDK for analytics purposes. Then the update went live. Now I've decided to remove the AppsFlyer plugin. But after doing that, weirdly the event Firebase.Messaging.FirebaseMessaging.MessageReceived is not firing now. The push notification is showing up, but when I click it and open the game, I'm not able to get any payload data since the event is not fired. Did anyone face this issue before? Why is AppsFlyer changing something of FCM?
Btw this is happening in iOS
I've checked the Unity settings, Xcode settings, plist files but I can't see any changes between the versions (with AppsFlyer and w/o AppsFlyer)
If I just reimport AppsFlyer SDK into my Unity project (without integrating into the game in any way) and run it then FCM will also work properly.
I think I might have my answer to all my physics issues, and it super sucks. Basically, I need to write my own physics engine almost. Make everything static/kinematic, and then do things similar to the KCC package.
The plan is basically:
- Al kinematic/dynamic RBs are moved via a different class which tracks pos, rotation, vel… It’s like an RB api on top. Then everything is kinematic. Call this class physicsMover.
- To move, AddForce/moveposition etc requests are passed to the PhysicsMover : Monobehaviour on the object.
- PhysicsMovers all list themselves to a singleton KinematicCharacterSystem, with a given order.
- Kinematic character system, right before physics simulation step, collects all the info from all the physics movers, and does its own physics calculation. It casts kinematic RBs, while pushing simulated dynamic RBs out of the way. Force will not transfer from simDynamic-simDynamic RBs in this system.
- Then KinematicCharacterSystem goes through all simDynamic RBs, and casts them based on velocity etc. It will use the collide and slide algorithm to find its next position.
- Call MovePosition on all RBs, and physics step will move them to where they need to go, and generate collisions and callbacks.
Does this sound like a solid idea?
I’m just so frustrated with the physics2D system. It’s closed, so I can’t do shit when I need to modify anything. I can’t program joints/effectors, I can’t change how contacts work etc…
yeah its a huge pain but that's the only way to have full control
I have extended KCC because I didn't really like the architecture too much but the core system is good
it gives a lot of control
I have not gotten around to making a 2D version yet as I am working on 3D projects but I would definitely do it if I was working on a 2D project
so, solid idea I think
many of Unity's systems are very closed 😢
tfw Godot grows stronger
What are you making ?
... You do not need to rewrite a whole physics engine for that ?
POW blocks can get: 1) thrown around and appear to follow gravity/momentum/other forces, 2) get stopped by solids (including any POW block), and 3) Can stably ride other surfaces (like POW blocks or platforms), and 4) can be ridden by other things (player, blocks, etc)
explain to me how to make that work in a simpler way
Sure, use kinematic + sphere cast
the whole system I proposed is a bunch of kinematic RBs casting in a specific order to calculate collisions and where they are going
You also use non kinematic if you want it to rebound and act like a physics bject
I have blocks right now that are dynamic, and work fine until you have blocks trying to ride blocks, as you need to translate transform to do that for a dynamic RB
Q: How do you get the block to rebound and get pushed by other physics objects, while also riding other blocks, without affecting the trajectory of the block it is riding?
Transform.Translate + Raycast
tried that. the moment you use transform.Translate, you move the colliders in a way that doesn’t respect physics
You use Raycast to respect the said physics
and if you cast to clear the way, you run into contradictions in what is supposed to happen
if block 3 rides 2 rides 1, and 1 moves left, 2 has velocity going up, and 2 hits an obstacle in the way, then where is 3 supposed to go? It would need to raycast n-1 times to move with everything
The other option, is to set the velocity
If block is riding, then add the velocity to the given block
tried setting velocity. It accumulates. If block 2 hits an obstacle, and then the obstacle disappears, it is difficult to get block 2 back on track synced to block 1 by setting velocity
You can use acceleration also.
Ride is going at 5m/s.
If block is not on point on Ride. Accelerate towards point
if you try to remember the old velocity, and calculate the difference before/after physics calculation, then if you have block 2 hit an obstacle, then during physics simulation, blocks 3+ were all given velocity assuming 2 didn’t hit anything, which is wrong
then what do you do if block 1 has constant x velocity
If block is on Ride, then add the velocity of the ride
if I add velocity of ride every frame, that is also wrong
velocity increases without bound with const velocity platform
Obviously, you do not add it every frame
then how do you make block 2 track properly if an obstacle gets in its way, then disappears?
block 1 moving at const velocity
static terrain shears block 2 to the side for a bit, then is out of the way
i would use acceletation, but the physics simulation is like a closed system
what you are suggesting is like a RelativeJoint2D, which would allow the block to track with forces based on how the underlying platform moves.
But since the physics system is closed, I cannot stop the block above from applying force to the thing it is riding
so if terrain is shearing off block 2, the joint would actually halt block 1, which is wrong
you need to calculate that before physics step, right? to apply force?
moving the top block onto the green is not right
Just for reference, what I have tried:
-Transform.Translate based on delta position OR with casting => janky collision and overlapping
-Joints => upper blocks pull lower blocks, wrong
-Friction => doesn’t sync motion well enough.
-Two colliders (so I can make lower block independent of top) => still can’t apply assymmetric force to upper block to track.
-Change velocity => Can’t reconcile collisions during physic step
-SurfaceEffector2D => incompatible with platform effectors, which are mandatory. Also I can’t track vertical pos.
can someone explain to me why I should use Dependency injection instead of Singletons for managers to keep track of certain game data?
More formalized control of the object lifecycles I guess? The standard Singleton pattern is just a low-sophistication DI implementation.
serialized fields are also a form of DI
DI lets you more easily replace the implementation of any feature/system/manager. Singletons are usually tied to a specific class with a specific implementation.
better unit testing support too I suppose (going along with the "more easily replace the implementation of any feature/system/manager" part)
@sage radish @sly grove
fair. I want to fit my code for unit tests anyways which would make that part easier.
However I'm having trouble implementing DI using Zenject
Any good resources you can recommend? The examples I saw in the official docs didn't seem to work and It was a bit weird having to manually asign how the DI should work for each objects.
https://github.com/Mathijs-Bakker/Extenject is specifically made for Unity
try Zenject
its really easy
they do very different things
Extenject is a unity-focused successor to Zenject
also i think you replied to the wrong person
singletons give you really clean and fast access to something you need frequently and everywhere. But isn’t a static class
yup sorry but ok
dependency injection is a way to decouple code by making both sides link to one thing in the middle
you know the difference?
dependency injection is literally just injecting a dependency into an object instead of creating the dependency within the object. passing objects via the constructor or assigning to public fields is literally dependency injection. it's not necessarily a giant framework where a middleman manages the commonly used objects that other objects depend on
the difference between extenject and zenject is that extenject was updated more recently. it's literally just a fork of zenject with the intention of keeping it maintained (which they seemingly failed to do since their latest release which wasn't even a full release is well over a year old now)
I see, yeah seems like it.
guess I'll give it a try again.
@thin mesa hope I'm not annoying you but I can't seem to understand how to make this specific case work:
I have a manager for handling scene changes which is a MonoBehavior rn.
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneManager : MonoBehaviour
{
private void Start()
{
LoadSceneWithLoadingScreen("Menu");
}
public void LoadSceneWithLoadingScreen(string sceneName)
{
// start an asynchronous operation to load the target scene.
StartCoroutine(LoadSceneAsync(sceneName));
}
private IEnumerator LoadSceneAsync(string sceneName)
{
// create an asynchronous operation to load the scene.
AsyncOperation asyncLoad = UnityEngine.SceneManagement.SceneManager.LoadSceneAsync(sceneName);
// while loading
while (!asyncLoad.isDone)
{
Debug.Log($"Loading Scene: {sceneName} - {asyncLoad.progress.ToString("P0")}");
yield return null;
}
Debug.Log($"Loading Scene: {sceneName} - 100 %");
Debug.Log($"Successfully loaded {sceneName}");
}
}
is it even possible to use this in my other script?
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NavigationController
{
public void NewGame()
{
// Call the sceneManager here to load a new scene
Debug.Log("Pressed new game");
}
public void LoadGame()
{
Debug.Log("Pressed load game");
}
}
or am I missunderstanding smth?
what's important to note is that my SceneManager is present in a persistant scene at the start
while the other script is located in a menu scene.
whatever object creates the instance of NavigationController just needs to get a reference to SceneManager and pass it to NavigationController. or you can use something like the singleton pattern to get a reference to it. this is far from advanced though. you should check out this resource for learning how to refer to other unity objects
you will need a reference to a SceneManager instance to call its functions
You can use the Singleton pattern
I'm trying to avoid singleton pattern right here, thats what this is all about.
Wouldn't it be better to inherit SceneManager from NavigationController?
NavigationController is just a UI View Controller tho, it does not really have much to do with scene transition, yet I need to call that functionality from there.
sorry i zoned out and forgot which discussion this was and which channel I'm in
All good, this is not the code-beginner channel haha
I know how to do references etc.
I don't see why that would be a problem though. You just have to change the Start() method
Then you can have it like:
public void NewGame()
{
base.LoadSceneWithLoadingScreen("Start");
}```
Isn't that against the law of inheritance kinda?
Why should a view UI controller inherite from a scenemanager
( plz correct me if I'm wrong )
I only use inheritance for things that are similar yet have differences like
sword and gun inheriting from weapon
or truck and jeep inheriting from vehicle
Gun and Jeep are also both inheriting the same class, MonoBehaviour
that's true
in theory
those were just inheritance examples, nothing I did in unity.
tbh I don't exactly know what you mean with view UI controller, but for me it sounds like SceneManager is a script that handles loading any scenes, NavigationController is a script that handles loading specific scenes.
NavigationController is attached to a UI panel handling starting a new game and loading the game
so it handles UI actions.
I have a weird issue, where the perlin noise that i generate, takes account on the Offset, when the game is started and its awake method is called, but not when the player moves, and those same methods within are called again. However when i use my mouse for moving it, within unity editor, it does work as intended... (I will send a video of my problem in a moment)
So as shown on this video, when my player moves to the side, and its supposed to push the perlin noise texture on the quad to the side, it doesent, it simply changes the offsetX value in the editor, but when I with my mouse change the value it the editor, then the noise moves as it should... This is such a weird issue, i hope someone can shed some light on what is going on here... i have quadruple checked my scripts, and they are all fine, so i am out of ideas of what to do to solve this.
I mean, that's a silly thing to say because obviously something is wrong with your scripts
you're going to have to show the PerlinNoise script but my guess is it's updating the texture based on OnValidate or something from the inspector, and you aren't triggering any changes when your character is moving
normally i have the myRenderer.material.mainTexture = GenerateTexture(); line in the update method, commented out
im guessing you need all the 2 scripts connected to this, right?
I have the random object spawner, which spawns my tree objects, and my infinite world script, which moves the squares or "Chunks" of background
nope, this one is horrific enough. What happens if you copy-paste the sequence of values offset gets set to instead of the tiny increments? maybe you just happen to be snapping to integer coordinates, so it's generating the same noise map every time
Perlin noise repeats on integer intervals, iirc
yes, that's what I think the problem is
oh, so how would you suggest i fix it?
And if you can find some references on the exact thing which is causing this, then please also send them, i would love to read up on it. thanks:)
well one easy way is to normalize the values using the dimensions of your map, or whatever size you're fine where the pattern will repeat at
how would you go about that?
or, first of all, how can i make the noise visibly update when player is walking?
you're already doing that in the above script, every frame spewing garbage everywhere
it seems that changing the number in which the offsetX value is incrementing with, to a much smaller value, makes it move as intended.
Thanks for a straight forward answer:)
I'm not sure if simplex noise behaves the same way or not. I should probably check that.
Discussion: Multiple Scenes or Single Scene for Game State
Reviving the thread from the dead.
Want to confirm that PolySharp works just fine in Unity, you need to update the outdated roslyn that comes with Unity
(sorry for the ping, Burrito 😅 )
I have not personally tried it, but it should at least work for C# 9 features that are not supported because of missing compiler stuffs
Eg init properties, which Unity manual just tells you to make your own IsExternalInit, and PolySharp would source generate it for you instead.
I'm using the tool made by Zombie from our server (c# discord). It can do c# 11 too now 🥹
Oh wow that's cool, good to know.
Maybe I'll mess around with it some day, some C# 10/11 features look pretty juicy 🤔
How would you go about updating Roslyn in Unity?
give me a sec I'll put his repo here
@scenic forge https://github.com/DaZombieKiller/UnityRoslynUpdater
Thanks.
is there a way using OnValidate() to make a value show in the inspector if bool is ticked?
just want to show/hide the value depending if the bool = true / false
Do it with customEditor instead
It's very cool, but I'm on the fence about it because of the need to patch Unity installation.
Though I guess there's not really another way to do it.
good morning people 😉
trying to improve my code using task, i just learn i need to manage the toke to be closed if app crashes or unity editor stopped
is this code fine?
when i launch the task i create the source cancellation token and managed this ?
Usually your method should take a CancellationToken parameter, and operate on that to see whether the task was cancelled
And generate a token from the source: await MethodAsync(source.Token)
Note: if you're on Unity 2022 or above, you can access destroyCancellationToken, available on all MonoBehaviour inheritors, token that gets cancelled when the object this script is attached to is destroyed.
I might as well share this, since its the solution.
using UnityEditor;
[CustomEditor(typeof(YOUR_SCRIPT_HERE))]
public class EDITOR_SCRIPT_NAME_HERE: Editor
{
public override void OnInspectorGUI()
{
YOUR_SCRIPT_HERE theScript = (YOUR_SCRIPT_HERE)target;
if (theScript.boolToCheck)
{
EditorGUILayout.PropertyField(serializedObject.FindProperty("boolToCheck"), true); // make sure to keep this one visable
EditorGUILayout.PropertyField(serializedObject.FindProperty("ANY_PUBLIC_PROPERTY_HERE"), true);
}
else if (!theScript.boolToCheck) // show other stuff if our boolToCheck isn't true.
{
EditorGUILayout.PropertyField(serializedObject.FindProperty("boolToCheck"), true); // make sure to keep this one visable
EditorGUILayout.PropertyField(serializedObject.FindProperty("ANY_OTHER_PUBLIC_PROPERTY_HERE"), true);
}
serializedObject.ApplyModifiedProperties();
}
}
Thanks @novel plinth
Or just wait for coreclr so we can target any lang versions 😄
The dream.
You can't do anything once the editor itself crashed
also you can do TimeSpan.FromSeconds(value) instead of miliseconds there for the delay
ok thanks, using 2021 yes
but i must take the source in the end where is my await?
im calling this task from another class , so how can i call the task with the token?
The source can be declared in the other class
i cannot find an example like this
class A
{
private CancellationTokenSource cts;
public B classB;
void Awake()
{
cts = new CancellationTokenSource();
}
async Task Sample()
{
await classB.MethodAsync(cts.Token);
}
}
but must be async task sample(cancellationtoken toke)?
// in class B
public async Task MethodAsync(CancellationToken token)
{
// do stuff...
if (token.IsCancellationRquested)
// handle cancellation
}
A CTS produces linked tokens, so you can see from the token whether the cancellation has occurred. Don't pass the CTS everywhere, it's not its job
ok thanks so much for the example, so then
what class so check in OnDisable destroy the task?
class A really?
Yes
If you need to cancel the task when B gets destroyed, then it's B's responsibility to signal A to cancel the tasks using the CTS
Using an event, preferably
hmm
Or, you can add some code in B that will just return from the async method when OnDestroy gets ran, using a boolean variable
CTS allows you to cancel tasks that the caller (the method that invokes the async method, passing the token) is not in control of
thanks for explanation
i can use profiler to check everything is going fine?
just reading in unity 2022 there is some changes
for this scenario you can use linked token sources
hmmm how can i get this
Guys, is it possible to insert the JOB System in my game (a classic 2D mobile project) to multithread a couple of algorithms here and there without changing it fundamentally?
For example, if I convert my project to DOTS, then I would definitely need to start over because of ECS. But afaik the jobs system is more malleable. I wouldn't need to run my entire project multithreaded, right?
yes, but you may need to change your collections to be job compatible
Thank you 🙏
I'm going to be building a 2D physics engine (kind of) on top of box2D. The plan is:
- No rotation. Rotations can be set, but never changed during simulation,
- All objects are kinematic, and have different settings for how they are allowed to be simulated (can slide, can push, true kinematic,....).
- All objects get a monobehaviour (physicsMover) as an alternate to the rigidbody API to communicate with the custom physics system. This monobehaviour holds those settings, as well as current position/velocity/etc. Also has a physics check order.
- During fixed update, right before Box2D physics simulation, we go through all those physicsMovers in the specified order, and evaluate by casting a single collider (called the main collider) which is used for force/physics calculations. Physics step goes as follows:
--Foreach physicsMover, cast it from its current position by a vector (velocity += force / m * deltaT, cast vector = velocity * deltaT)
--If we hit something, logic depends on physics mover settings. Kinematic objects push pushable things forward if possible. pseudo-dynamic objects may or may not collide and slide. If the object get pinched in an overlap, then we need to call other logic to know what to do (kill object, let it pass though, etc).
--Update all positions and sync.
Does this sound like a non-terrible idea?
Yes, it sounds like a terrible idea. It is no small task to rewrite a pseudo physics engine.
Is there a com.google.games:gpgs-plugin-support for UPM?
thakns
Is there an advantage of using the vertex buffer methods from the Mesh class, or can I just focus on writing logic inside of my own compute shader script, then setting the mesh data directly from the output?
**Actually I'd still compute the logic via gpu program regardless, but Mesh has two different APIs and I was wondering the advantages of both.
If anyone can answer some general mesh manipulation and optimization questions through unity's API, do ping me ;)
For advanced use cases that require maximum performance, you can use the advanced API, which has functions like SetSubMesh, SetIndexBufferParams, SetIndexBufferData, and SetVertexBufferParams. This advanced API gives access to the underlying mesh data structures that primarily work on raw index buffers, vertex buffers and mesh subset data.
https://docs.unity3d.com/ScriptReference/Mesh.SetVertexBufferData.html
As far as I know, it gains in performance mainly because there is no validation done.
Using these methods, Unity performs very little data validation, so you must ensure your data is valid.
https://docs.unity3d.com/ScriptReference/Mesh.SetSubMesh.html
What would be needed to validate? Like if you had more UVs than general vertices?
I would be fine with just using SetColors, SetIndices, SetNormals, SetTangents, SetTriangles, SetUVs, SetVertices, and such. But I've no clue if it's like passing through all vertices every time.
There's really no single Mesh method to take in this type of vertex info, so maybe that's the idea of using the other API.
@regal lava , An example would be:
Ah, ok yeah. Lot of extra logic I'd probably don't need.
Most of it is C++, so cannot really see what it really is
Except if you have a 80k laying around and some notoriety.
Haha, yeah. Eventually ;)
https://docs.unity3d.com/ScriptReference/ComputeShader.Dispatch.html
Any reason to optimize threads on all three dimensions for vertex data? Rather, what scenarios would I spread out these threads? Like a situation that your x/y/z verts are strictly on those axes, but other than that?
Seems like a strange concept that maybe I'm not understanding, but a lot of code I see is just throwing what's available into a single dimension.
I mean, each thread should be doing work independently anyway, so why would subdividing them help with the results?
https://gpuopen.com/learn/optimizing-gpu-occupancy-resource-usage-large-thread-groups/
Ah, an interesting article on it
From what I understand reading the documentation, Unity's .Net Standard 2.1 framework should be compatible with .Net 6.0, Correct? I wrote some class libraries using .Net6.0 but after integrating and writing a unit test, I'm getting an error about System.Runtime version missmatch. '''TypeLoadException: Could not resolve type with token 01000039 from typeref (expected class 'System.IAsyncDisposable' in assembly 'System.Runtime, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')'''
How does one do that? Accordion to the Microsoft docs there is no .net Standard 2.1 SDK your just suppose to use various versions of .Net. ".NET Standard is a formal specification of .NET APIs that are intended to be available on all .NET implementations. To target .NET Standard in your projects, install one of the SDKs from the .NET/.NET Core table. For more information, see the .NET Standard article."
The spot were it's erroring out is when I'm trying to setup DI for the backend libraries, perhaps it's not the framework but the Microsoft DI libraries.
I did have an error when I was importing the Dependency Injection assemblies. I excluded them from the Editor seems to resolve the issues. I couldn't find any clear answers on the errors: Unloading broken assembly Assets/GuildLegendsPrototype/Unity/References/Microsoft.Extensions.DependencyInjection.dll, this assembly can cause crashes in the runtime
Ok so apparently when using nuget there are multiple versions of the assembly downloaded, There is a specific standard2.1 folder with compiled dlls. removing the previously imported dlls, and importing the ones from the standard2.1 folder, its no longer erroring on the DI call.
Has anyone done occlusion culling for procedural levels?
If you got any resources or even open source solutions you can point me to, please do
The levels are fully generated on start, so that's when the occlusion data generation would happen
Why would this happen in android (error doesnt happen while in the editor)?
2023/10/22 16:20:40.483 530 702 Error Unity NullReferenceException: Object reference not set to an instance of an object.
2023/10/22 16:20:40.483 530 702 Error Unity at UnityEngine.Object+MarshalledUnityObject.ThrowNullExceptionObjectImpl (System.Object obj) [0x00001] in \home\bokken\build\output\unity\unity\Runtime\Export\Scripting\UnityEngineObject.bindings.cs:737
2023/10/22 16:20:40.483 530 702 Error Unity at UnityEngine.Object+MarshalledUnityObject.MarshalNullCheck[T] (T obj) [0x0001d] in \home\bokken\build\output\unity\unity\Runtime\Export\Scripting\UnityEngineObject.bindings.cs:620
2023/10/22 16:20:40.483 530 702 Error Unity at UnityEngine.Collider2D.OverlapPoint (UnityEngine.Vector2 point) [0x00000] in <00000000000000000000000000000000>:0
2023/10/22 16:20:40.483 530 702 Error Unity at ClickScript.Update () [0x00059] in E:\Games\Franks-Pizzeria\Assets\Scripts\Principal\Clicks\ClickScript.cs:73```
void Update() {
foreach(Touch touch in Input.touches) {
if(touch.phase == TouchPhase.Began) {
Vector3 wp = Camera.main.ScreenToWorldPoint(touch.position);
Vector2 touchPos = new Vector2(wp.x, wp.y);
if(boxCollider2D.OverlapPoint(touchPos)) {
ItemClicked(Camera.main.ScreenToWorldPoint(touch.position));
}
}
}
}```
Which one is line 73?
looks like the boxCollider is null
Does anybody have a guess as to why a mesh generator I modified from Sabastian Lague's procedural generation tutorial stops working when the vertex count is greater than 2^16 (65,536)? https://i.gyazo.com/f7d06d3e491123a9a45d148402d92ca7.gif
That is the max vertex count of a single mesh in Unity
You need to break it into multiple meshes
You can change it though
Is that so? Would that be a bad choice for performance? Although I am trying to bust out this project as quickly as possible.
Probably doesn't mater much
I see. Where do I change it? Is it in project settings?
the 32 bit one may not work on some mobile gpus
Just don't support old phones then
Hey folks, anyone know what course of action I could take when trying to squeeze as much performance out of MonoBehaviour Unity as possible?
I'm unable to adopt DOTS as a stack due to my project's requirements (a core part of the project has dynamic, hierarchical structures that rely a ton on interfaces + delegates) and unfortunately I won't be able to make architectural changes to make it compatible
I've tried to get as much as I can out of things like Jobs, leaning on the right data structures, and so forth - but I've hit a dead end and haven't been able to reduce the work my game needs to perform. Anyone know where I might be able to look at this point to help improve perf?
Deep Profiler/Profiler to start - figure out where your bottleneck is
Are you CPU bound?
Absolutely, I've been building out the core systems and haven't made a start on anything graphical yet - everything's a cube at this point
there's probably some low hanging fruit you could improve your performance drastically, depending on your expertise with unity.. but .. yeah, unfortunately the question is kind of broad and hard to answer easily
I've run Deep Profile on my project and most of the CPU time is being spread across a lot of dictionary reads/writes across the codebase. Unfortunately, there aren't any stand-out large bottlenecks to tackle at this point
is your project public? I wouldn't mind having a peek while watching football 🙂
That + some calls needed to get/set values on things like Transforms, though I've tried to keep those to a minimum
then probably work on optimizing your code to require fewer reads/writes
Won't be able to share, unfortunately 😔
get/sets and dictionary access likely aren't your issues unless your dictionaries are really huge
right not the operations themselves but the sheer number of them needs to be reduced
cache your monobehaviours, minimize instantiates, minimize update work, don't traverse the heirarchy with GetComponent or GetComponentInChildren calls
what magnitude of MBs are we talking about here? 1000s/100ks/1Ms?
you mentioned DOTS so I imagine it's large
its impossible to diagnose your issues without actually seeing the project, there are 100s of little things and 1000s of big things you can do to fix your issues, starting with simplifying the design of the project, if that is not possible, detail optimizations can only ever get you so far
could be that your whole architecture makes no sense, impossible to tell
yeah.. i mean, if you can't share your entire codebase to peruse (no worries on that, btw), it's hard to give general guidance on optimization.. but if you've narrowed it down to something more specific that'd enable better feedback from this channel
if you use a lot of interfaces and abstraction actual optimization on the data/cache level is likely out of the realm of possibility anyway, so your focus is on algorithms, structures and design
I can't share the whole architecture, which is a shame, though there are some problematic parts that I can give a share real quick
I'll get a gdl/hatebin/something set up for some things that have been causing a ton of trouble, hold on a sec
also we don't know your expertise.. like.. maybe you have something like
void Update()
{
MyMB newMb = Instantiate(myMBprefab);
Vector2 speed = newMb.GetComponent<MyOtherMB>().GetSpeedFromHugeDictionaryThatIsntCached();
this.transform.position += speed;
}
and if you had even as few as a few hundred objects this would likely kill your app
ie - instantiating in update, get component-ing every update, etc
this gives me an idea for a cursed unity code youtube channel or something lol
why just read more #💻┃code-beginner
because i give the little patience i was blessed with for my kids :p
hehe, good choice
"hey i have this problem with X but I won't do the obvious solution Y because I'm involved in a holy war can ne1 help"
"hey can anyone help me decompile minecraft"
you can also join the group of people who never ask anyone for notes on their work
bet you'll find some gems there
while I wait for quote's hatebin paste.. thought problem...
I have a "level map" (ie, candy crush, vertical scroll) where I want a background, a parallax layer, and a UI layer (on top).
Should I just orchestrate all 3 layers with one scrollrect? Or is there maybe a better solution
ie
that sounds nasty
stars move 1:1 with scrollrect, planet will move in parallax, and UI levels will move 1:1 with background but appear above parallax layer
i'd aim to not use UI if i can help it for the BGs
unfortunately i'm in a UI world since.. that's how I roll 😉
just because UI likes to redraw a ton of stuff all the time
yeah, i probably ought to reevaluate it at some point, I've got this app running in 60 fps and my phone gets a little warm
maybe make your own parallax component based on the UI API
https://gdl.space/opovazomut This here's a sample of some of the code that's been causing trouble
a stripped down version of the scrollview
which bit specifically?
Scheduling the Boxcast + the part at the end where I end up getting the components, the allocations + other jobs barely make a dent based on profiling info
fair but you're going to experience this thing where you play for 30 seconds then suddely the GC has to do a bunch of work and the app hangs for a few hundred ms or
are you able to show Looker.cs?
yeah this chunk of code is a pretty good candidate for profiling
how many raycasts are you performing per frame?
public class Looker : IObjectiveComponent {
// A Looker is an object that tracks what our characters
// can see when they're moving about the world
//--------------------------------------------
// The eyes that are being used by this looker
public Transform eyes { get; set; }
// The visual range of this looker - used to determine how
// far this character can see
public Vector3 visualRange { get; set; }
//--------------------------------------------
public Looker(Transform eyes, Vector3 visualRange) {
this.eyes = eyes;
this.visualRange = visualRange;
}
//--------------------------------------------
// Runs when this component is added to an item
public void OnCreate((Component) obj) {
// Register this looker inside of our manager
LookerManager.instance.Register(this);
}
// Runs when the object is destroyed OR the component is removed
public void OnDestroy((Component) obj) {
// De-register this looker inside of our manager
LookerManager.instance.Deregister(this);
}
//--------------------------------------------
// Clones this object, returning a deep copy
public IObjective Clone() {
throw new System.NotImplementedException();
}
}```
Had to roll my own component system to get more perf  @misty glade
those native allocators aren't as bad as plain c# allocation though
they are actually free if you pick the right one
About 20k or so, it's unsurprising that this amount of raycasts would end up causing problems w/ GetComponentInParent but I'm just not sure how to get around the issue
then you need to redesign the system, parallelization wont help you
you need to get those down by a factor of 10-100 depending on the importance of the system
or run them in the background at a lower frequency
I've tried to spread the work across frames by making the Lookers only activate every second or so + trying to stagger them so that they don't all get checked on the same frame. The thing I've put in to make that work hasn't been very successful, though
The lookers are all attached to characters in the game, the fact that there are so many is a fundamental design requirement so the only way through is to increase performance
Do you know any good ways to spread work evenly across frames? Giving each looker a time and trying to spread those out with Math.Random() probably isn't the best approach - but I'm not sure what would be better
You could queue looker "look requests" and only pop requests as long as the render time for this frame hasn't exceeded some amount of ms
(and keep an eye on the queue size, decide what to do if it exceeds some cap etc)
You can/should also use the job system for the raycasts
also is it possible to only process "lookers" that are near the player or camera?
and cull the rest?
private IEnumerator Process()
{
var sw = Stopwatch.StartNew();
while (true)
{
foreach (var looker in allLookers)
{
DoWork(looker);
if (sw.ElapsedMilliseconds > 10)
{
sw.Restart();
yield return null;
}
}
}
}
Already scheduling raycasts w/ RaycastCommand, sadly checking results is the only part that isn't jobified 
Also if you find yourself always doing GetComponentInParent on raycast results you may eventually find that a cache Dictionary<Collider, MyScript> is a worthwhile optimization
@compact ingot Re: Parallax - using scrollrect.onvaluechanged and orchestrating the parallax (and ui layers) seems to be reasonable
These all look like good roads to take, will give them a try and see how things go - thanks all 🙏
if it works and sells, you're done
😛
i could probably even add and expose the parallax coefficient to the designers but.. maybe that's complexity for the sake of complexity and not really useful
also keep in mind that if you can't get it into the ballpark on a single thread, parallelization won't really help you, its not a technique that can offer orders of magnitudes of improvement, only system design (culling, faking, caching), algorithms and datastructures can do that.
Yeah, pretty stupid on my part to think that this rule wouldn't apply here when that's always been the fix for practically every other performance problem I've run into 🫠
Again though, thanks for the help everyone - I appreciate it
Good enough for government work
I'm trying to retrieve domain name of the webpage the webgl client is running on from javascript to unity. Here's what my .jslib file looks like js mergeInto(LibraryManager.library, { GetTeamName: function () { let teamName = document.location.hostname.split('.')[0]; if (teamName === 'play' || teamName === '127') { teamName = 'blitzchampz'; } console.log('Host Name: ' +document.location.hostname); console.log('Team Name: ' + teamName); return teamName; } }); My GameManager looks like this ```cs
public class GameManager : MonoBehaviour
{
[DllImport("__Internal")]
private static extern string GetTeamName();
private string teamName;
private void Start()
{
teamName = GetTeamName();
Debug.Log("Team name: " + teamName);
}
}
Here's the output:
so for some reason the return teamName doesnt give return anything to unity... not sure what im missing... was following this article: https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html
Returning strings is covered in that very document
To return a string value, call _malloc to allocate some memory and the stringToUTF8 helper function to write a JavaScript string to it. If the string is a return value, then the IL2CPP
runtime automatically frees up the memory for you.
StringReturnValueFunction: function () {
var returnStr = "bla";
var bufferSize = lengthBytesUTF8(returnStr) + 1;
var buffer = _malloc(bufferSize);
stringToUTF8(returnStr, buffer, bufferSize);
return buffer;
},```
thanks lmao... ive been stuck for an hour lool
i just read the int part and assumed it'd be same 
Hey, I have implemented cellular based water simulation in a compute shader. It is OK but there is some issues there.
When I hole (dig a small just one voxel hole), stored water in the storage/tank, only some portion of water can leak then it stops. Do you know the reason?
It seems the voxels are settled
Do you know the reason
Absolutely! I would say there's a bug in your code.
is there a way to require all of the methods of a specific interface, but not allowed that interfaced to be found by other objects with GetComponent<Interface>()?
No. This also sounds like an xy problem, what are you actually trying to do?
Im currently coding a networked game, and certain things the player can react to, like being slowed, damaged, thrown ect. To prevent duplicat code, i have a script which has the code to handle all of these things, and I dont want these to be called directly, rather a separate script to call these, because when in online mode, I need to tell the server to do these things, while in offline mode, i can simply just call them basically.
im new to this stuff so if theres a better way id like that lol
hmmm.... maybe i could split every interface into a grabbable and ungrabbable ver? then if i wanted to require certain methods I could inherit from the ungrabbable ver???? would that work?
would that be practical?
I'm no networked game expert, but personally I think I would try to make it the same code path. Why can't you run a local "server"? Your way sounds horrible to me
Usually, you still use the network library in Offline. If you really want, you could try to use Precompiled, Reflection, Partial and/or Code Generation. You would probably be able to do something that is mostly transparent. However, that would definitely cost you implementation time and, depending on the implementation, performance at runtime.
Also, if you have reusable Network Code, you can opt for the usage of MonoBehavior (By example, sync Transform), the usage of utility function to reduce the boilerplate code down or even the usage of Composition with something like a NetworkVariable.
In this documentation, what does it mean to "Never have Unity serialize duplicate data or cached data"? Can anyone gives an example?
It's just syncing problems
If you change the type it might not deserialize anymore and thus cause errors
good morning
where can i ask something releated to using mysql inside my unity project?
i can get working update, insert get etc... but im trying to manage case then but something is wrong
i want to check if player make cheats and set player.score to higher number then set to 0
Why are you trying to do the check in the query? Check the score before running it
yes, i have the code before
but if i know before to run the query, my score is differnt from 9999 then how can i exclude to update player score or what is the best approach?
I don't understand what you're saying and I don't know what programming language you're using there but the idea is this:
if(dtplayer.score == 99999) {
score = 0
} else {
score = dtplayer.score
}
"UPDATE players SET player_score = " + score
Awesome yea sorry this example was fixed
but i got another case, where i need to set a column to null if this score is 9999
i cannot set to 0, its hard to explan, then i need to use "case" sintax
Even harder to advice if you can't explain the problem
I will try to make an example inside the code, thanks so much
You need to elaborate on "something is wrong"
Because I need to set to null the value no to 0
Yea I know sorry
Btw, you should parameterize your query to protect against SQL injection.
what is duplicate/cached data? Does it mean runtime temporary data like a local variable in an if block?
This is what I’m trying to reach with chat gpt or using doc but all time says my sintax is wrong
I cannot find an example to do it inside my unity class
I can manage update get etc but using a long sql query
ok i have to go thanks anyway i will show you later my full code to check if my sintax is fine, at this is not lol
I would strongly suggest you to get comfortable with navigating documentation and not rely on ChatGPT.
thanks so much
Does anyone know of a ShaderLab parser library that would be good for writing a converter? An HLSL parser with include support might also do the trick.
I don't remember now, there was an issue with ?? operator not working with NULLS properly but i dont remember the details. Does this work 100% of the time?
combinations[i] = combinations[i].Zip(cellCorners, (combinationCorner, cellCorner) => cellCorner ?? combinationCorner).ToArray();
(cellcorner and combinationcorner are monobehaviours)
?? will only recognize true null. When a Unity object is destroyed, it will pretend to be null by returning true when you do object == null, but it's not actually null.
So this will only work if cellCorner is actually null, like if you set it to null or it's unassigned. Note that an unassigned serialized field will still have a fake object assigned to it, at least in the editor.
Anyone ?
is there a pre-existing package which wraps the native collections like NativeArrays into ordinary C# classes, such that they are disposed when the C# class would ordinarily be finalized / garbage collected?
private class OrdinaryByteNativeArray
{
public NativeArray<byte> bytes { get; }
public OrdinaryByteNativeArray(NativeArray<byte> bytes)
{
this.bytes = bytes;
}
~OrdinaryByteNativeArray()
{
bytes.Dispose();
}
}```
is this a sufficient implementation?
supposing the bytes were always persistent allocated
I would use IDisposable and using statements rather than a deconstructor. You have very little control over when an object is garbage collected, it's not recommended: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/finalizers#explicit-release-of-resources
you could use a finalizer still as a backstop but IDisposable and using are much more predictable
Why not put it in ondestroy? Unless your class is runtimeinitializeonload then your monbehavior creates native array in awake or start (or other class that use native array) then free it in OnDestroy (or dispose the class)
Warp a native array can result on heap use after free, though unlikely to happen
Just for native array, if you wrap other dynamic buffer (hashmap, list, etc) then you will get an additional double free error in your implementation (only get but no set)
Hey guys,
I'm working on a JSLIB and am wanting to return a string after awaiting my JS function, however it only returns null as I assume Unity C# doesn't work async with the JSLIB?
JSLIB:
ConnectAccount: async function() {
if (window.ethereum) {
const accounts = await window.ethereum
.request({ method: 'eth_requestAccounts' });
var TestString = accounts[0];
var bufferSize = lengthBytesUTF8(TestString) + 1;
var buffer = _malloc(bufferSize);
stringToUTF8(TestString, buffer, bufferSize);
return buffer;
} else {
console.error('MetaMask not found. Please install MetaMask or enable it in your browser.');
}
}```
This should return a string of '0xSomeAccount'
**C#:**
```csharp
[DllImport("__Internal")]
private static extern string ConnectAccount();
public void RequestAccount()
{
string test = ConnectAccount();
Debug.Log(test); // Returns 'Null' instead of '0xSomeWallet'
}
Does anyone have experience with this and am willing to point me in the right direction?
{
bossHealthBar = FindObjectOfType<BossHealthBar>();
switch (scriptType)
{
case ScriptType.First:
if (firstScript != null)
firstScript.bossBarUpdate += bossHealthBar.UpdateFillers;
break;
case ScriptType.Second:
if (secondScript != null)
secondScript.bossBarUpdate += bossHealthBar.UpdateFillers;
break;
}
} ```
So, this is a script that is kind of an interface class between 3 scripts, BossHealthBar, firstScript that handles a type of enemies, and secondScript that handles another type.
It's giving me the following exception upon construction:
` ArgumentException: Value does not fall within the expected range. `
Knowing that first and second scripts can be turned off when this gets constructed, what could be a solution to it?
Note: the exception is given on the line where the events subscribe.
I remember this error is due to no case is matching the variable in switch
That's odd. The variable scriptType is being determined in the editor, so that might not be the case.
I don't think you can use async feature from separate language interchangeably. You'd need to separate the API into a request, state check and result retrieval.
i have a question about ml agents if anyone has time for that
And also, the subscription is being executed.
Maybe i am wrong
Which one?
Can be both, depending on the type.
What's bossBarUpdate and UpdateFillers. Can you share the implementation?
Currently no. But I can share a description.
bossBarUpdate is an event instance of a delegate BossBarUpdate, that takes one integer as an argument and returns nothing.
UpdateFiller is a function in the BossBarHealth script, that also returns nothing and takes one integer.
I'm sorry. On my way to university, and don't have access to my laptop.
Does it work of you change the UpdateFiller type to BossBarUpdate?
You mean the return type of the function?
1 sec. I'll try to write the whole thing down from memory.
Ah sorry, assumed that UpdateFiller is a delegate too
Check if your delegate signature matches the method in terms of accessor(public/private)
Here's an outline of the scripts:
{
FirstScript,
SecondScript
}
public class BossHandler
{
public delegate void BossBarUpdate(int hitPower);
public ScriptType scriptType;
public FirstScript firstScript;
public SecondScript secondScript;
private void Start()
{
bossHealthBar = FindObjectOfType<BossHealthBar>();
switch (scriptType)
{
case ScriptType.First:
if (firstScript != null)
firstScript.bossBarUpdate += bossHealthBar.UpdateFillers;
break;
case ScriptType.Second:
if (secondScript != null)
secondScript.bossBarUpdate += bossHealthBar.UpdateFillers;
break;
}
}
}
public class FirstScript
{
public event BossHandler.BossBarUpdate bossBarUpdate;
public void HurtInAWay(int hitpower)
{
bossBarUpdate.Invoke();
}
}
public class SecondScript
{
public event BossHandler.BossBarUpdate bossBarUpdate;
public void HurtInAnotherWay(int hitpower)
{
bossBarUpdate.Invoke();
}
}
public class BossHealthBar
{
public void UpdateFillers(int hitPower)
{
// Updates health bar fillers.
}
} ```
Thank you for the reply!
Do you have any resources on how to accomplish this?
Can you not just make that function synchronous? I think it would have the same effect.
I tried, but Unity C# has no chill haha.
So what happens when you call the function in WebGL is this:
-
MetaMask extension pops-up and asks you to select an account to connect to the current window.
-
Once connected, it returns the connected address or address[0].
The problem though is that for some reason, Unity immediately returns the buffer instead of waiting for the response from the JS.
Try using then and catch and return different values depending on the result/error.
See if it waits until the results are actually ready.
window.ethereum
.request({
method: 'eth_sendTransaction',
params,
})
.then((result) => {
// The result varies by RPC method.
// For example, this method returns a transaction hash hexadecimal string upon success.
})
.catch((error) => {
// If the request fails, the Promise rejects with an error.
});
Ah, maybe not
async methods return Promises. you do not have to await them. you can call a c# callback in a .then(() => { ... }) handler
well there it is
Yeah, you should probably be Calling Unity scripts functions from JavaScript
https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html
Iiiinteresting!
So I could essentially add the account to a variable in JS 😮
Lads thanks for the help! I'll have a go at these recommendations 🍻
Not sure about that. But you wouldn't need it as long as you call the unity script from within that same js function(after awaiting/within the then/catch)
Will give it a go 🙂
I'm trying to make a map renderer thing, whats the best way to do this? I have a big 2d array, and some lights that have a point, radius, intensity 0-1, and I want to cast some rays to set lighting values, then put it into a channel (lets say red) so I can use that later. image included for a bit of explanation.
should I go thru every pixel and check lights? Im assuming just shooting rays from every light would be fastest but wouldn't they spread out and miss?
Ray tracing…
yeah im crazy
In 3D computer graphics, Potentially Visible Sets are used to accelerate the rendering of 3D environments. They are a form of occlusion culling, whereby a candidate set of potentially visible polygons are pre-computed, then indexed at run-time in order to quickly obtain an estimate of the visible geometry. The term PVS is sometimes used to ref...
thats 3d though is it not, I just need to raycast my 2d grid of pixels
this only needs to run once btw, so I'm not too worried about performance or computation time
2d is just 3d without one axis, but the algorithm should be similar (even much faster/easier then 3d version)
I think it can be computed by fragments shader using z buffer at real time but i have no clue how to write it
would that be able to compute it then give data back so I could write to an image?
i know compute shaders can do stuff like that right (not that i've ever used them)
There should be some ways to retrieve the frame buffer back to cpu
If there is, that is really not recommended
just an brute force way to pre compute the pixels
ofc another way is to find out all triangles visible to light source->rasterizer->compute all the pixels, but still look like gpu stuff
I mean I would probably just precompute a bunch of cells in the level then only check whether those cells are visible
Rather than trying to find every pixel
it depends on whether the cells is "small" enough for sampling etc ('L'=light source, 'A'=air, "W'=wall)
LAAAAAAW
AAAAAWAW <--
the "top" of rightmost wall in second row should be lighted up by light source but if you just line cast you may get wrong result, better solution is still treat it as mesh and continuously value in 2d plane
Minor errors are often fine in these kinds of systems
Even in competitive multiplayer systems
Better to have high performance rather than perfection
I am now testing the ability to send Json data to the AWS DynamoDB via the Lambda function to POST, and the error Error: HTTP/1.1500 Internal Server Error keeps occurring. What is the cause?
Internal server error
Check AWS logs
Thank you for response, but it's already been resolved.
Any best practices for using fonts (w.r.t prefabs) in Text Mesh Pro?
Consider I need to use multiple fonts with different sizes. Do I need to
- Create prefabs for each different size? (or this is a overkill)
- Create prefab for each different font?
Size of the font and rect transform size are variable in most cases. So linking those to prefabs sounds odd. But would like to know how usually the fonts and prefabs are handled.
Use the size parameters on the TextMeshPro. You could use a single prefab if you really want so that you are able to edit every TextMeshPro at the same times, but this is not really necessary.
Wow Unity. Why is UnityEditor.BuildTarget not compatible with UnityEngine.RuntimePlatform? I want to store some information about my build, and I can into the problem that UnityEditor.EditorUserBuildSettings.activeBuildTarget returns a value that cannot be properly mapped to UnityEngine.Application.platform.
if I have a long running blocking task that uses Unity API, and I want to spread it across multiple frames, there is no other choice other than unity coroutines, right ?
I can't make it an async task in this case ?
async/await, Task.Delay would work for waiting a frame at least
Or are you saying you cant use Task here?
from what I see it doesn't
awaiting a Task that uses blocking unity calls blocks the unity thread for the whole duration of the task, Task.Delay or Task.Yield between the work batches don't suspend the task
Just don't await it from a non async place
Well wdym by "blocking unity calls" exactly?
I do await it from an async void entry point
in this particular case it's a bunch of compute shader dispatches
but I checked with something simple, like 2 loops with a dummy calculation, with a Task.Yield in between
https://gdl.space/oqeriweyed.cs
the simple test case I tried, it halts the rendering and then outputs all the test messages in one go
Your problem is that the for loops are not async
Those are blocking main thread operations
Typical async in Unity is not running on a background thread
I expect loops to be blocking, I want to render a frame in between them, so work is spread between 2 frames
as far as I understand It will work with a coroutine, right ?
yep, just tested with a coro instead and it does render a frame between the loops
I'm working with some deep-linking between two full-screen mac apps.
Deep-link from App 1 to App 2 works fine when app 2 is closed and it steals focus appropriately.
When either I try to link back to App 1 or try to go from 1 to 2 again, it fires the link, but doesn't take the focus off whatever app is currently shown.
Is there a way I can force steal focus or something?
are you perhaps using unity 2023?
I am
oh wow
big thanks 🙏
Usually, you use preprocessor directives. You can also use Application.platform, however the other method is to be privileged.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives
https://docs.unity3d.com/560/Documentation/Manual/PlatformDependentCompilation.html
Task.Yield isnt the same as yield return null is the problem
yeah box hooked you up
They don't unfortunately. With CustomYield instruction, they can
your issue here is that you're using Task.Yield.. scratch that
why would Task.Yield not work there?
What do you mean 'they don't'?
it doesn't respect Unity's gameLoop
or frame timing
it reliably waits one frame due to how the synchronization context works, at least in my years of experience using it
they're not reliable. Thus they came up with Awaitable api in 2023
If you need to wait just 1 frame you don't necessarily need anything fancy
wat?
I'm saying that an async Task with 'Task.Delay(1)' will work just fine for waiting 1 frame

in what ways isn't it reliable? in what ways are the effects actually different? i'm not trying to prove you wrong, i've just never encountered a situation where there was any difference
What's the problem?
yeah, I replaced it with the Awaitable.NextFrameAsync
Anyway yeah with 2023 might as well use awaitable
I don't think this works on WebGL
while it did work for the test case, it didn't help with the actual use case, but I'll keep digging
yeah, Task.Delay using threading/timer stuff in the background, you might as well just yield a frame anyway since most frames are longer than 1ms
Async/await works on webgl.. if you're not doing Task.Run() or offload it to threadPool you should be good.
Regular await by default will use current context
Or other Task APIs that rely on threading, which waiting APIs have a tendency to do.
UniTask is a safer alternative for this
it should be noted, you can still use Task.Run or threadPools but the caveat here you must use ConfigureAwait(true) which may cause deadLock
on webgl? i'm pretty sure that's not true
continuing on the current context is the default regardless of platform anyway
in the case of Task.Run(), no they don't, where did you get this info from?
ConfigureAwait affects how the continuation runs after an await, that doesn't affect what Task.Run does at all
it should affect it, I mean, you're not in Unity's lala-land anymore, so how can you get back? 😅 ...
Task.Run runs something on a worker thread, if you await anything inside the method you're running there, it'll just continue on the same worker thread unless you use ConfigureAwait(false)
I mean did you read that ? 👆
well i asked if that was about webgl still?
oh yeah, I meant Task.Run in general in Unity was not specifically to WebGl
so you're correct here
webGl will just nope out
Deep Link Mac OS Between Two Apps
Was making a simple test.. See how Task.Yield gets executed twice at the very beginning of execution
Need to run this test couple of times to successfully reproduce the issue
see the almost identical code between async and coroutine on the inspector
tagging @untold moth as we had the same argument regarding this the other day iirc (sorry for the ping!)
Lol, I was just trying to understand what the argument is about.
So why does it print the same frame twice? Is it executed later in the frame?
simply bcos Task.Yield does not respect Unity's gameloop, it doesn't care what frame it should be executed
Just don't use Task.Yield if you don't want a buggy code..
Damn I was using it for several years and never noticed.
FWIW Task.Yield doesn't really "do" anything unlike Task.Delay, it's more about how the unity synchronization context behaves
i guess it runs twice in the first frame because the synchronization context updates after Update in the player loop? otherwise i think you can count on it to run at a 1 frame interval on every subsequent frame because unity doesn't update the synchronization context more often than that
Task.Yield was originally made so when you do longrunning ops in UI thread (Winforms/wpf ) it will not block the thread. Just that
sure, it doesn't actually do anything specific to winforms or wpf though, and you can observe that it works fine with the unity context
Another neat trick with Task.Yield is that it you can avoid StackOverflow exception on a recursive function.
{
await Task.Yield();
await Foo();
}
Meanwhile await Task.Delay(1) will still throw StackOverflow exception
(I've seen this used in production with my own eyes
)
seems like a bad idea in either case
Something like prefab per font would be good?
Not really.
I decided to rewrite that long Task into a chunked processing from the Update
because Awaitable.NextFrameAsync also couldn't yield to the render thread, it runs the whole thing to completion
in a test case NextFrameAsync does work though
maybe something to do with compute shader dispatches preventing any yielding behavior
Text mesh pro best practices for font prefabs
anyone here got ever mouse control working on a nintendo switch?...
I have a scroll rect with a content panel that I'm plopping down icons for each level.
I know the y location of the icon in the scroll rect.
I want to add a "back to the current level" button that "punches" the scroll rect and makes it land near the current level, accounting for inertia.
Anyone have an ideas how to accomplish this? I didn't see any API in the scrollrect component itself that would handle it.
https://docs.unity3d.com/2018.2/Documentation/ScriptReference/UI.ScrollRect-normalizedPosition.html
You have to divide the levels y position by the total height of the scroll rect
I mean, I can do that, that's what I'm already doing.. but I was hoping to get a nice animated effect
it feels a little janky to just snap it to the current location
(I suppose I'll just tween it there and disable all my parallax stuff while the tween is running)
use Vector2.Lerp()
or..... tween it. :p
Never did the "mouse" control, however I've done the Joycon, Handled and Dual Controller with Rewired fairly easily.
Hello guys, quick question is anyone already used the facepunch.steamworks dll for Unity ? And if so did you used the leaderboard features ?
I think this is more on the advanced side, I'm making a note taking app and I want it to be able to have features like list making (like you've seen in apps like Word) or like adding shortcuts and just generally changing the text input field that comes with Unity to have more complex functionality
I have no idea where to start and every single thing I think of seems inefficient and dirty, like checking if a user presses enter and manually adding those dots for the user and manually adding spaces it just seems weird
Unity is not made for such application.
Here a list of other development framework that might be more suitable: https://kotlinlang.org/docs/cross-platform-frameworks.html#xamarin
(Note that the source could be bias)
Regardless of framework, unless you are using a component that has these features built in, you are going to have to write low level logic like "when enter is pressed, insert - with the correct amount of leading tabs/spaces"
They aren't "dirty," you just don't tend to work that low level in most projects (and especially not in a Unity project)
There are also software like Obsidian that solves note taking already.
But yes Unity is a game engine, you'd have much better time using something else.
I want to figure out how to turn a big 2d array of pixels into a polygon collider 2d for my map editor (its a dev map editor btw), I could just use a tilemap collider and read from image manually but I want it to be a little bit smoothed (to ease physics, so the player can walk up a slope instead of it being jagged). I think I would need some kind of triangulation algorithm but I'm not entirely sure where to start (i also don't need internal points because polygon collider handles that already)
I know Noita did like exactly the same thing where they get a group of pixels as some triangles for collision
So what have you done?
well i have my 2d array of pixels sorted
the issue is they can in seperate 'groups' which might complicate things
i think it is some variations on convex hull but i am not sure
i think no matter what algo i would have to separate into groups somehow
I’ll rewatch that one Noita talk and see if i can find out what they used
What if its a concave shape :/
Yeah
I might have to like
Split it up
Or find all exposed tiles and use those maybe to find all outlines?
If i find all exposed outline things could I just like line-of-best-fit it and have my points be those
Wait does polygon collider 2d even support like donut shapes uh oh
I would have to use line colliders then
each tile can be treated as 2d rect in 2d plane, so you can directly get the x y coordinates, four for each tile
Yo so I am doing some networking stuff and every fixed update the clients sends it position and reads all inbound packets. What would be the best way to use lerp so that the player has been smoothly moved to the correct location in time for the next one? The time step is 0.2.
i think you can introduce some parameter and modify convex hull algorithm, lets say if the angle between two edges fall in some specific ranges then reconnect to make them one edge eg:
A A
X X
X X
XAX
give up the A in the middle and use two A on top
but you need to scan all vertices in each iteration
or compare the result with the actual convex hull, i think this should be better
If you're planning to publish this for mobiles, you may out of luck.
Any games/apps that are made with Unity can't be used as background service on mobiles, meanwhile note-taking app ideally should be able to run as background service, so when a user put your app running in the background while doing something else, your note-taking app will still be running normally hogging lots of resources.
it's a bad idea
im trying to displace vertices on a mesh with perlin noise to generate a "planet like surface". but i don't know how to make the noise align with the "shape" of the circle if that makes sense. currently it's just in this weird 45 degree angle.
Rather than using Cartesian coordinates I would use polar coordinates. I.e. the input should be the angle. Use the angle as one dimension in the noise function (keeping the other dimension constant) use the noise output as a modifier to the radius at that angle. Does that make sense?
Though what you have now would make a cool comet ☄️
yeah i was thinking of something like that
Anyone know How I can get this script to picka random point to spawn in a sphere shape? right now it spawns randomly but the spawned objects are horizontal line
https://pastebin.com/7RwJrhNw
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.
Are you using an orthographic camera or looking at them from along the z axis or something?
Your code should make something like a circle shape on the x/z axis right now
you set position.y=0.....
but viewed from a certain angle that might look like a horizontal line
Yes looks like this
Basically all objects are on the x axis
that's not a line
that's a circle on the x/z plane
which is kinda exactly what you are asking for with y = 0
horizontal "plane"
That's what i meant
what exactly do you want if not this?
if you want in a sphere just get rid of the y = 0 part
// Ensure objects spawn at ground level.
randomPosition.y = 0.0f;```
this
Think of a semi circle , I want to spawn randomly inside the semi circle.. I.E in front , behind and above me when looking around
so you want a sphere, but just the top half of the sphere?
or you want an arc
(a circle, but only the top half of it)?
top hemisphere?
correct
Then instead of:
// Ensure objects spawn at ground level.
randomPosition.y = 0.0f;```
Do:
```cs
// Ensure objects spawn in the top hemisphere
randomPosition.y = Mathf.Abs(randomPosition.y);```
also do you want them all on the edge of the sphere or is inside the sphere also ok?
inside , is it giving me the edge?
i have a min distance so they arnt too close to the camera and a max disatance
Thank you
anyone know why roslyn source generators must depend on Microsoft.CodeAnalysis 3.8 und must target netstandard 2.0 in 2022.3? using generators for netstandard 2.1 works fine in 2022.2 ...
how to detect through code if a vfx is finished?
okay so basically tried your idea, it works great! but one issue, i can't get the pivot of the cartesian magic in the center of the asteroid, it's for some reason on the top center. (just put in some crazy values for demonstration)
I think you actually want to change:
float x = r * Mathf.Cos(angle) + transform.position.x;
float y = r * Mathf.Sin(angle) + transform.position.y;```
to:
```cs
float x = r * Mathf.Cos(angle);
float y = r * Mathf.Sin(angle);```
This is because the coordinates in the mesh are in local space. Plugging the world space position of the object into it doesn't fit.
even if i change this, it doesn't work. here's a picture of the wireframe if that helps.
i'm pretty certain that the cluster on the left should be at the center
Yep, I don't even think of mobile when developing games so this would be worse, I realized how different mobile is when I had to maintain 2 versions of my game, that was probably the worst time I've ever had programming. I've decided to learn WPF for this so it's for Desktop apps and I was able to learn REALLY quickly with the experience I have with C# in general
I think it looks ok. The wireframe looks like that because that's how you're triangulating it, attaching all of the vertices to the zeroth one. The other problem is you need to make sure you sample the noise function in such a way that you start and end on an integer in the noise coordinate system to make sure it loops smoothly ( so there's not that hard cut at the end)
Respected,
i have applied force on a gameObject with rigidbody.
But when I applied force in z-axis then automatically force applied on x-axis even there are no force can seen on x-axis in rigidbody component and even still force applied when I freeze the position x..
can someone please guide me how can i resolve the issue.
Thanks
Anyone know how I would go about building a headless unity build, with special compiler definitions? I already build unity as a headless instance for a server, but I need 2 different "types" of headless instances
the second being a special type of player
You use #if MY_PREPROCESSOR_DIRECTIVE.
yea, but specifically trying to conditionally define these based on a cli argument
Ahh thanks that's what I'm looking for! :)
Was wondering if anyone had some advice on an issue I'm having (might be a memory problem). I have an isometric tilemap. And the function that is giving me trouble is the following situation: I have a button that takes in some data, and then calculates and updates the isometric tilemap. The issue I am finding is that there are 4 of these buttons, and the intent is that you can click one, itll clear the tilemap, re-evalute then display the new info.
My issue is that after about 4 button presses, the game slows to a crawl and basically crashes.
Any thoughts? I have checked that the tilemap is being cleared and updated properly
My thoughts can be anything when there's very little to go off of assuming this is all custom code.
If you're having performance problems you need to start with the profiler.
that is valid
As stated by others, you gotta use the profiler
sadly i am not familiar with viewing the profiler
like i know how to open it up
but viewing it is something entirely different
There's detailed documentation on how to use it. If still confused about something, share the profiling data here(like a screenshot) and ask your question.
Found the issue lol
but no clue how to solve it
its some memory issue
when i press the buttons and get up there, the memory on my computer went all the way up
What does the profiler say?
lets see if i can get a screen shot before unity crashes
ok i saved it after i pressed it enough to not crash but is like
feeling the burn
is there anything specific that would help you help me
I mean, what exactly made you think it's a memory issue..?
the fact that when unity was frozen
i had to go to task manager
and saw my memory at 95%
Ok, well, with profiler you can see the memory allocations. Select a frame with most allocations and take a screenshot of the hierarchy mode in profiler.
i think you are referring to this
i apologize, this is one of the sections of unity ive never dabbled in
I don't see any abnormality on this frame. The last frame in the graph seems to go up the processing time, so might want to look at it instead.
As for working with the profiler, look at the documentation. It's not that complicated.
see i dont see why the processing time would increase with each button call
unless im doing something very wrong
wait dumb high level question
the brain is firing
if i create an onClick listener
you are allocating more and more objects each time you click?
does it create a thread that needs to be closed?
no
That's why we're looking at the profiler. But there's no point looking at the wrong frame.
the code in question btw, at least what the button invokes is the following:
it just takes in a scriptable object from a class, and then the show___Range is just a function that edits the tilemap
what do all those showSpellRange etc functions do
but i figured clearing the tilemap would destroy the objects
You do seem to be allocating new Lists all the time at the very least
show___Range basically does some cacluations in a loop
to determine what the tiles that are in range of the weapon, spell or ability are
a loop over what?
maybe show that code
also how are you storing these tiles etc
and what does ClearAllTiles() do
this is the longest and the shortest because it depends on the scriptable object
according the to documentation, it clears all the tiles that are on the tilemap, and then resizes it to its default value
the tiles are mainly stored in a list of tiles that get referenced elsewhere
ok i wasn't sure what type we were dealing with
didn't knwo that was a Unity Tilemap
use !code to share code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
sure i can use that
This is the self spell version, since the only tile it needs to highlight is the one that the character is standing on since its the only valid target
public override List<GridTile> showSpellRange(List<GridTile> movementTiles, GridTile start, int movementRange)
{
List<GridTile> attackTiles = new List<GridTile>();
attackTiles.Add(start);
CursorMovement.instance.attackRangeTilemap.SetTile(start.gridPosition, CursorMovement.instance.friendlyTile);
return attackTiles;
}
I can see that you are creating new lists constantly
this is really bad for performance
that could be it then