rudderstack offers a unity SDK
https://www.rudderstack.com/integration/apache-kafka/integrate-your-unity-app-with-apache-kafka/
#archived-code-advanced
1 messages · Page 108 of 1
if that fits your needs
a relatively generous free tier of a million monthly events
Do you have anything in mind for the middleman web service?
Yea i checked this out but wasnt sure if it was the best approach, although it might be the easiest one
I see, thanks
I plan to write json data to a file in unity and then have it read from the producer which will send it to a kafka topic
i'm looking to hack into https://github.com/Unity-Technologies/Graphics/blob/master/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipeline.cs#L1400
I want to update that cameraData.renderScale to be always based on lets say "640x320". Current that value is being calculated as a percentage of the players screen resolution. Is it possible to override this cameraData from a custom render pass/feature? I can see you can at least read it from
public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) {
UniversalCameraData cameraData = frameData.Get<UniversalCameraData>();
cameraData.renderScale = (.. calculated scale based on monitor resolution and hardcoded resolution);
// There is no way to "set" this data I think.
}
I'd rather not fully override UniversalRenderPipeline.cs ( is that even possible?).
Alternatively I can see in the "Render Graph Viewer" that there is a texture called _CameraTargetAttachmentA created, if i can resize that before the first blit it would also work I guess?
I'm trying to get a pixelation effect by rendering at very low resolution and then doing a point upscale. For various reasons I don't want to have a full screen render texture on a quad.
Any clue why my camera isn't taking pictures correctly? I made an extension method for the RenderTexture to Screenshot thing and the first image is how it looks in-game and the second image is the result. Any clues why this is happening?
I'm first of all confused about what's happening with the colors, but I'm moreso confused by the fact that it doesn't seem to be at the same position that the render texture is at? I made sure the transform is exactly where it should be so I'm just confused
I fixed the position thing but I can't figure out the lighting one
here is the render texture it generates
and here is the PNG
is it the color format?
Anyone has any idea what “Assertion failed on expression: 'SUCCEEDED(hr)'” error could mean? I’ve been scratching my head for the past 2 days… my drivers are all updated and I tried reinstalling unity/using different versions
It happens whenever I open older projects or create new ones
I have directx 12
which unity version is it? Have you tried updating to the newest LTS?
Some system call fails. Is there no more details?
That’s all that it shows
But it doesn’t affect the game at all
Maybe the log file hase some more unfo
Nothing pretty useful
As I saw online it has to do with GPU or smt
No idea tbh
Graphics API most likely, but not necessarily. Calls to system API(,or rather the result evaluation) would often look like that
I tried changing api in editor but nothing
The fact that unity doesn't provide any more info on that failure is a bit weird though.
No idea
Can you provide a snippet from the log file with a few logs before and after this message?
My pc is off rn it’s almost 2AM here
I’ll provide tomorrow
Unless I find solution
Anyways ty
does anyone here know how to handle tilemap transformation matricies? i'm attempting to import a tilemap from a godot game and i'm having trouble migrating the transformation properties that godot provides (allowing flip h/v and transpose)
this is where i'm at with my code so far. transposing works but none of the tiles are flipped horizontally or vertically
var transformMatrix = Matrix4x4.identity;
var scale = new Vector3(1f, 1f, 1f);
if (tile.flipH != null && (bool)tile.flipH)
{
scale.x *= -1f;
}
if (tile.flipV != null && (bool)tile.flipV)
{
scale.y *= -1f;
}
if (scale != Vector3.one)
{
Debug.Log($"{scale} (h: {tile.flipH != null && (bool)tile.flipH}, v: {tile.flipV != null && (bool)tile.flipV})");
}
transformMatrix *= Matrix4x4.TRS(Vector3.zero, Quaternion.identity, scale);
if (tile.transpose != null && (bool)tile.transpose)
{
transformMatrix *= Matrix4x4.Transpose(transformMatrix);
}
turns out that the correct answer was to just do the transpose operation myself
transformMatrix *= Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0, 0, -90), new Vector3(1, -1f, 1));
Hello. I'm making a 2d spider that uses its legs to walk. It uses 2d hinge joints. I know you shouldn't use transform.rotate with joints and rigid bodies, but it gives more precision than the chaos of using motor speeds with precise alignments. The weird thing is, it works well with the right side legs, but the left side legs, not so much. they seem to only rotate one way(not consistently). but I'm assuming its going out of the joint limits, hence the full rotation. I only manually rotate the transform of the "thigh" to align it to lock on to its next step target. The left legs freak out sometimes.
Vector2 footPosition = GetFootPosition();
Vector2 directionToTarget = (currentTarget - footPosition).normalized;
float aimRotation = 0f;
float targetAngle =
Mathf.Atan2(directionToTarget.y, directionToTarget.x) * Mathf.Rad2Deg;
float currentAngle = legSegment2.transform.eulerAngles.z;
float rotationSpeed = spiderController.rotationSpeed * Time.deltaTime; // Adjust the rotation speed as needed
float newAngle = Mathf.MoveTowardsAngle(currentAngle, targetAngle, rotationSpeed);
legSegment2.transform.rotation = Quaternion.Euler(0, 0, newAngle);
Hey, im back, i tryed to uninstall all the packages, and the error is still there, except for the 4 with installed as dependencies, i can't remove them to try ( i think )
I was not talking about packages, but plugins. Like firebase. These shouldn't appear in the package manager.
hoo mb
how should i do ? i try to build after deleting folder by folder with stash on github ?!
You can start by looking for "Plugins" folders in your assets and researching them online.
i start to check them on internet to understand what they do, and see if i see some things to configure them correctly and check that, then if i didnt find, i try to delete them one by one ?
Something like that yes
thank you
Is there another method, because I'm having trouble doing this one because of the dependencies
Hey all,
Anyone knows how should I start implementing fishing line physics like what it is in Red Dead Redemption 2 ?
Does anyone know what persistent malloc is? accumulates a lot of memory in the memory profiler
malloc stands for memory allocate, give you a clue?
I Know what is malloc,but i dont Know why if i clear memory with thé garbage collector
Thé alloc stacks
How exactly works malloc in Unity?
pay more attention to how much resident memory things take up. Allocated memory is only one part of the story and less important to optimize than resident
malloc allocations are not garbage collected, they are C/C++ memory allocations not C#
I already pointed out to firebase several times, since it's probably the culprit. So start from checking it first.
Where do you see that? Does it actually say "persistent malloc"?
Memory profiler
Can you take a screenshot?
Lots of native code systems use this memory
Things like physics, navmesh stuff, etc
Doesnt deep profiling also show you what part of your process is allocating?
Use the hierarchy view instead of the timeline view you have now
Click "timeline" on the bottom left
As it says, it's part of the unity subsystems, so there's not much you can do about it. Though unity could've provided a better job at describing what it's used for.
Only one thing though: are you profiling a build?
Also, what are you actually looking for? Optimizing the memory consumption or performance?
yeah i do, when i build and run my game, the star memory usage is 300 or 500 mb, but when i star moving and charging chunks, (my game is 2d sandbox) the memory start stacking and i dont know why
Are you using native arrays or buffers or something similar that allocates unmanaged memory?
only use list, not native arrays
Lists of what?
And I'm not talking about regular arrays, but native arrays. There's a difference
gameobject list and two-dimensional arrays to store block data
These should be in the managed memory
two-dimensional array? but i use myarray = null; and destroy any object inside this
It's really hard to say what's going on, without having a grasp of your project.
Point is, it's not what malloc persistent is.
In my code I do not use malloc, in fact and implemented the IDisposable interface
to dispose block class, chunk class,
Are you using any third party assets or plugins that could be allocating memory?
So regarding what I eventually did - it was enough to just replace my UnitGroup script with a ConcurrentUnitGroup which uses the ConcurrentDictionary internally. What's nice about this is that I can do all the fancy management that I want on worker threads while the main use of the class continues to operate on the main thread. It ended up being super simple. Here is a working skeleton of the class: ```cs
using Sirenix.Utilities;
using System.Collections.Concurrent;
using System.Linq;
public class ConcurrentUnitGroup
{
ConcurrentDictionary<int, Unit> dict;
public ConcurrentUnitGroup()
{
dict = new ConcurrentDictionary<int, Unit>();
}
public int Count { get { return dict.Count; } }
public delegate void UnitTransactionAction(int unitId, Unit unit, ConcurrentUnitGroup group);
public event UnitTransactionAction onUnitAdded;
public event UnitTransactionAction onUnitRemoved;
public void SetSingle(Unit unit)
{
if (dict.ContainsKey(unit.id))
{
var keysToRemove = dict.Keys.Where(key => key == unit.id).ToList();
keysToRemove.ForEach(id => TryRemove(id));
} else
{
Clear();
TryAdd(unit);
}
}
bool TryAdd(Unit unit)
{
bool result = dict.TryAdd(unit.id, unit);
if (result)
onUnitAdded?.Invoke(unit.id, unit, this);
return result;
}
bool TryRemove(int id)
{
bool result = dict.TryRemove(id, out Unit unit);
if (result)
onUnitRemoved?.Invoke(unit.id, unit, this);
return result;
}
public bool AddSingle(Unit unit)
{
return TryAdd(unit);
}
public void Clear()
{
dict.ForEach(entry => TryRemove(entry.Key));
}
public void IssueCommand(int id, SelectionTarget target)
{
dict.ForEach(entry => entry.Value.IssueCommand(id, target));
}
}```
Or use jobs/compute shaders or something else that is close to low level.
i dont use any plugin or asset, the only thing that i make is creating and destroying blocks
Well, then there's nothing explaining the growing native memory consumption
i dont know XD
courutines?
ienumerator can consume memory?
No, none of that would be making native allocations.
As I said before, native arrays(or other collections) and potentially compute/graphics buffers. So anything that might be using these is the culprit.
Did you actually make a memory profiler capture at different points of time to make sure that this specific memory allocation is growing?
Or what are you basing your assumptions on?
i make a snaptshot in diferent times of application, look
The more you explore the world, the more memory they consume.
What does it look like in the first snapshot?
Are you using UnsafeUtility anywhere in your code?
no
Well, then no clue. Might want to post about that on the forums.
Maybe show your implementation. Setting the array to null will not free it if it's still accessible.
Or create test scenes with limited functionality/features to see which objects/features are the underlying problem.
this is my method
Just to be clear, if width is 10 you'll be destroying blocks -10 to 9. Is this your expectation?
Same with height
the methods normalizecoordinate take negative values to translate to array column and row
What's the purpose of normalizing the coordinate?
When x is -width, the normalized coordinate would be 0.
When x is 0, the coordinate is 0. 🤔
when i walk 300 blocks this happens XD
oh normalize coordinate is because i wanna build terrain left to the right
and sometimes i wanna find my object in the array
using his global x coordinate
I understand what your intentions are but I'm not sure if you understand that when x is -width it'll produce the same outcome as when x is 0.
Looks like a waste of processing power as your calling destroy twice on the block
but if i use 0, the chunk is builded from the 0 to the top
from bottom left to top right
i wanna build all chunk to left to the right
oh, Block is the class that storage my block data, IBlock is the MonoBehaviour script
i destroy twice
that why i destroy my block class storage
and my block class MonoBehaviour
and the gameobject
active blocks
So just for simplicity purposes let's assume you've got a 6 chunk world (linear) that ranges x: [-3, 3). Evaluating a single axis only (x, width)... Destroying the (-3, 3) would yield the normalized (0, 3). Since you iterate this and also destroy element (0, 3) as well, there's some redundancy and you may even be possibly skipping or missing half of the elements - very highly possible that you're getting unintentional memory leak (relative to blocks not being freed/destroyed)
my gamobjects are destroyed, when i search my blocks in memory profiler i dont find blocks or IBlocks with null references
And likely you're referencing null but have not freed/destroyed the actual elements
I'm only stating that with 6 elements, you'll be destroying blocks (relative to x): 0, 1, 2, 0, 1, 2
where the first three numbers were derived from the negative values
relative to (int x = - width; x < width; ++x)... x => normalized where x = -width and width = 3 using the formula coordinate < 0 ? width + coordinate : coordinate -3 => 0 -2 => 1 -1 => 2 0 => 0 1 => 1 2 => 2
oh, i wanna try making thiis
im gonna take a snapshot to compare
How are you handling updating the chunks/deciding when they're going to be released? It could be that you have some hanging chunks that you forgot to release and/or can't reference anymore
Also this is a good point, if you want even distribution of points(? blocks?) from your center you need an odd number of them. That's why I suggest you start from zero instead so you can get an even number(potentially a power of 2). A chunk size being a perfect power of two will definately help you down the line.
Why doesn't this work? I'm trying to sample the player's pose based on an animation right before rendering the camera and it seems like part of it is working because it's rotating (since for some reason the animation is offset by 90 degrees) but the position is inconsistent like it's sampling different parts of the animation
I'm using it to pose the character for these icons, and as you can see, the player isn't in the exact same pose in every icon
I'm trying to sample this frame
you can see I have the animation plugged in and it's not throwing any errors so I'm not sure why this isn't working
(also you can see that the hair isn't affected by the animation sampling for some reason. I assume it's because it's a child to the object butagain, it's rotating properly, just not doing the right position in the pose)
ProjectWindowUtil.CreateAsset(_newMap, "Map_" + temp_mapName + ".asset");
string path = AssetDatabase.GetAssetPath(_newMap);```
Why isn't this working? I'm trying to get the path of the newly created asset, it's probably trying to get the ``ScriptableObject`` I created...
Is there a way to look for an asset via the name?
GameObject.FindObjectOfType()?
That would look in the folders? Also, I'm looking for a very specific name (ie, the one I just created. I have a string (temp_mapName)
Wait... I'm a bit confused--what's wrong with using AssetDatabase.CreateAsset? Idk what ProjectWindowUtil is or its advantages
is there much different between using a List / Array vs unity's Native Array but use persistant allocation ?
Because every time i need to run a job im moving the same managed data to a native array (which is the most performance heavy part), so im thinking why not just put the managed data to a native array once and use that native array all the time and mark the allocator as Persistant ?
there must be a downside but docs dont really say much
No, but don't forget to free it
of course. 🙂
There is downtime in the editor for saftey checks but these aren't applied in build. Also those checks are very minimal, and managed arrays already do their own checks as well
just wanting to check if any one knows any gotchas with it before i go for it
Nothing, it just doesn't return a path, and I need a path this specific object for renaming reasons (This also creates a scene file but due to Unity being weird it won't let me name the scene file with ProjectWindowUtil.CreateScene()
But... aren't you saving it at a path you defined? Why do you need to query the path?
When you CreateAsset do you call AssetDatabase.SaveAssets() ?
you have to save first
it might help to show the code CreateAsset function
No, it just creates at the current selected folder path...
No, I did not
Don't you want the folder path? What path do you want here?
ProjectWindowUtil what is this ? i dont see it in the docs
is it your own thing
confused why you dont just use AssetDatabase.CreateAsset
Path to eternal life I guess...
@charred drum you'll need to explain a bit better what you're trying to achieve and what the current issue is.
I'm trying to create a Editor Window, that creates a Scene and a custom ScriptableObject, which names both files to the name (Plus a prefix). I would also want it to add it to the Scenes in Build thing, but I'll sort that out later (If it's even possible)
Develop once, publish everywhere! Unity is the ultimate tool for video game development, architectural visualizations, and interactive media installations - publish to the web, Windows, OS X, Wii, Xbox 360, and iPhone with many more platforms to come.
No, I'm on version 2022
I'm confused too
This looks like an extremely outdated API
that might be from a namespace not related to unity? maybe an asset or some api you imported perhaps
either way you should just use AssetDatabase.CreateAsset
I'd avoid using anything that's not documented at all in the modern docs.
You can create assets with the assetdatabase. I don't see why you'd need anything else
It has to be related to Unity, because this specifically creates a Scene file
you right it does exist but i dunno what that function is doing when i looked at the code:
[RequiredByNativeCode]
public static void CreateAsset(UnityEngine.Object asset, string pathName)
{
StartNameEditingIfProjectWindowExists(asset.GetInstanceID(), ScriptableObject.CreateInstance<DoCreateNewAsset>(), pathName, AssetPreview.GetMiniThumbnail(asset), null);
}
safe to say thats not what you want anyway based on that code
its undocumented so w.e it is they dont want us using it
I've already used CreateAsset for the ScriptableObject, but I'm not sure how you can create a completely blank scene with it
like this:
Scene newScene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);
string path = "Assets/NewScene.unity";
EditorSceneManager.SaveScene(newScene, path);
AssetDatabase.Refresh();
think its only possible from editor folder
Alr, let me try that
Ok, so what it does is it opens a scene with that name
But doesn't save it
you have to tell the asset database to save
once you save it, it should be in your asset folder
Oh wait no, made a typo
It works, thanks 🙂
string path = AssetDatabase.GetAssetPath(Selection.activeObject) + "/";
ScriptObject_Map _newMap = new ScriptObject_Map();
_newMap.Map_Scene = sceneName;
AssetDatabase.CreateAsset(_newMap, path + "Map_" + temp_mapName + ".asset");
Scene newScene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Additive);
EditorSceneManager.SaveScene(newScene, path + "Scene_" + temp_mapName + ".unity");
EditorSceneManager.UnloadSceneAsync(newScene);
AssetDatabase.SaveAssets();
Debug.Log(path);```
Here is my end code
But yeah, I have no idea what was going on with that ProjectWindowUtil. I was having a similar issue a while back, and that's the code people suggested I use
Either these people are time travelers from 10 years ago or don't really know what they're talking about and can't use documentation properly
I mean, it does work, I just can't rename the files or otherwise get the path
It does, but that doesn't mean that it's the correct way to do it.
Just another question, is it possible to add it to the Scenes in Build automatically?
If you look at the available classes in the docs, there's this one. It seems like you can modify the scenes list.
https://docs.unity3d.com/ScriptReference/EditorBuildSettings.html
Does anyone know if it's possible to render a ScreenSpaceOverlay Canvas to a RenderTexture?
https://docs.unity3d.com/ScriptReference/EditorWindow-hasUnsavedChanges.html
how can i trigger the opening pop up section without closing the window ?
do i have to implement custom popup and delete all sections about this structure
If it’s in the camera, it’s renderable to texture.
Yeah, it's ScreenSpaceOverlay so it doesn't use a camera, at least not one I can set the target texture of, was just wondering if anyone had some workaround/hack
I'm working on a system that heavily relies on generics, and I'm having some trouble integrating it with Unity specific stuff. Ideally, I'd have a generic MonoBehaviour and be done with it, but Unity doesn't allow it. So I have to create an empty derived class for every type I want to use with the generic MB. It's not too bad, but I thought it'd be nice if I could auto-generate those scripts. Specifically, I'd want to go through the sources, find every instance of class SomeClass : Generic<SomeType> and create a file SomeTypeMonoBehaviour.g.cs with contents class SomeTypeMonoBehaviour : GenericMonoBehaviour<SomeType> {}. Roslyn's source generators seem like the perfect tool for the job... except that they inject source at compile time, while Unity needs actual physical files so it will let me add the MBs to objects. So, my question is: how can I tell a source generator to save its files somewhere in the Unity project? Any help is greatly appreciated. (Note: I have done some research. I am aware of <EmitCompilerGeneratedFiles>, but I don't know if that's the way to go, nor how to inject that into Unity's auto-generated .csproj files, nor if Unity will care about it in the slightest.)
you could make a simple editor tool that generates the missing empty wrappers, via T4 or something simpler. Then you (and your users) don't have to deal with invisible black magic.
depending on your IDE, it can run the T4 for you
But then wouldn't I loose the benefits of using the Roslyn API? Finding which types need to be generated just from the source files seems like it'd be a pain
are you making something with signatures like this:
public abstract class AtomEventReference<T, V, E, VI, EI> : AtomBaseEventReference<T, E, EI>, IGetEvent, ISetEvent
where V : IGetOrCreateEvent, ISetEvent
where E : AtomEvent<T>
where VI : IGetOrCreateEvent, ISetEvent
where EI : AtomEventInstancer<T, E>
{
I don't really understand what you mean with that. As I'd said, I need to find some classes that derive from a generic class and create new classes that derive from a generic MB based on that
just curious, i have no idea how to make Source Generators produce convenient artefacts for Unity to pick up.
in the example signature above the problem is that when creating a new type one has to make ~15 of these empty wrappers you talk about, and making those by hand is annoying. So that particular library has a code generator tool in the editor that just generates them as a starting point when you implement a new type.
Using an editor script, you would just use reflection to find the classes/attributes/etc.
I don't think it's that kind of thing. More of a simple one liner to make Unity happy
I think someone asked a similar question awhile ago though, apparently ECS does something where it can magically generate a class that can be used in editor like regular components. You can search #1062393052863414313 forum to try and find that thread, not sure if it got answered.
The other alternative would be doing the reverse, so instead of "write class Internal and ask SG to generate class MB based on it" you would do "write class MB and ask SG to generate class Internal based on it."
And of course editor script would be the last resort (since it sucks that you have to alt tab from your IDE to Unity editor whenever you want to trigger editor script, have to wait for recompile, and pollutes version control with a bunch of generated artifacts)
its also possible to run such a generator in most IDEs
Sure, the other two points still stand though.
i think its somewhat weird to have a compiler produce artefacts that are inputs on its next compiler run...
They are not.
Source generated by SG does not participate in the next compilation, nor can they recursively generate from themselves. It's basically an added step to the compilation.
thats what im saying, its weird to work around that constraint and do it anyway
the SG emitter is for debug/validation/tracking/evidence
Oh I don't suggest to emit the files generated by SG.
That was talking about Unity editor scripts.
i've found it easiest to do that kind of thing (generating monobehaviours etc.) by running a T4 based generator in the IDE, off some reflection/static config. But thats probably not what the OP needs.
there is a GameObject based ECS from years back that requires such a generator step, that always felt quite heavy handed and broke all the time.
It's a trade off yeah, SG is notoriously difficult to develop and debug, but once you get it working it's really nice that you get immediate update within your IDE.
Is there a good way to detect whether a navmesh path is going to make use of a navmesh link, without relying on the NavMeshAgent class?
Well any path is based on some particular agent, no?
No, I've had to avoid using agents because I'm making a vehicle-based game.
Why does that mean you can't use an agent?
If I remember correctly, agents affect the movement of an object, don't they? It's been a while but I vaguely remember this being the reason I avoided them.
https://www.reddit.com/r/gamedev/comments/bq6c5d/deterministic_physics_dice_rolls_in_a_non/
This looks cool. I've got a question, though - in case anyone's done any sort of 3d physics based dice rolling. How do you prevent "infinite" situations? IE - dice tipped up against other objects, dice on top of each other, etc. Should I just put a cap on the time I sim, and if it goes over that cap, try a different starting set of "bump" velocities and directions?
This is a pathfinding script I was working on, and I'm trying to make it detect floors and move around, thing is- this worked last night but for some reason always returns true, even if the box shouldn't be triggered
Detection code:
Debug.Log(name + " - " + _frontFloor + " (@ " + Time.frameCount + ")");```
Debug cube:
```Gizmos.color = Color.green;
Gizmos.DrawWireCube(transform.position + (NPC_PathfindDir * (charcontroller.radius * 2)) + (Vector3.down * 2.5f), new Vector3(0.2f, 2.5f, 0.2f));```
``NPC_PathfindDir`` is basically ``transform.forward`` in this case
Oof - use string extrapolation, all that string concatention is hard to read
Debug.Log($"{name}:{_frontFloor} (@{Time.frameCount")");
checking the code tho, sec
The comment from the poster says they just simulate until it comes to rest. I dont really see how these unique situations affect much though, depending how you check what the roll is. I'd assume you compare each face with Vector3.Up so it being leaning against a wall wouldnt matter
Also, I'm using CheckBox instead of just raycasting so that way small gaps like, for example in a bridge, won't affect pathfinding
Yeah, I'm just concerned about wacky physics sims where the dice roll around and around and around.. Say the dice "move" for like.. 8 seconds, at 50 fps (physics time).. that's 400 frames of simming that need to happen pretty quickly, otherwise the user's gonna feel a noticable stutter when rolling
maybe not, i dunno
Here's somre more shots of the detection cube, shouldn't be true
Not sure - this is a little hard to parse. I'd probably try to do less on one line with some intermediate variables. If you're having trouble grokking it I'm sure that I'm not going to be able to do better.. I don't know what all those magic numbers are
ie, what's charcontroller.radius*2, what's Vector3.down * 2.5f, what's new Vector3(0.2f, 2.5f, 0.2f) * 2, etc
I can .. assume? what those mean but if you had some intermediate variables (and you logged them) it might be more obvious to you/us what you're intending and what the problem is
charcontroller.radius*2 is the radius of the character controller (In this case it's default at 2)
Vector3.down * 2.5f is an offset
new Vector3(0.2f, 2.5f, 0.2f) * 2 is the size of the cube, I put *2 as is half extents but I realize I'm utterly stupid and have removed that
well you're not utterly stupid 🙂 but I'd make it simpler for yourself by putting a lot more intermediate variables in there so you just really can't goof it up
const float characterHeight = 2.5f; // half height? full height?
const float characterWidth = 0.2f; // half width? full width?
float characterControllerRadius = charcontroller.radius * 2;
Vector3 footPosition = Vector3.down * characterHeight;
Vector3 cubeSize = new(characterWidth, characterHeight, characterWidth);
Vector3 collisionCube = transform.position + (NPC_PathfindDir.normalized * characterControllerRadius); // Did you really want to add the down vector to this?
bool isOnFloor = Physics.CheckBox(
collisionCube,
cubeSize,
Quaternion.Euler(Vector3.zero),
layerMask,
QueryTriggerInteraction.Ignore);
that might be how i'd debug and write this this
(then debug log each of those vars)
might seem like I'm trying to de-clever the code but.. imho being clever/cramming stuff into one line = hard to understand/find bugs
Thank you Sharp
I see what you mean, I feel this could just be a game design solution. Since the post uses unity physics, your option is to apply some counter movements or just have some max time before just taking the results
I mean, my reason for doing it would be the networking issues
(it's multiplayer/server authoritative)
so.. the server would roll randomly, then the client would "see" a physics-dice roll but the rolls are already known
So I added threading to my project and moved the main calculations off to a 2nd thread and it helped alot, but I'm curious if any of this could go on a 2nd thread or if forbidden due to needing monobehavior?
public void AssignMeshData()
{
mesh.Clear();
mesh.vertices = verticies;
mesh.uv = uvs;
mesh.triangles = triangles;
GetComponent<MeshCollider>().sharedMesh = mesh;
mesh.RecalculateNormals();
}
I think the bulk of the time is spent baking physics, as a result of the collider being added.
I don't see any reason why it couldn't be taken off the main thread, although I dunno if RecalculateNormals() does anything funny - like just flag the mesh for recalculation of normals at a later stage in the tick lifecycle, in which case you'll want that probably to be on the MT
or .. you might just want it on the MT anyway in case of any sort of race condition or deadlocking
how are you taking items off the MT? with UniTask or something similar?
I sorta figured them last 2 lines were off hte table since it wouldn't even let me use Random.Range in 2nd thread
it wouldn't let you use Random.Range? lol.. roll your own that's not in Unity.Math 🙂
well for that I just switched to System.Random, that was no big deal
I wrote a wrapper to random a long time ago using System.Random just because I didn't have a need for seeds/determinism most of the time
public static class NumberUtils
{
private static readonly Random _internalRand = new();
public static int Next(int maxExclusive) => _internalRand.Next(maxExclusive);
public static int Next(int minInclusive, int maxExclusive) => Next(maxExclusive - minInclusive) + minInclusive;
public static bool NextBool() => _internalRand.Next(2) == 0;
public static double NextDouble() => _internalRand.NextDouble();
public static T Next<T>(List<T> list)
{
if (list == null) return default;
if (list.Count == 0) return default;
return list[Next(list.Count)];
}
//... and a zillion more.. colors.. vectors.. positions on a rect border, etc
The problem of a dice rolling for a long time stll could just be solved with a timer. The actual dice roll client side could just be treated as any other moving object where you dont need to know its future locations all at once
I don't understand what you mean..?
Like, if the server says to the client, "ok roll the dice but the results are going to be 1,1,1,1,1" I still need to sim up the physics if I wanna have ... "physical dice"
Guess it depends how you're moving objects in the first place. With rb I assume youd have the client move it and the server correct it
it's a board game, so.. server won't even be unity-aware or doing any physics at all
I see, my bad. this is a bit different from what I thought
all good.. just talking it out, thinking of cool solutions
my current solution is just to show the dice in UI, but that feels kind of flat
Can always have a set of premade fixed animations for each outcome and just randomly pick one that matches.
might be a bit hard since there'll be ~20 dice rolled per turn
I was also thinking that it might be cool if the dice bounced off of the units/environment stuff
if the physics bake is taking the most time, look at https://docs.unity3d.com/ScriptReference/Physics.BakeMesh.html. It's one of the relatively rare thread-safe calls in Unity
Interesting, thanks. I did try to move some that other stuff to 2nd thread, but it said no way lol
Also I'm just using System.Threading currently, does Unity off something in Jobs or othre that would be more suitable?
the job system (+burst) is likely to be a lot more efficient if you can do whatever work you're doing with the mesh inside its restrictions
cool, I'll have to read up on that, haven't touched it yet
You could just do an async call--using the job system may be faster but it has a lot more setup
Do the dices bouncing around actually matter in terms of gameplay, since the server doesnt even have anything position or physics wise related to it? If not, you could just do it all client side while using the servers dice roll as the result.
Yeah but what do you show on the dice? without simming it ahead of time
like if someone rolls the dice and they come up 6, 6,6,6,6,6 and the server is like 1,1,1,1,1 that's gonna feel weird/bad
I meant that the client would do everything the post said, and just let clients do it differently if it doesnt actually affect gameplay
Ah, gotcha
It doesnt sound like something solvable at least if the server isnt physically rolling it, you would have to have a deterministic system (not unity physics)
Solvable meaning everyone sees the exact same movement
Well, that's sorta what I'm doing. 🙂 Everyone is going to see the same "result" but not the same animations
I'm gonna physics sim throwing the 20 dice (from start to finish, all in one frame), keep track of position, rotation, then fudge the initial rotation so it ends up on the number I want, and then "replay" the sim one frame at a time just using RB
if I "kick" the dice quickly in the first frame then you shoudn't be able to see the cheat
If you don't require having random animation every time, simming a bunch of animations and randomly picking one is fine.
I can't sim them ahead of time though since they'll bounce off of units in the game
Then you just change the dice texture so that the desired numbers end up on top.
https://www.reddit.com/r/gamedev/comments/bq6c5d/deterministic_physics_dice_rolls_in_a_non/
If you look - you can see the dice bounce off the units on the board. If you look really close and slow it down, you can see the dice flicker to a different number in the first frame of the "roll"
Then you don't need to do this part:
then fudge the initial rotation so it ends up on the number I want
You just need to record down the final face that's facing up, and change the texture so that the desired number is on that face.
sure, can do that too
Ah, that's essentially just what the post is describing.
so I have the ability to take photos in my game and I notice that they come out way different. After some research, I found out that this is because my game is in a linear color mode and the pictures are in gamma. How do I fix this?
this is my code that makes the texture. I've tried changing linear to true and false and neither worked and I tried changing the TextureFormat and that didn't change anything either
here are the settings for the render texture
you can see that it looks just fine, it's just the texture that the code is making that's off
RenderPrimitivesIndirect works worse than DrawProceduralIndirect.. why? maybe i do something wrong.
DrawProceduralIndirect is around 300FPS
while
RenderPrimitivesIndirect is around 170FPS
shouldnt be RenderPrimitivesIndirect newer and better method?
First of all, fps is not a very reliable metric. You should profile and see the CPU/GPU time and what exactly causes the difference.
Additionally, there's not just one, but 2 new methods replacing it that you should choose according to your needs:
This function is now obsolete. For non-indexed rendering, use RenderPrimitivesIndirect instead. For indexed rendering, use RenderPrimitivesIndexedIndirect
https://docs.unity3d.com/ScriptReference/Graphics.DrawProceduralIndirect.html
I know i added them both for testing and indexed dont work for me
So porting to unity 6, before I didn't get any errors, now im getthing this
RenderTexture.Create failed: random writes are not supported for depth only textures - format D16 UNorm (90).
This is how I'm creating the Render Texture
RenderTextureDescriptor descriptor = new RenderTextureDescriptor(textureResolution,
textureResolution, RenderTextureFormat.RHalf, 16, MipLevels)
{
useMipMap = true,
autoGenerateMips = false,
enableRandomWrite = true,
#if UNITY_6000_0_OR_NEWER
graphicsFormat = SystemInfo.GetCompatibleFormat(GraphicsFormat.None, GraphicsFormatUsage.Linear)
#else
graphicsFormat = SystemInfo.GetCompatibleFormat(GraphicsFormat.None, FormatUsage.Linear)
#endif
};
DepthTexture = new RenderTexture(descriptor);
DepthTexture.Create();
Any idea how to get the right format to use?
that cause the difference
DrawProceduralIndirect
RenderPrimitivesIndirect
Hello, is there a way to have the title of a script shown in the inspector (red arrow) be changed by a variable in that script? (in this case the Name variable so it would be something like "Music: Phase1") instead of Music Track (Script) )
I've looked online but I haven't been able to find anything helpful so far. I just need to know where to look.
No, well it is possible but you would need to deep dive into the internals of Unity
That's unfortunate. Do you know if there's a way to do anything similar? I'd just like to have an easy way to differentiate each instance of the script (especially when being referenced by another script like the Next Track variable) without having to make a different game object for each one.
'easy way' not a chance, you'd need to use reflection on the UnityEditor class instances and, believe me, that is not a can of worms you want to open
Alright, thank you for the info!
#↕️┃editor-extensions might have additional suggestions
You can add icons to script.
You could put each script on a separate child gameObject and then use OnValidate() to change the name of the gameObject to the name of the audio track.
That's actually what I ended up doing.
Interesting indeed. Can you share the code used in both cases?
it's one code just using switch to change between rendering methods
https://github.com/AndrzejKebab/UnityVoxelMeshGPU/blob/master/Assets/Scripts/VoxelChunkGenerator.cs
Okay.
What I'd do is analyze both cases with PIX to see what exactly is taking the GPU time in each case. Here's the docs page on how you can set it up:
https://docs.unity3d.com/Manual/DebuggingShadersWithPIX.html
As well just generally see what execution path it takes and what parameters are used. Perhaps it is faster in the first case because it omits some calculations.
Btw, can you expand the hierarchy further on these screenshots? There might be some import info hiding inside.
RenderPrimitivesIndirect
DrawProceduralIndirect
Interesting. It doesn't register any actual draw calls. I wonder if it's just a profiler issue or there's something more to it.
and what should i look here for?
Well, start from comparing 2 captures: one with RenderPrimitivesIndirect and one with DrawProceduralIndirect.
You could also make both calls in the same frame to avoid jumping between the captures.
Compare the used shaders, the command used for the draw call and it's parameters. Then you could also use the debug tab to step through the shader as it executes and compare it in both cases.
Hey ive been running into a problem with the a* pathfinding package where my agents just walk right into the wall
So I'm using a render texture to take pictures in my game and as you can see, it looks a lot darker in the final output than in-game (it looks a lot brighter in game). I'm pretty sure this is because the game is using a linear color space, but I'm unsure how to convert it when I export it. Does anyone have any advice about this?
is there some way to just convert a texture's color space?
Anyone ?
What would be the best way to have an asset rename feature sync to an editor window? Currently the title of the editor window comes from a GUI content, and I would like to update it every time the name has changed.
What do you currently have working?
You can set render textures format so that it writes in a specific format (and doesn't apply conversion). For example
RenderTextureDescriptor descriptor = new RenderTextureDescriptor(resolution,
resolution, RenderTextureFormat.RHalf, 8, 0, RenderTextureReadWrite.Linear)
The RenderTextureReadWrite mode on creation https://docs.unity3d.com/ScriptReference/RenderTextureReadWrite.html
I would say if you don't have anything working to:
First (and for future reference) ask it in #archived-code-general or #💻┃code-beginner
And then start with a simple implementation with raycasts and line renderers, and slowly add features for rope simulation (whether it's yours or using unity joints)
About the physics itself, you dont really want to make real forces simulation. Playing with animations that look like its applying forces and having a simpler implemtation will make it waay easier to work with (and I doubt red dead uses physics itself looking at some videos)
Probably I should use rope physics but I'm not sure if I can get the correct feeling for rod line.
Also I would like to know what is the best technique performance-wise.
Rod line it's a matter of bending it with a shader. Line itself is just a line renderer. Performance wise, wait until you have something working. Once you can test if it works then its time to iterate and optimize if it needs it
Or at least that's how I would do it
Hmm, I'm mostly looking for a correct approach to achieve something like RDR2. I think it is not just line renderer and probably mesh generator or something.
Also I think it is not that much physics based, or at least it is not effected by collisions.
I'm asking about performance because I want to omit techniques which are not performance-wise at least. I don't want to waste too much time on an approach which can't optimize it that much. For instance, if I want to use rope physics probably I'll waste too much resource there because of no collision impacts.
Yeah, I mentioned physics because you mentioned physics initially, but I agree that i don't think it's physics based either. I don't think there's any mesh generator either because you can see that the line is almost always in tension (at least on the active part of fishing). Plus, in any case, you are probably better using a line renderer with multiple points even if you want some bending when throwing it, and calculate the positions yourself to bend accordingly
I think you should start on something and act on the problems as you find them. The line renderer approach should not take you more than max a couple of hours, and im being really generous there
What might be more troublesome is the rod bending, but it's just math
And once you got the animation and visuals part separte of the point of the fish in the player, its way easier to just move the fish and then everything follows
Actually I've made a fishing line with line renderer before and a mathematic formula for bending but I'm looking for spring damping or jiggling or something based on the character and rod movement besides those bending and pulling.
That's why I also asked what was your previous experience. Looks like you already got it figured it out!
You could dig up the code for tonemapping in your render pipeline's shaders and run it on the final HDR output texture with a custom shader.
Though it'd be weird for it to still be HDR after all the postpocessing has run 🤔
why?
aight
when i try to build asset bundles my editor crashes, has this ever happened to anybody?
this is the code i use to build bundle
public class AssetBundleBuilder : MonoBehaviour
{
[MenuItem("Assets/Build AssetBundles")]
static void BuildAllAssetBundles()
{
string assetBundleDirectory = "Assets/AssetBundles";
if (!Directory.Exists(assetBundleDirectory))
{
Directory.CreateDirectory(assetBundleDirectory);
}
BuildPipeline.BuildAssetBundles(assetBundleDirectory, BuildAssetBundleOptions.UncompressedAssetBundle, BuildTarget.StandaloneWindows);
}
}
i dont think it should be the issue
it worked before but it dosnt anymore and i cant pinpoint why
Hey everyone 👋
Is someone able to help me with this: https://discussions.unity.com/t/webgl-wasm-build-without-graphics 
I have tried everything I can, running out of ideas now

thanks! I'll try this
Hi, I can ask you a question, how can I change the value of some components in the Input Manager with a script (for example, "Horizontal")
and if this cannot be done, then what is the way to implement it
in your experience, which is cheaper: Physics.Raycast or Navmesh.Raycast?
Am currently modding a game that uses harmony though that detail itself isn't toooo important. Am optimizing said game in question since the devs for it aren't willing to do it themselves even with help and one major issue is all the game object and component spawning during even bullets ect. Have attempted an object pool and it kind of works but truth be told the code is just way too convoluted to catch all these edge cases and thus ends up impractical to fix/maintain. So another solution came to mind which I use for my own works. Where one would have a custom allocator of sorts that gives you a block of memory based in input size similar to malloc but when said memory is "returned" it never actually gets cleaned up by system memory. The end result is such that once the game "warms up" it roughly keeps allocated about what it needs and has minimal overhead such heavy polymorphism and nested allocations aren't anywhere near such a big deal. I know GCs are supposed to solve this but reality is when they release memory back to system that defeats the entire point and the data pool required is rather large. So would anyone happen to know if there's a way to either modify the GC or tweak a setting such it never releases memory back to system? It's entirely worth while to reserve anywhere from 4GB to 8GB extra memory.
Well, then you'll have a memory leak. Because there's no guarantee that you would be able to reuse the same memory, simply because the allocated blocks might not be of the required size or alignment. Besides, I bet that most of the overhead is not from the allocation/deallocation itself, but from invoking the destructors and cleaning up the objects.
Also, changing the behaviour of the GC would at the very least require you have access to the engine source code.
Finally, are you sure that the issue is the GC? Did you actually profile the project?
Eeeew darn it >.<
Discussing modding is against the rules, by the way
We've done extensive testing and the custom object pool at the least did a major impact, when it didn't crash at least.
The heck?
I guess I should find a community server in that case sorry for not reading.
I didn't want to believe the destructor calling would be that expensive but honestly the nesting is sooooooooo deep it very well could be.
Righto off I fuck thank you.
Also I know I'm a DOD nut but someone please spread the word of at the very bare min object pooling to push the industry in the right direction please and thank you much you all have an awesome day.
I would venture to say that the industry is pretty much familiar with object pooling 🤣
How can I "listen" to an object destruction?
What I need: I have delegates. Behaviours connect to those delegates. Programmers forget to disconnect from said delegates on object destruction. I get wacky errors when the delegates fire callbacks on destroyed objects.
My attempt to solve: An extension method on Behaviours so you can do something like SafeConnect(delegate, ()=>{}). This function somehow needs to hook into the behaviour destruction to remember to unhook the delegate on object destruction.
(Somehow similar to DoTween's SetLink)
Now... how can I listen to an object destruction? 🥲
Oh, I could make a behavour to do the linking and the behaviour itself would take care of himself 🤔
something like GetOrAddComponent<TheDelegateinator>().SafeConnect(delegate, ()=>{})
Oh my god... I made a Maid/Janitor pattern for unity 🤦♀️
UniTask has that kind of thing for all unity events
oh 👀
I have unitask, lemme check, thanks!
It’s in the UniTask.Linq assembly
Hey guys, I need to use a mutable static field in Unity's Job system. I'm doing this because I have some settings that I do not know in compiletime, but only need to set once in runtime. Burst provides this utility for mutable statics here https://docs.unity3d.com/Packages/com.unity.burst@1.8/manual/csharp-shared-static.html
Unfortunately, the documentation is a bit lacking on this. To use the generic I need to initialize it on load using GetOrCreate with a key and a context. Does anyone know what this key and context means? If I make a template of a struct, can I then use the struct type as the key? Can I use a struct as a context? My sharedstatic won't be changed on a job so I don't need to care about synchronization.
The context is the unique “key” of passed types. You have the option of either passing one type as the context or two types (context and a sub-context). The goal with using types this way is to uniquely identify a given SharedStatic. There’s internal hashing of the type to produce a unique identity for each SharedStatic. You would most simply use the type containing the SharedStatic the key, as long as there is no other SharedStatic that does the same.
You can use generic types for the context/sub-context, which comes in handy for where you want to create data associated to specific types.
Oh so as long as the context+subcontext is a unique type combination it should hash differently then?
Thanks!
Pls I need help can some tell me what the problem is i have been try for days just on how to shoot but I keep getting error
this is not advanced. do not crosspost. and you were shown how to post code correctly, so do so in #💻┃code-beginner
Fine .Pls can't someone just help me out
not until you post something that someone can actually read
First go to #💻┃code-beginner and read the !code rules and apply them correctly
Posting 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.
Did you see any errors in my code
are you just intentionally ignoring everyone telling you to post your code correctly? because you are unlikely to get help until you do so
Am sorry I don't understand
What else should I do I Post the picture of what I wrote and I still don't get what you mean
Ok go to #💻┃code-beginner and read the !code rules written by the bot.
Posting 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.
Should I write it or what
Yes or use one of the paste sites if it is really large
So you mean I should write the code in the link above
Write the code in a code block or if it is large then use the link and copy and paste the URL and paste it in #💻┃code-beginner
OK I get
Yeah I understand you meant to ping me
using UnityEngine;using System.Collections;using System.Collections.Generic;public class rig : MonoBehaviour { [SerializeField] private GameObject projectilePrefab; [SerializeField] private float shootspeed = 20f; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (Input.GetButtonDown ("fire1")) { shoot (); } } void shoot() { GameObject projectile = Instantiate (projectilePrefab, transform.position, transform.rotation); Rigidbody rb = projectile.GetComponent<Rigidbody> (); rb.velocity = transform.forward * shootspeed; }}
Hello
My phone died, did you follow what the code bot said? Also this needs to go in #💻┃code-beginner
No
No?
Hello
Am new on discord
It does need to go in #💻┃code-beginner and you need to follow what the code guidelines say to post code
Hello! I am struggling with implementing Item Drops in my Unity game. First I am trying to do a Promo Item drop that happens when the user first starts the game for the first time.
I think I am doing everything correctly but I am just not seeing the items in my steam inventory. The Item definition is created and looks like this: https://pastebin.com/pFg54NVp
Currently my AddFirstItem script looks like this: https://pastebin.com/WSeZHg11 but it just runs in a loop because the item is not found in the inventory.
What am I doing wrong? Inventory service in steam developer is allowed of course. In "Economy" the url is also correct. Why is it not working? 😦
Pastebin
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.
Pastebin
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.
Hey all,
I made fishing rod line with Verlet Integration and I want to add throwing part. What is the correct way to do that ? I should modify something on the last point on the line ? I want to implement something like RDR2.
You can think of the line as purely visual. The part you need to get working is the hook/bait physically simulated for the throw, bobbing on the water and reel. You can make it fully physically simulated as a Rigidbody, and use forces to simulate the throw, buoyancy, and reel. After that's all done, you just connect your verlet rope between the end of the fishing rod and the hook.
It's also possible to use the verlet integration to apply forces to the hook, to implement the reeling and drag during the throw, but not necessary.
Thanks for the reply.
I have the same idea too. As a separate logic for the hook/bait. But still I should connect the last point on the line to the hook/bait, right ? So when it is not in throwing state hook/bait position and rotation are updated based on the line last point because of hanging behavior and when I want to throw it I should update the last point on the line based on the hook/bait when its Rigidbody is activate ?
Also does it make sense to change the connection length between points by lerp when it is during throwing part ?
For implementing throwing based on Rigidbody what is your suggestion ? Do you think AddForce or AddRelativeForce is enough ?
Hi, is there a way to call a function with more than 1 parameter using UnityEvent?
I guess it depends on how realistic you want the simulation to be. You can totally go all the way and simulate it entirely with the verlet integration. You just need to simulate as if the particle/node at the end of the rope is heavier than the rest. That approach makes the most intuitive sense, but might be more difficult to tune.
With forces, you can just apply an upward/forward impulse force for the throw, and then calculate the distance between the hook and the end of the rod. If it's greater than the length of the line, apply a force to pull it towards the rod. This is not too dissimilar to how verlet integration works, except it also applied forces in the opposite direction if the distance is less than it's supposed to be.
Besides heavier mass on the last particle/node, what parameters should be tuned to achieve more realistic behavior ? I want to make it more like RDR2 (+ Wind effects it). Also mass is just multiplied by the acceleration/gravity ?
Thanks for the help.
Not easily. Lots of "bad" solutions. Concatenated strings that your parse the int. Wrapper methods that you have enum values to represent fixed tuples. Set a public variable (or two) and call a method without parameters, etc.
You have to tune how stretchy/stiff the line is, how many particles are in it, what the mass of the line vs the hook is, dynamically adjust the length of the line like a real fishing rod would, where it can be pulled out, unless it's being reeled in.
Hmm, got it. Thanks. actually I've been working on the same thing somehow but I couldn't achieve it. So probably I should continue working on this approach more. At least now, I know I'm on the right track.
btw, by rigidbody approach, I shouldn't adjust the length of the line ?
Also I adjust the length of the line by increasing connection line between each particle/node. Does it make sense ?
I'm not sure what the best approach would be for lengthening the line. The simplest would be to increase the distance between the particles, but then it also becomes lower resolution, visibly and can affect simulation quality too. Alternatively, you can try adding additional particles at the rod end of the line, as if they are being unwound from the reel, but I'm not sure I've seen that done before.
With the rigidbody approach, you will need to have some variable representing the length of the line. If the rigidbody gets pulled further away by something, the length will have to be increased to account for that, up to the max length of the reel. But the length should only be decreased if the player is reeling it in.
Awesome, thanks a lot.
@earnest heron As mentioned, you should probably adjust the length of the line by inserting new particles rather than spacing out the points as this has a significant impact on behaviour, if you want to retain visual plausibility.
Mass in sims is used for constraints resolution within the system.
Since you are familiar with verlet integration, I suggest looking into positions* based dynamics. It's similar to what you're already doing in the sense that the new velocities are driven by the delta in position.
If you go with PBD, which is fairly simple to get a grasp of, you can establish constraints such as distance constraints between 2 particles. Your line could be a series of particles, sequentially connected by distance constraints, with a higher mass at the end. You could simulate it entirely physically while retaining great visual plausibility.
Hell you could even throw in buoyancy constraints so that it looks accurate when hitting the water
And of course, it makes it trivial to apply external forces like the gravity or your wind system
The only thing that is more difficult to implement with verlet integration is interactions with colliders and rigidbodies. It's possible, but usually more limited, like a select few primitive colliders. Full interaction with colliders will require a more complex approach to be performant.
But other than that, it's a much more interesting and promising approach.
Ya, can't hook onto unity's space partition, so need your own spatial hash + common interface that wraps around physx components and your own
can confirm its a pain
You could also do both. The hook can be a Rigidbody and you can attach the line to it, computing the forces between them. This is similar to how joints/constraints in PhysX work.
The line still won't collide with anything, but at least the hook can be hit by boats and not go through colliders around the water.
Yup, inserting new particles is a great idea. I hope I don't get to any obstacles during implementing 🤞
Hmm, what do you mean about mass ? Could you tell me where should I add that ? I thought I should add that like _particles[i].pos += _particles[i].mass * gravity * deltaTime * deltaTime
Oh, I'll research about that. I don't know much about that, just I've read about 3 ways for implementing Verlet Integration which I think one of them is this one you mentioned.
The distance constraints between 2 particles you just mentioned here is not something common in Verlet Integration ? I mean I already made this constraint between particles in this way:
for (int i = 0; i < _particles.Length - 1; i++)
{
Vector3 delta = _particles[i + 1].pos - _particles[i].pos;
float length = delta.magnitude;
float percent = (_connectionLength - length) / length * 0.5f;
_particles[i].pos -= delta * percent;
_particles[i + 1].pos += delta * percent;
}
Which I added iteration on that because of accuracy and stiffness.
Yeah, so with what you have there. When you compute the error, divide it by the sum of the inverse masses for the particles
e.g. particle 1's mass is 1, particle 2's mass is 3.
w (aka inverse mass) = 1/1 + 1/3, and then when you move the particles back towards their respective gradients, multiply the gradient * error * that particle's respective inverse mass
Yup, I'm aware of that and hopefully I don't want any interaction with colliders. Just a trigger for entering the water is enough for me because I don't want to make it heavy by adding collision checks which I think it impacts performance greatly. I think in RDR2 there is no collision checks too.
this way, you'll have whichever particle has the higher mass cover less of the distance
I assume connection length is your rest length? Then error = restLength - currentLength
gradients are your normalized delta and its opposite vector.
e.g.
// Where .InverseMass = 1f / mass
var w = a.InverseMass + b.InverseMass;
if (w != 0f)
{
var delta = b.Position - a.Position;
var length = math.length(delta);
var error = restLength - length;
if (error != 0f)
{
var gradient1 = math.normalize(delta);
var gradient2 = gradient1 * -1f;
var s = -error / w;
a.Position += gradient1 * s * a.InverseMass;
b.Position += gradient2 * s * b.InverseMass;
}
}
I'm working on that too but I'm not sure if I can handle connection between Verlet Integration and Rigidbody clearly.
But I want to make it ASAP so I need your experience too.
@torn rose @sage radish. So as a conclusion, which way is the fastest way ? Also I don't want to implement a dirty code and approach and I want to expand it later.
Fastest implementation? Whatever you're familiar with and yields good enough results I guess?
As you said, you don't need collisions, so ignore what I said about the hybrid approach. It sounds like you have a good enough understanding of the concepts to go with the fully particle based approach. If realism is very important, you will get better results from particles. But I don't know if I would say that it's faster to implement.
It will be difficult to replicate RDR2 with other approaches, I think.
I see, got it, thanks. Though I don't understand what is the effect of mass here mathematically.
When you are solving that constraint, you're essentially computing the error based on what their distance apart is, and what it should be.
Now if you wanted to make that constraint happy and give it a big error of 0, youd move the particles in a way that satisfies the condition. Should the particles move an equal distance if their mass is not the same? Most of the time, the answer is no.
Sorry to ask a silly question, but by other approaches you mean other than Verlet Integration or Rigidbody and Verlet Integration combination ?
Oh, got the point here. Thanks a lot.
Also mass is just a parameter in here or it should be used other places in Verlet Integration too ?
the distance constraint and usage of mass is atypical for verlet integration, seems like a mix of PBD and other sequential solving methods
I mean mass is just used here or I should add it somewhere else in Verlet Integration ?
Likely no.
I mean, it's just a tool to obtain results X and Y. Is there something in your sim that is undesireable and you think it could be solved by factoring masses?
I see, I didn't know about mass parameter before this conversation but I was thinking it would be good to have something heavier at the end of the line to be affected by velocity (position - old position I mean)
Right, so "heavier" is relative here. It's relative to the other particles in your system, not just a general scalar.
So by factoring in the inverse masses like I've shown you above in your distance constraint, you'll get what you're trying to achieve. Also I recommend solving from the last particle of the line if you're not already doing that (the one at the end that hits the water first)
Hmm, got it, thanks.
By solving from the last particle you mean start the for loop from the last particle index instead of the first one ?
Well that'd depend on the order in which you've initialized/inserted your particles.
I mean the one that's the farthest apart when you're throwing your line
Got it, thanks. Also could you tell me the reason too ? 😄 Just for my knowledge.
Sure, because verlet/pbd is sequential solving, when you're solving your distance constraints, you're solving them one by one and the outcome of each individual constraints solved is going to have an impact on the ones remaining, but not on the ones before that. It's a bit abstract, but the general idea is that whatever feels the most important to your simulation should probably be processed first
The impact of this is attenuated by the amounts of substeps
Anyone here I need help
Dayum it look so empty
I want to move a 2d gameobject in a perfect circle, how to do it? Without using parent/child (with script)
Tag me please
don't crosspost. you've posted this question in 3 separate channels, and are actively receiving help in 2 of them.
My bad man
Ok so i've tried to do this on my own and i cant figure it out, so i'm gonna ask here.
Workin on a 2D Top down "Realistic" tank controller. By realistic i mean that all the player controls is either the Left track or the Right track, W & S controls the left track, I & K controls the right track.
What i'm greatly struggling on is making the tank rotate correctly. When only one track is accelerated, the tank is supposed to rotate around the stopped track, either clockwise or counter clockwise (depending wether the moving track is accelerating or reversing.)
I need to simulate this movement using Rigidbody2d, and only modifying the "velocity" and "rotation" properties of the rigidbody. Making the tank move according to its current rotation is EZPZ (since its just rotating the input from the player by the rigidbody's rotation), the main issue again, is figuring out how to make it rotate around a pivot and modify the velocity & rotation accordingly.
Here's the script itself, i'm working on this on an empty project to remove any unecesary baggage.
https://hastebin.com/share/aqodafalew.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Does anyone know whether, when calling multiple Async Unity methods (like Resources.LoadAsync, SceneManager.LoadSceneAsync, Adressables.LoadAssetAsync, and Addressables.LoadSceneAsync), the requests are always completed in order?
For example, let's say I execute 50 requests and add the returned async op objects (in whatever form they are), to a list. Now I want to check if any of them are done. My understanding is, if I start at index 0 (the first async op queued), once I find an async op that is not completed, I can stop checking the rest because they cannot complete before any that were queued before them.
Is that assumption correct? Or do I need to actually check all 50 because they can be completed randomly?
No. Asynchronous operations are assumed to be independent from each other.
Okay, cool. Then I'll check them independently.
Thanks!
Just came upon this page (https://docs.unity3d.com/Packages/com.unity.addressables@1.15/manual/LoadSceneAsync.html) which also says they can complete loading in any order, so it sounds like you are right.
You start cooking an egg and downloading a movie at the same time, there's no reason the computer can magically know to not finish until the egg in your pan is done cooking.
haha yes, I was just confused because there is mention of some blocking behaviour when using async ops like these. But it looks like that is unrelated to what I was asking here. Thanks!
Actually another question after reading the page I linked above. It says this:
Be aware, if activateOnLoad is set to false, the entire async operation queue is stalled behind the blocked scene load operation. This is not limited to scene load requests. Any asynchronous request is blocked until the scene is allowed to activate. This means yield retruns and callbacks cannot trigger until the queue is unblocked. If multiple scene load operations are started with activateOnLoad=false it can lead to inconsistent behavior. For example,
{
AsyncOperationHandle<SceneInstance> handle1 = Addressables.LoadSceneAsync("level1", LoadSceneMode.Additive, false);
AsyncOperationHandle<SceneInstance> handle2 = Addressables.LoadSceneAsync("other", LoadSceneMode.Additive, false);
yield return handle1; //will sometimes trigger, sometimes not
yield return handle2; //will never trigger
}```
Whichever of the two loads gets to "loaded but not activated" first blocks the queue and fires its completion/yield/task events. In this case, if "level1" loads first, its yield return proceeds, but execution is stuck on handle2 forever. If "other" loads first, then even though handle2 is done, handle1 cannot finish. Which scene loads first has nothing to do with which one is requested first in code.
" If "other" loads first, then even though handle2 is done, handle1 cannot finish. Which scene loads first has nothing to do with which one is requested first in code." - This I understand
" In this case, if "level1" loads first, its yield return proceeds, but execution is stuck on handle2 forever". This one I do not understand. If level1 loads before level 2, then won't the yield return handle2 be allowed to trigger?
That sounds like some implementation details of how they are loaded. yield return handle in a coroutine isn't magic, the handle still needs to give an "okay I'm done now, you can proceed with the rest" signal, and it sounds like the situation above will cause the handles to never fire those signals and thus stalling the coroutine forever.
What are you trying to achieve?
Right, I guess my misunderstanding was due to when the "signal" is fired. No worries, I think I may understand it better now, thanks! As for what I'm trying to do, basically queue up multiple load calls and then manually control when they are "activated" (because the activation phase, which involves main frame integration, is very costly if multiple operations are allowed to complete in the same frame).
I think the way I'm doing it will avoid the issues mentioned on that page, but only one way to find out!
that sounds... wild if true
i really need to find a course online for trigonometry because thats something we've never seen properly in my uni where i just studied videogame design and i decided to specialize in programming
nevertheless, if you do figure it out somehow lmk and i can try it out
bet it'd feel as iluminating as the time i learnt how to properly use a debugger instead of debug logging everything, lol.
i kinda do understand vectors to a certain degree, rotations with quaternions, radians, cosine, etc are the things i struggle with since i've never handled them. all i know is how to rotate a vector by x rotation and thats about it. lol
yeah,
You might be able to avoid the math and just use joints and such... I haven't really played with them before, but I got curious. This is with RBs on the body and each track. Each track has a Fixed Joint to the body.
I couldn't get the desired turning behavior by fiddling around with RB values, so I just froze a track's position if it has no input and it's not already moving... I reckon there's a better solution though.
i definetly plan on doing that if i cant get it to work by directly modifying a single RB's velocity and rotation.
but if its possible to make it work by directly modifying the velocity and rotation then that'd be perfect
is the fact that its in 2d complicate matters a lot?
which would be... kind of ironic? since its one less axis to worry about lol
2d is as complicated as 3d, you can even use 3d vectors for 2d if you would want, if you understand one you should be able to apply to another
fair enough, can i expect you to like... make something out? if you cant thats allright. not like i can force you
@white pulsar Since it's operated as one entity, you need to cheat a bit.
One way to do this would be to get the point between center of tank and mid point of either track. Compute the distance between both to get the radius.
Once you have the radius, (moveSpeed * Time.fixedDeltaTime) / radius should give you the delta in radians that you should travel for this given step.
Compute the offset with cos(currentRotation + delta) * radius for the x component, sin(currentRotation + delta) * radius for the y component
Add that offset to your tank's current position. That will give you the position where your tank should be if it had rotated around one track for that frame.
At that point, you can simply compute the delta between that position and your current position, and add that as a force with whatever the forcemode that ignores mass is.
i could do that since i dont really want to have more than 1 rigid body per "entity" if that makes sense.
but yeah, ideally the output values would just be the rotation and velocity.
its alright
Tracks are not simulated independently, you're not gonna get a physically based animation here.
the animation doesnt matter atm, just the movement of the entity
apologies, i should've specified that from the beginning
Ok this definately isn’t a good solution, but off the top of my head.
If you have a vector V1 from the center of the tank to a tread, and another vector in the direction we want to go, V2. The angle we have to rotate is
V3 = V1+V2
angle = arccos(dot(norm(V3), norm(V1))
Then you should apply the rotation and move forward in the new direction you are facing–hope this helps!(I have no confidence that this works just some mental math)
if you press A, V1 is the vector to the left tread, if you press D, V1 is the vector to the right tread. V2 is always the vector facing forward
Feel free to criticize me 😅
whats the problem you're trying to solve with this? because honestly this doesnt make sense. (last sentence of this message looks like AI too)
vector V1 from the center of the tank to a tread
V1 is always the vector facing forward
Also do you mean normalized vector, rather than norm? because vector norm is a real thing and is a single value, not a vector.
Sorry I wrote this in a rush, norm is normalizing the vector, and I mixed up V1 and V2 later.
@white pulsar was talking about tank tread movement before so I made up a very quick system for this
Also wdym by vector norm? Like the magnitude? Norm should implicitly mean normalizing the vector no?
dont need to read this link but norm is a thing https://en.wikipedia.org/wiki/Norm_(mathematics) but yea i guess it only makes sense to mean normalized in this server.
you should probably restate the exact problem you're trying to solve because all i see is getting an angle (not sure why its needed even).
https://docs.unity3d.com/ScriptReference/Vector3.Angle.html
There is also a built in function to get the angle
Oh figures there’s a way. Yeah but this is the most barebones physics solution for this task(which is good if you don’t want to overcomplicate it with a lot of extra functionality rigidbody provides).
Also why not just call Norm magnitude? It’s like mathematicians just wanna confuse everyone.
There is more than just 2 norm which is your standard magnitude formula. But it's too much to go into, especially since I had no clue wtf my professor was telling me norm was for either
Wow I just read a bit into that subject, idk how it’s useful but very interesting
Hey all, I've never worked with 3rd party plugin in Unity and I'm having some trouble using this one : https://github.com/xioTechnologies/x-IMU3-Software/tree/main/Examples/CSharp
It's a lib to interface with a IMU.
On the GitHub repo I've been able to download a .dll, .lib and .h file that I included in my unity project, but I can't figure out how to reference the ximu3 class present in the plugin as done in the example. I tried the using directive, the [Dllimport] directive but without success. What am I missing ?
I know my employer won't like it that I'm gonna try these solutions when it's a holiday here where I live but I'll try it anyways
Tank related, managed to build this thing which is working quite... well it seems
works only for the left track but should be easy to modify for the right track.
All I know is that if the movement speed gets too high the angle change is too high. Which tbh I can't do much about it? Since changing it causes the tank to no longer rotate on its appropriate pivot
Using var makes it hard to know what speed is. A vector? A float? Also, naming a local the same as a member is gonna give you a bad time. Name the local speed something different.
Not quite sure what the problem is, though? Why do you normalize v1 before getting the angle? What is the return tuple? What's "movement" - speed? location? acceleration? Why is "angle" (in the return tuple) not actually the angle, but the angle times the delta time and speed?
The intent is ... confusing from this snippet...
@torn rose @sage radish Hey, sorry for pinging. You are absolutely free to ignore my message here. Just pinged you because we already had a conversation about my problem and you are expert on that.
So in the morning, I added Rigidbody and force to the hook/bait for throwing that and Verlet Integration on the line. Also for unwinding the line, I made 200 particles which for instance from 0 to 180 are in the start position (tip of the rod) and their positions are always same as tip of the rod with no Verlet Integration impact and from 181 to 199 are affected by Verlet Integration.
When I need to unwind the line on the reel, I add to the total number of particles which are affected by Verlet Integration based on the deltaTime and it kinda looks okay.
The problem I have right now is, the curve on the line is converse of RDR2 and I don't understand why that happens. Probably because of stiffness ? Do you have any idea what is the issue ?
Bait and line codes:
public class FishingBaitHandler : MonoBehaviour
{
[SerializeField] private float _force = 10f;
public bool IsHanged { get; private set; } = true;
private Rigidbody _rigidbody;
void Awake()
{
_rigidbody = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter(Collider other)
{
_rigidbody.isKinematic = true;
}
public void Throw(Vector3 direction)
{
IsHanged = false;
_rigidbody.isKinematic = false;
Vector3 axis = Vector3.Cross(direction, Vector3.up);
Vector3 modifiedDirection = (Quaternion.AngleAxis(30, axis) * direction);
_direction = direction;
_modifiedDirection = modifiedDirection;
_rigidbody.AddForce(modifiedDirection * _force, ForceMode.Impulse);
}
}
Pastebin
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.
Do I have to write my own HttpValidationProblemDetails and ProblemDetails models in Unity in order to deserialize 401 responses or is there a way to use JsonUtility to do that?
I don't understand what you mean. Can you give another shot at describing your issue?
More specifically, this line
"The problem I have right now is, the curve on the line is converse of RDR2 and I don't understand why that happens. "
I mean the curve on the line as you can see on my game and RDR2 has different arc. Completely opposite.
Environment looks nice by the way
Honestly, I think yours is more realistic. I think the actual curve will depend on the weight of the line vs the weight of the hook, but yours makes more sense to me. The heavy hook falls faster through the air, while the line falls slower like a feather.
I'm trying to find actual reference footage, but it's difficult to find one where the line is in shot or visible at all.
Yeah, honestly I also thought it looked great.
That being said, if you want to tweak the behaviour, I still don't understand what you mean. The curve as in the position of the bobble over time while it's been cast?
Oh hmm, maybe not. This looks more like in RDR2.
https://youtu.be/mvenRLJvEaM?si=hTcV63eVHGKn2YQU&t=177
Film excerpt from the movie Casting & Strategy. Links below in the description. This is for both the beginner and the advanced fly caster. Casting instructor Ronny Lagoni Thomsen takes you on a trip to many different fishing locations to demonstrate fishing strategy and double hand fly casting in real fishing conditions.
© Wide Open Outdoor Fil...
Yup, exactly. I'm not aware of the reason but RDR2 looks more realistic 😄
In RDR2, the middle of the line hangs below, while in their implementation, the middle is the highest peak.
Ah I see
Maybe there's not enough gravity acting on the line. It almost seems like it's being affected by air drag, which I don't think is intentional.
Yup, what @sage radish said, sorry about that.
Or some energy is being lost somehow
One thing is for sure, it's not tight enough. The line feels very loose once it's being cast. I think I would address this first.
Maybe try this. Instead of releasing particles based on the frame delta and crossing fingers the rate matches the motion, perhaps you could simply not constrain the particle closest to the fishing* line. Sample its distance to the tip of the fishing line. If the distance is greater than it should be in function of the resolution of the line, then you generate a new distance constraint and you attach it to the next particle, and you release the next particle.
This way you'd insert particles based on the actual requirements
I increased the gravity from -9.81 to -50 and it looks like this right now. Does it make sense ?
Also what about give higher (I think lower actually) mass to the all of the line particles except the one at the end of the line where hook/bait is ? I've tried to add mass to my Verlet Integration implementation but I don't really understand that.
Yup, I have a problem with its stiffness too even when it is hanging from rod in idle state as you can see in my video at the beginning. How can I make it more stiff ?
I'm trying to understand your solution here. Give me some time 😄
btw, did you check those 2 scripts too ? @torn rose @sage radish
Okay, got what you mean @torn rose. I'll try to add that and test how does it look. It makes sense I guess.
Yup, that's right, so should I add mass you mean ? I did that but I don't understand what should I do about that because still all particles have the same mass.
I changed my code to use mass like this but not sure about that and I don't know how I can take advantage of that.
private void UpdateParticles(float deltaTime)
{
for (var i = _totalNumOfParticles - (int)_currentNumOfParticles + 1; i < _totalNumOfParticles; i++)
{
Vector3 velocity = (_particles[i].pos - _particles[i].oldPos) * _friction;
_particles[i].oldPos = _particles[i].pos;
_particles[i].pos += velocity;
_particles[i].pos += (_gravity / _particles[i].inverseMass) * deltaTime * deltaTime;
}
for (int i = 0; i < _totalNumOfParticles - _currentNumOfParticles; i++)
{
_particles[i].pos = _pin.position;
}
if (!_baitHandler.IsHanged)
{
_particles[_totalNumOfParticles - 1].pos = _particles[_totalNumOfParticles - 1].oldPos = _baitHandler.transform.position;
}
}
private void ConstraintParticles()
{
for (int i = _totalNumOfParticles - (int)_currentNumOfParticles; i < _totalNumOfParticles - 1; i++)
{
Vector3 delta = _particles[i + 1].pos - _particles[i].pos;
float length = delta.magnitude;
float error = _restLength - length;
float sumOfMass = _particles[i].inverseMass + _particles[i + 1].inverseMass;
float percent = error / length / sumOfMass;
_particles[i].pos -= delta * percent * _particles[i].inverseMass;
_particles[i + 1].pos += delta * percent * _particles[i + 1].inverseMass;
}
_particles[_totalNumOfParticles - (int)_currentNumOfParticles].pos = _pin.position;
if (!_baitHandler.IsHanged)
{
_particles[_totalNumOfParticles - 1].pos = _baitHandler.transform.position;
}
}
Here
var a = _particles[i]
var b = _particles[i + 1];
var w = a.InverseMass + b.InverseMass;
if (w != 0f)
{
Vector3 delta = b.pos - a.pos;
float length = delta.magnitude;
// The magic number to satisfy the constraint
float error = _restLength - length;
if (error != 0f)
{
// What to scale the vectors with
var s = -error / w;
// The directions
var gradient1 = delta.normalized;
var gradient2 = delta * -1f;
a.pos += graident1 * s * a.InverseMass;
b.pos += gradient2 * s * partifles[i + 1].InverseMass
}
}
Untested but it should work, let me know if you run into issues
I think it is same as mine, the above one. right ?
No, you are applying the correction based on the current* magnitude
float percent = error / length / sumOfMass;
_particles[i].pos -= delta * percent * _particles[i].inverseMass;
The current length should only be factored in to determine the error
Why the masses matter here is because your bubble should feel heavier. If all particles are treated the same within the simulation, you will not be able to properly illustrate that.
You are cheating this a bit by reassigning the last particle to the bauble's position after solving the constraints. This kind of works in the sense that'll force all the particles down the line to bridge a larger gap during the next step to satisfy the constraint.
What should be done is the particle with the bauble should have a higher mass. When resolving the distance constraint, the particle attached to the one with the bauble will move more than the one with the bauble, when attempting to make the constraint happy. Consequently, all the particles down the chain will end up being affected by that.
e.g. if the error between bauble particle and the next particle is 1 for a given step, if the mass of the bauble is significantly higher, the other particle will be responsible for closing most of that gap, forcing the rest of the particles closer, thus giving more influence to the higher mass one
provided youre solving from last
hello
So I just need to remove that / length from percent, right ? I'm a little tired right now so it is hard to understand that 😄 Other than that they are same ?
Hmm, so I should use Verlet Intergration for throwing instead of rigidbody force ? Or I can just increase the mass on the last particle and it will do the job ?
Also start the for loop from the last particle.
No, you can absolutely cheat the way you are, but your last particle should still have a higher mass so your simulation is aware of and accounts for the higher mass in its solving process
What should I should do about the stiffness ? I want to make it heavier so it looks less stretchy when it is hanging.
Well accounting for masses for one
It should have higher mass or lower ? Because look like fishing rod line is heavier than the bait/float/hook.
I'll test all of your suggestions. Thanks a lot. Can I send a message here by pinging you tomorrow if still I have an issue there or at least if it works, show the result ?
btw, does it make sense I put mass here too ?
_particles[i].pos += (_gravity / _particles[i].inverseMass) * deltaTime * deltaTime; ?
I don't understand. The fishing rod line isn't simulated is it?
Also yeah, I might answer, maybe not depending on what I am doing, but please do share your results
I wouldn't
Forget it, I think I can't convey the point 😄 I'll ask it again if I can't figure it out.
Thanks a lot
Np. General idea is that if it should feel heavier, increase its mass. The distance constraints scales how much particles travel to make the constraint happy, based on their masses relative to one another
good luck
does anyone have a guide on how to use graphics fences with compute dispatch and AsyncGPUReadback?
I'm feeling kinda lost and the docs are devoid of examples in this realm from what I can tell
I apologize if this is the wrong channel, but the ad button is clickable in testing, but not the game.
Checkout pinned resources in #📲┃ui-ux , specifically on how to implement dynamic layout supporting different resolutions. You likely have a transparent element obscuring and blocking it.
Are you dispatching the compute shader as async, with Graphics.ExecuteCommandBufferAsync? If not, you don't need a fence to use AsyncGPUReadback. I haven't used fences before. They seem simple to use, but maybe deceptively so. I would assume it's just calling CommandBuffer.CreateGraphicsFence(GraphicsFenceType.AsyncQueueSynchronisation, SynchronisationStageFlags.ComputeProcessing) after dispatching the compute shader, using that return value to wait for it in either another non-async command buffer or Graphics and then creating the async gpu readback request in the command buffer or Graphics
I'm using computeShader.Dispatch() and AsyncGPUReadback.RequestIntoNativeArray(...).WaitForCompletion(), which, I think should all be synchronous right?
Yes, that should all work synchronously.
I want to use a library that has a DLL for .net standard 2.0, but it's missing the Microsoft.Bcl.HashCode dependency. Fine, np, I grabbed that DLL from nuget, but now I'm getting conflicts between unity stuff that's using Microsoft.Bcl.HashCode from netstandard 2.1.
Is there a way to .. get the library I want to use to use the 2.0 version and the unity stuff to not use that DLL?
Or more specifically, the compute shader will always finish before the next GPU command is executed, in this case AsyncGPUReadback. The WaitForCompletion doesn't change anything other than defeating the purpose of the async readback, but if it's for testing that's fine.
yeah I'm specifically doing that to make it synchronous to rule out issues
and because there's no built-in synchronous GPU download into nativearrays from what I can tell
Hmm yeah, weird that CommandBuffer.GetData and GraphicsBuffer.GetData only accept managed arrays...
yeah idk why
is GraphicsBuffer.SetData() synchronous as well? as in, waits for the GPU queue
or would I have to fence this manually
I don't think you ever need to use fences unless you're using Graphics.ExecuteCommandBufferAsync, which is the only way to queue commands into the async compute pipeline, if one even exists on the GPU.
alright
I've used this package in a pinch, worked great.
https://github.com/stella3d/SharedArray
I'm guessing the issue has to be somewhere else then, unrelated to synchronization
do compute shaders have issues with reading and writing to the same RWStructuredBuffer, even if the different groups read/write their own dedicated section?
If each thread has its own index/section, it's no problem. If it's all within the same thread group, I think you need to use memory barriers in the shader to ensure there are no race conditions.
But I've not used the thread group stuff for anything more than examples, so I'm not the best person to ask.
yeah each thread is accessing a unique part of the buffer
and it does work,, for the most part
I'm starting to wonder if maybe there's some kind of silent behavior with uninitialized or out of bounds memory in the compute shader, so that it cancels or something
Are you using Mathf.CeilToInt when computing the number of dispatch threads? That always gets me.
yep, using (x+iv-1)/iv
I have noticed one behavior that seems to suggest this
for context, this is for a selection system in my 3D modeling tool, and this is what happens
green = box selection hover
blue = selected
so sometimes, the blue applied selection just, doesn't happen, and the green stays, which it shouldn't (the apply step should clear the hover state)
but! the thing that's curious is that, the more I do this, and the more I select, the more rare the bug becomes
and if I select the whole thing, sometimes the issues goes away entirely, so, maybe it's got something to do with dynamic buffer resizing, or, the compute shader making assumptions about elements being in range, when the buffer is too small, or something
the selection buffer is a packed uint structured buffer, with two bits per selection state (hovered and selected), and one uint worked on per thread
Do you have any bounds checks in the shader, to early exit if the thread id is out of bounds? I don't think you need to on DX11, but you do on other graphics APIs, so you should always do that.
yeah
And you're not touching the contents of the buffer at all after starting the async gpu readback?
not as far as I know, if .WaitForCompletion() makes it synchronous
I've also tried the managed array one, the same issue still happens
Hmm. Do you have any explanation for why it seems the hovered selection becomes flipped in Y screen space after you release?
Could be a clue 🤔
kinda, I think the flip the lesser of the issues
the flip is likely because I'm reading from unity's global shader variables, which mneans that if other parts of the unity editor sets things like the _ProjectionParams.x it would flip
and I'm guessing it's maybe not fully synchronous when running it in GUI.repaint?
Hmm yeah, I've never dispatched a compute shader in the editor loop. Probably some caveats there.
maybe I can shove it into a command buffer to see if it's more consistent
@floral marten love your content btw - you're a superhero
o, thank you 
I'm having a weird issue with my A* pathfinding that's utterly killing Unity, and I'm not quite sure where the issue is.. or how to debug this.
My pathfinding loop is essentially something like bool TryGetPath(HexPoint from, HexPoint to, List<HexPoint> map, out List<HexPoint> path) and it works brilliantly on a single click to get the path and highlight the squares.
When I changed it to calculate the path in update() while mouse is down, it works for about 20 frames and then just dies. The weird part is that .. as best I can see, Unity isn't crashing in the GetPath method, but instead in between frames...
I am taking the returned List<HexPoint> path and emitting an event that individual hexes subscribe to and turn their own highlight on/off if they're "in" the path, so maybe something's going on there..
Anyone got any ideas/strategies on how to debug this? Code available upon request obv
path highlights on click
private HexPoint _lastMousePosition = HexPoint.None;
private void Update()
{
if (Input.GetMouseButton(0))
{
v("Getting mouse position...");
HexPoint target = GetMousePosition();
v($"Got {target}.");
if (target != _lastMousePosition)
{
_lastMousePosition = target;
v($"Checking path for {target}");
List<HexPoint> path;
HexPoint.TryGetPath(HexPoint.Origin, target, _map, out path);
ShowPathChanged?.Invoke(path);
v($"Done with {target}");
}
}
}
Unity hangs after some number of passes through this chunk - but it always makes it to "Done with".. it never dies in the middle of the TryGetPath method that I assumed with be the issue.
(unity is hung completely here - those are the last lines in the console)
can't stop playmode, exit unity, etc.. have to kill the process with a knife
Attach the debugger and pause from the debugger when it's frozen
See where your main thread is hanging
hmm well for one you're allocating a new list every time instead of reusing the same one, so if it contains a lot of data you'll pressure the GC a lot
Yeah - definitely there's some bad optimization stuff going on here, was gonna tackle that in a second pass
You'd have more than a comment if you saw my A* implemention innards 😛
(But that shouldn't kill unity so thoroughly.. at a minimum life would return after GC burped, I would imagine)
hm.. I don't know what to do with this..
maybe an issue with a race condition on some of my internal lists?
hard to tell but looks like something related to something in System.Collections
Is this the main thread?
🤷♂️
I'm certainly not doing anything async in here
Should be all sync on MT as far as I'm aware
looks like not the main thread but a burst thread
the objects (unity MBs) that are subscribed to the C# events.. unity doesn't do any magic to thread those, right?
no, but you do need to change to the main thread to see what it is doing
oh, ok.. lemme try again (restarting unity)
just use the dropdown menu i screenshot to change the thread you are viewing
Like, is the following problematic in any non-obvious way?
public class MechMiceMap : BetterMonoBehaviour
{
public Action<List<HexPoint>> ShowPathChanged; // emits the event with a list to the path
}
public class TerrainHex : BetterMonoBehaviour // 200+ of these
{
public void Initialize(HexPoint p, MechMiceMap map)
{
_map.ShowPathChanged += OnShowPathChanged;
}
private void OnShowPathChanged(List<HexPoint> path)
{
Cursor.ShowMoveCursor(path.Contains(_location));
}
}
(there's ondestroy unsubscribes, I just omitted it from the above)
but shouldn't matter, terrainhexes live "forever" here
Got this one this time
what is the main thread? there's many here that VS attached to
start stepping through it to see what it's doing, it isn't likely stuck on that specific line
Oh, ok, I'm able to step through it now.. I'll mash through a bit and see if that helps
Or an infinite loop inside Update
it's definitely in the TryGetPath though
Hmm there's no loop in Update so nevermind there
I mean, the maps' pretty big so pathfinding worst case could be bad.. 331 hexes it looks like
it's entirely possible I have a bug in my A* implementation, this is .. like.. first pass debugging
You could easily have a factorial algorithm or something
I can paste the code for it but... asking anyone to load this into their brain is a big ask 😛
TryGetPath code would be good to see
it should be lean but.. hard to know for sure
I'll pastebin it, gimme a few minutes, gonna step through a bit and see if anything pops out
but honestly.. it's a lot to load into your brain 😛
I'd jump to the TtyGetPath stack frame and step through from there
AHHHHHHHHHHHHHHHHH
Everything else in the trace looks straightforward
looks like I didn't catch the HexPoint.None from the path finding algorithm lol
and since i hardcoded my HexPoint.None to that "real" value of absurd size... having the mouse click "in between" the hexes (there's like a one pixel gap) is leading my A* pathfinding to .. you know.. try to find a path to a hex several million units away
In retrospect, pasting the code might have been helpful because.. it was in the first couple of lines
Check if the map contains from but not if the map contains to
Thanks again PB, add it to the tab 🍻
(you too @thin mesa)
(honestly if PB ever were able to actually collect the beer tab he's earned from me in the past few years it'd break me)
🎉
honestly it's pretty fast even for how badly optimized it is
i'll dig into optimizing it more later.. maybe it's using gigs of ram and I just don't know yet 🙂
Question: Is there anyway of telling which gameObject fired and event?
I have a multiple cursors for different players in a game. When a key is pushed, it fires the event that it has been pushed. I just want to know which instance of object(s) pushed the button.
Neat! Does it alwyas work? Saw a couple of frames like this
Nope, fixing that now
Just had an error in the "backtracking" part of the code where it backtracked from the end to the start without keeping them adjacent
So each tile highlighted is, in fact, one step closer, just not necessarily adjacent to where you are 🙂
A* is hard.
Now time to optimize.. maybe.. or maybe leave it for another day since my brain already hurts
(now witness the power of this fully armed and operational A* star)
Not an advanced question, stuff like this is more suitable for beginner or general next time.
And no, you would need to pass the object as a parameter to do this.
I see
Stuff like that doesnt look like it should be an event in the first place, but not really sure what you're doing with it.
wait so,, if I have a compute shader, can I expect this to behave?
cs.SetInt("_Blah",0);
cs.Dispatch(...);
cs.SetInt("_Blah",1);
cs.Dispatch(...);```
because I'm getting behavior suspiciously similar to what I would expect if setting properties wasn't synchronous
..if I instantiate the compute shader, and use the clone for the blah=1 case, everything works fine
what in the world
I thought it was synchronous... Maybe setting and dispatching through command buffer works?
https://docs.unity3d.com/ScriptReference/Rendering.CommandBuffer.SetComputeIntParam.html
Thread.Sleep(20) before each Dispatch makes it work
GL.Flush() does nothing, Graphics.WaitOnAsyncGraphicsFence also does nothing
only sleeping the thread, or, using two separate compute shaders, makes it work
the heck
Very weird. It must be something to do with the editor rendering loop being weird. I've never observed anything like this or seen anyone talk about it.
ok I might not be alone here https://discussions.unity.com/t/compute-shader-during-design-mode/684243/11
https://docs.unity3d.com/ScriptReference/ScreenCapture.CaptureScreenshot.html
How can I apply the superSize logic in the screen capture method here? I want to extract the content of my editor window, but the image quality changes depending on the zoom ratio, so it is blurry.
private static void CaptureWindowScreenshot()
{
EditorWindow inspectorWindow = EditorWindow.GetWindow( typeof( Editor ).Assembly.GetType( "UnityEditor.InspectorWindow" ) );
inspectorWindow.Focus();
EditorApplication.delayCall += () =>
{
int inspectorWidth = (int)inspectorWindow.position.width;
int inspectorHeight = (int)inspectorWindow.position.height;
Color[] pixels = UnityEditorInternal.InternalEditorUtility.ReadScreenPixel( inspectorWindow.position.position, inspectorWidth, inspectorHeight );
Texture2D inspectorTexture = new Texture2D( inspectorWidth, inspectorHeight, TextureFormat.RGB24, false );
inspectorTexture.SetPixels( pixels );
byte[] bytes = inspectorTexture.EncodeToPNG();
System.IO.File.WriteAllBytes( Application.dataPath + "/InspectorScreenshot.png", bytes );
};
}
I'm making a game that runs on buttons controls. I decided to achieve this through making the buttons an action event that fires and have other scripts respond to it
GL on game jam! (first year in 4 that I'm unable to play 😭)
Hi, i dont know id this is the right channel, but i am creating cross platform game and i am using UGS authentication. One of my platforms requires to use 3rd party acounts, so i decided to use CustomID sign in, but i cannot find how can i link custom ID to an existing acount? Does anybody here have any experience with that? the docs only mention sign in https://docs.unity.com/ugs/manual/authentication/manual/platform-signin-custom-id
I have a SO with these field but when i press plus on inspector i can't add a new value because of reference type i guess how can i fix that ?
Also i have to use reference due to GPNodeData base class , if i dont use reference the derived classes of GPNodeData dont serialize their derived fields
Also should i use nested SO files and if i use that how can i register callbacks to sub so files changes like rename-callback , delete etc,
There is a OnOpenAsset callback but i cant find other things should i use asset preprocessor for that ?
[SerializeReference] public List<GPNodeData> NodeDatas = new List<GPNodeData>();
[Serializable]
public class GPNodeData
{
public GPElementType NodeType;
public string GUID;
public string NodeTitle;
public bool Expanded;
public GPSerializableVector2 Position;
}
using System;
namespace GP.Serialization.DataTypes.GPType
{
[Serializable]
public class GPSelectorNodeData : GPNodeData
{
public GPSelectionData SelectionData;
public GPSelectorNodeData()
{
SelectionData = new GPSelectionData();
}
}
}
You can use #🔎┃find-a-channel to find the channel that is the most relevant to your question
The three code-* channels are reserved for code issues only. If you can't find a channel, ask in the default general talk one: #💻┃unity-talk
What is the best way to detect when the individual sides of a box collider trigger move in and out of collisions?
For SerializeReference, you either need to implement a PropertyDrawer or use a 3rd party library. There is many free implementation on GitHub
this is about as minimal of a repro we could come up with for the compute shader shenanigans
using UnityEditor;
using UnityEngine;
[ExecuteAlways]
public class Ashl : MonoBehaviour { // add this to a game object
public ComputeShader cs; // assign the compute shader in the inspector
private static GraphicsBuffer gpuBuffer;
static uint frameid;
void OnEnable() => SceneView.duringSceneGui += SceneViewOnduringSceneGui;
void OnDisable() {
SceneView.duringSceneGui -= SceneViewOnduringSceneGui;
gpuBuffer?.Dispose();
gpuBuffer = null;
}
void SceneViewOnduringSceneGui( SceneView obj ) {
if( Event.current.type == EventType.Repaint )
Dispatch( frameid++ % 20 == 0 ? BoxAction.Apply : BoxAction.Preview );
SceneView.RepaintAll(); // <-- just to make it re-trigger repaint like an update loop
}
void Dispatch( BoxAction action ) {
gpuBuffer ??= new GraphicsBuffer( GraphicsBuffer.Target.Structured, 1024, 4 ) { name = "googhg" };
cs.SetBuffer( 0, "_gBufSelection", gpuBuffer );
cs.SetInt( "_BoxAction", (int)action );
cs.Dispatch( 0, 1024 / 64, 1, 1 );
if( action == BoxAction.Apply ) {
uint[] dataAll = new uint[gpuBuffer.count];
gpuBuffer.GetData( dataAll ); // downloads the data from the GPU
uint data = dataAll[0];
bool works = data == 0xFFFFFFFF;
string color = works ? "ffffffaa" : "ff2222ff";
string msg = works ? "works fine so far" : "BUG HAPPENED";
Debug.Log( $"<color=#{color}>{msg}: {data:X}</color>" );
}
}
enum BoxAction { Preview = 1, Apply = 2 }
}```
how do i fix this? (im making a gtag fan game)
This is not a code question (and definitely not an advanced issue either). First, look at the logs, then provide any information you find from that in #💻┃unity-talk if you still need help
Trying to recreate this. Haven't been able to, but I believe it. My first thought is that the Repaint GUI event is the issue. Have you tried using something else, like EditorApplication.update and EditorApplication.QueuePlayerLoopUpdate();? The script you provided forces the scene view to constantly refresh even if no updates or mouse movements have happened which, for a box select like you're making, shouldn't be necessary, right?
using 2022.3, built in RP, not in play mode
it happens regardless of whether the force update is there or not, it just makes debugging a little faster
..and it only seems to happen in D3D11
I can't repro this when using any other render platform
Hmm, I can get the error now, but only right after I start Unity, where it will spam constantly until I move the mouse of the scene view, and then the error never happens again. That's not what you've observed, right?
I've tried both with URP and built-in in 2022.3 and get the same thing.
that's exactly the behavior I get as well!
Oh okay. Does the actual case behave differently? Since you were interacting with the scene view and it was still happening.
very similar in the actual case yeah
in the actual use case it comes across as selection being broken for the first 30 selections or so
but after that it works consistently
I just identified a,, hecking big clue
so the bug is that _BoxAction has the wrong value in some dispatches
I tried writing an reading frame index as well, and somehow the frame id was always correct
and so I wondered what the difference was between the frame int and the box action int
and the one difference is that frame ID changes every dispatch, while the box action doesn't
so,, I decided to try - what if make the box action different every frame, in the unused bits of its uint?
and now it works
what the absolute heck
I... don't know... I mean, Unity's managing the default cbuffer for global uniforms. Maybe whatever check is in place for detecting and uploading changes is bugged.
You can create and write your own constant buffer, but that's a bit of a hassle.
Alternatively, _BoxAction could also be a shader keyword to avoid the property altogether, but it doesn't feel good to just bypass this issue when it could be happening with other properties...
yeah, I have found a bunch of workarounds, but they're a little clunky and I'm kinda scared I'll run into this again unless I understand exactly how it goes wrong
Well, I tried it with a custom cbuffer, but it's the same
I think the best workaround for me would be to use another structured buffer for params, instead of using properties
that way I can still clearly define types in the data, and I don't have to add like a custom layer on top of everything to special case every property setter
PropertyField serializedSelectionField = new PropertyField(serializedSelectionProperty);
serializedSelectionField.RegisterValueChangeCallback(OnValueChange);
private void OnValueChange(SerializedPropertyChangeEvent evt)
{
SerializedProperty serializedProperty = evt.changedProperty;
string deserializedValue = serializedProperty.stringValue;
if (string.IsNullOrEmpty(deserializedValue)) return;
bool isInteger = int.TryParse(deserializedValue, out int value);
serializedProperty.stringValue = GPSelectionData.SerializeValue(isInteger ? value : deserializedValue);
bool needToUpdate = serializedProperty.serializedObject.ApplyModifiedProperties();
if (needToUpdate)
{
serializedProperty.serializedObject.Update();
}
}
How can i update serializedSelection field without triggering on value change , if its trigger endless loop corrupts data due to my (ISerializationCallbackReceiver - Serialize , Deserialize methods)
Hey, I posted a question into #🔊┃audio that I could use some help with if anyone here has some experience with FMOD
dont crosspost
I'm trying to render a few thousand grass blades, with a parameter determining if they have been cut or not. I'm using a graphics buffer and (currently), Graphics.RenderMeshInstanced. Supposedly, this method has a limitation of 511 instances.
When I look at it in the rendering debugger, it appears to render all instances, in chunks of 584. The positions spawn correctly even for the new grass blades, but the problem is, it will only draw them "correctly" for the first batch.
Additional batches seem to have random positions or are randomly cut or not. Any insight into this behaviour, and how I might be able to hack around the limit?
I'm still confused as to why it breaks for the first batch, then seems to work in some capacity for the next, still modifying the instances, just incorrectly
I've tried converting it to use Graphics.RenderMeshIndrect instead but am having difficulty converting the script (nothing will draw currently)
Before I call Graphics.RenderMeshIndirect() in my update loop, I initialize it with the code below
public struct GrassBladeInstanceData
{
public Matrix4x4 objectToWorld;
public float isCut;
public float SpriteIndex; // Randomly pick a grass sprite
public static int Size()
{
return sizeof(float) * 4 * 4
+ sizeof(float)
+ sizeof(float);
}
}
private RenderParams CreateRenderParams(Material mat){
RenderParams rp = new RenderParams(mat);
rp.matProps = new MaterialPropertyBlock();
return rp;
}
public void GenerateGrass()
{
commandBuffer = new GraphicsBuffer(GraphicsBuffer.Target.IndirectArguments, 1, GraphicsBuffer.IndirectDrawIndexedArgs.size);
commandData = new GraphicsBuffer.IndirectDrawIndexedArgs();
// If no random positions are set, generate them
grassMatInst = new Material(grassMatMain);
rp = CreateRenderParams(grassMatInst);
grassInstance = new GrassInstance();
grassInstance.mesh = mesh;
grassInstance.gbInstData = new GrassBladeInstanceData[numGrassBlades];
for(int i = 0; i < numGrassBlades; i++)
{
... (Get all positions, create grass matrix, set it below)
rp.matProps.SetMatrixArray("_ObjectToWorld", grassMatrix);
}
commandData.baseVertexIndex = mesh.GetIndexCount(0);
commandData.instanceCount = (uint)numGrassBlades;
instancesBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, numGrassBlades, GrassBladeInstanceData.Size());
instancesBuffer.SetData(grassInstance.gbInstData);
rp.matProps.SetBuffer("_PerInstanceData", instancesBuffer);
}
which I access in my shader from
struct InstanceData{
float4x4 worldMatrix;
float isCut;
float SpriteIndex;
};
StructuredBuffer<InstanceData> _PerInstanceData;
void GetIsCut_float(out float Out){
Out = 1;
#ifndef SHADERGRAPH_PREVIEW
#if UNITY_ANY_INSTANCING_ENABLED
Out = _PerInstanceData[unity_InstanceID].isCut;
#endif
#endif
}
which is accessed in shadergraph. It worked fine with Graphics.RenderMeshInstanced when it was in shadergraph (and others have gotten Graphics.RenderMeshIndirect working with it) so I don't think it is the problem
Any help would be greatly appreciated, I've trowled the discord archives for similar issues and am at a loss
so I'm trying to "flip" my model for my game, what's the best way to do this?
I have a character in a fighting game who can face left or right, but I can't rotate them 180 degrees because then they don't face the camera properly
my first instinct was to just make the X scale -1 but that messes up the rig in weird ways
you can see the character facing the right looks normal, but the character facing the left has less-bent knees and is sinking into the ground a bit
is there a good way to flip the model without making a new animation for each animation that's just facing the other way?
did you scale the parent of the SkinnedMeshRenderer?
a little update - turns out this bug was introduced in unity 2018.4 and has been broken since (aras looked into it and found out!)
submitted a bug report now bc this is clearly not intended behavior 
nice 😌
Good to know aras has some doors open to Unity still, you could always count on him to figure out obscure graphics related problems like this.
my workaround for now is to just not use the SetInt parameters, and only use buffers
public class CompyootShader<P> : IDisposable where P : unmanaged {
public readonly ComputeShader cs;
private ComputeBuffer @params;
public CompyootShader( ComputeShader cs, int stride ) {
this.cs = cs;
this.@params = new ComputeBuffer( 1, stride, ComputeBufferType.Structured );
}
public void SetParams( int kernelIndex, P newValue ) {
@params.SetData( newValue, 0 );
cs.SetBuffer( kernelIndex, ShaderProps.PARAMS, @params );
}
public void SetBuffer( int kernelIndex, string property, ComputeBuffer buffer ) {
cs.SetBuffer( kernelIndex, property, buffer );
}
public void Dispose() {
@params?.Dispose();
@params = null;
}
}```
and then you use it with a struct for your params (the <P> above)
struct SelectionParams {
public const int SIZE = sizeof(uint) * 2;
public uint boxAction;
public uint frameId;
}```
so then before dispatch, you do
cs.SetParams( 0, new SelectionParams() { boxAction = (uint)action, frameId = frameid } );```
Hey all,
Sorry again for pinging you.
@torn rose @sage radish
So couple days ago I made this.
What do you think ?
The code:
https://pastebin.com/kvfksuyv
Any idea how I can add twist to the line like RDR2 ?
Pastebin
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.
Your line looks to be a bit stiffer, or has more damping. It needs to be more elastic to bounce back and forth like that. And the rod needs to induce the sideways force in its swing, but it looks like yours is, it's just getting dampened out too quickly.
At least, I think that's what you mean by twist
anyone knows how fast is animation retargeting in unity ? (in ms on avg?) or if i can debug it ?
I mean in RDR2 you can see, it swings to the side a bit.
I'm not talking about its bouncing.
You mean before the cast?
Part of it is probably the motion of the rod. In the RDR2 clip, it looks like it's at more of an angle, whereas in your clip it's pretty straight.
No, during the cast and throwing in part. You can see, it swing to the right side slightly.
Hello, so I have a view direction, how can I convert it so it can work with raycasts? View direction as in x = -90, 90 and y = -180, 180
this isnt an advanced question, this stuff should be in #💻┃code-beginner
this also looks like euler angles, so one way can be using this https://docs.unity3d.com/ScriptReference/Quaternion.Euler.html to get a quaternion.
Then you can rotate a vector with Quaternion * Vector3. (2nd example on the page)
https://docs.unity3d.com/ScriptReference/Quaternion-operator_multiply.html
yes
actually I've tried scaling both the parent and an empty parent to it and neither worked
I figured it out, I had to scale the parent of the rig, not the whole thing
I was able to get this to work using Graphics.RenderMeshPrimatives. I don't know the ramifications of this change but it seems to work well so far
I might be wrong, but indirect means your params for how many instances& triangles to render is available from your GPU, and mostly should only be used when your data exists on the GPU(because it’s costly to get it back). If you have that info on the CPU, you shouldn’t use that function call.
I was under the assumption that if I had something like meshes that have a static world position, it's entirely possible to upload the params from the CPU to the GPU once, and then they'd continue to be there (ie, render in the correct position), so something like grass would be a good use case for Graphics.RenderMeshIndirect
Yes, in that case, RenderMeshIndirect is better because RenderMeshPrimitives will copy your data every time you call it, so the ramifications of doing it is it’s slower.
I figured. I just can't seem to get it to work (hince the code dump). RenderMeshPrimatives at least doesn't have the 511 instance limit Graphics.RenderInstance does, but I hope to migrate it at some point
Hello, I came across this tube renderer script on Github and it works just like I wanted. It's basically like a line renderer but it generates a tube mesh instead. The problem is there's a comment that says that the script causes a memory leak, I have no clue on how to deal with that and I need some help on making the code better
Code: https://gist.github.com/mathiassoeholm/15f3eeda606e9be543165360615c8bef
There is no memory leak, the term is being used incorrectly. One thing I would do is to remove lines 42 and 43
not sure what @upbeat path means because there are two types of memory leaks in that script, yes!
- on line 83, 122, 142 and 192, new arrays are allocated on every call, which puts a ton of pressure on the GC. One way to resolve this is to use persistent
List<T>instead that are cleared and re-used, instead of recreated on every call new Mesh()is used with[ExecuteInEditor]which means that any meshes created will not be automatically cleaned up, and might even get saved to the scene, which is a different type of resource leak. This can be avoided by settinghideFlagson the mesh, likenew Mesh(){ hideFlags = HideFlags.HideAndDontSave };
unrelated to memory, running the mesh generator in Update() is generally not a good idea either, because you'll be paying that cost every frame, not only in-game, but also in editor
generally you'll want to only regenerate the mesh when it's either non-existent, or has changed
- also needs to be considered in play mode. Any created Unity Objects will persist until the slow
Resources.UnloadUnusedAssetsmethod is called. Unity calls this automatically during scene loads.
but that happens when leaving play mode right? so it's less egregious at least
Hmm, either that or next time you enter playmode, but if your game mostly happens in one scene with no scene loads, those objects will stick around forever unless you Destroy them yourself or call UnloadUnusedAssets.
I guess I meant "in build" instead of "in play mode".
The most common case where this happens is when using Renderer.material, which creates an instance the first time it's accessed per renderer, but Unity never destroys it except during scene load!
https://docs.unity3d.com/ScriptReference/Renderer-material.html
This function automatically instantiates the materials and makes them unique to this renderer. It is your responsibility to destroy the materials when the game object is being destroyed. Resources.UnloadUnusedAssets also destroys the materials but it is usually only called when loading a new level.
A memory leak is a very specific term, C# does not have memory leaks unless you are using unsafe code
alright! well, most people I've been around have never used the term in that super strict way
No need to be pedantic
Unity has memory leaks though, and Unity C# scripts that create and manage native Unity objects, like Mesh, can have memory leaks.
currently i'm trying to render a lot of foliage using DrawMeshInstanceIndirect for android platform. when i'm using vulkan api, it works fine. but when switching to OpenGLES3, it doesn't works at all. what is it that i'm doing wrong?
also to clarify what I meant, doing things like this would help reduce the GC pressure!
readonly List<Vector2> uvs = new(); // cached list to avoid re-allocating
private List<Vector2> GenerateUVs() {
uvs.Clear(); // instead of Vector2[] uvs = new();
for( ... ) {
// ...
uvs.Add( new Vector2( u, v ) );
}
return uvs;
}```
there's also a built-in CollectionPool that can help remove nuances with caching lists in the field section. ensure to Release it after use.
Random question, I have a bunch of characters that all have the same script calling Physics.OverlapSphere(), I can change it to OverlapSphereNonAlloc and add a buffer for Colliders. Since unity is single threaded, can I make that Collider array static and shared between all the instances?
Yes, you can.
I won't but I thought coroutines (at least the monobehaviour one) is still on the same thread?
Sure but it's delayed, so if you invoke overlapSphere, then wait until the end of the frame, other instance might've ran and updated the data
It is safe to do though, I am pretty sure at least. Just performance may suffer.
No, the data would be different. Performance is the same, the coroutine would just be working with the wrong colliders.
But as long as you don't yield between the overlap and processing the colliders, there's no chance of issues.
Ah okay. I don’t use coroutines much. 😅
oh, yeah, I misunderstood you meant delayed calling the overlap, I'm going to process the results immediatelly after the Physics.*NonAlloc call, thanks!
How many characters are we talking? Just wanted to point out that OverlapSphereCommand also exists:
https://docs.unity3d.com/ScriptReference/OverlapSphereCommand.html
Not sure how to differentiate which hit belongs to which overlap though 🤔 Gotta look into that
Ah nvm, the doc explains it ofc
oh, I didn't know about that. Definitely not need it now though 🙂 (probably don't need the results buffer static really, it was more making sure I understand it correctly
is there any way to have custom player loop sub systems show up in the profiler window?
im having great success with optimization using the PlayerLoop API, but i'd like to know how much time it actually saved and still takes
unfortunately, none of the sub systems show up by default
Yes, wrap everything in your callback method with a ProfilerMarker
https://docs.unity3d.com/ScriptReference/Unity.Profiling.ProfilerMarker.html
ahhh, perfect! thats it
You can nest them as often as you want to see more detailed timings.
appreciate the quick help!
Thanks for the help! I tried to do most of the things that you said and here's the code I ended up with: https://pastebin.ai/xznrc4zeue
I'm not sure if I'm doing it right tho, would appreciate some feedback
looks good to me! I would also add hide flags on the mesh object, just in case
Oh yeah forgot to add it, really appreciate the help
Is there a version of Vector3.Slerp that allows to define the plane in which the vectors interpolate? (I'm switching characters look at vectors and to prevent head snapping I'm trying to slerp the look directions, most of the time it works exactly as expected but sometimes the look at target will fly in an arc above my character instead of in front of them)
(just noticed this comment in the docs example: // move the center a bit downwards to make the arc vertical so I think this was happening because I was using the characters transform position as the starting point for the vector directions.
Two non-Zero, non-colinear vectors define a plane, this plane is used for the slerp. If you hit the undefined planes, you just need to nudge one vector onto the plane you want.
Project the vectors on the desired plane first
I ended up using this Vector3 directionSource = new Vector3(transform.position.x, (0.5f * (targetPos.y + oldTarget.y)), transform.position.z); as my vector origin, this would fail with the character being exactly between 2 targets, but I only allow targets within a certain Fov, so it shouldn't happen.
This is equivalent to projecting your vector on a particular plane at that height, so yeah
hmm.. my thinking was if the new POI look target is somewhere high above this will give me an arc upwards, where as if I projected the vectors I'd need another transition from the projected view direction to the actual view direction
can I create my own message thingy in monobehaviours without polymorphism?
lemme explain.
I want to add a method to my monobehaviours that is like Update or Start or Awake, that is, called automagically by something else but I don't really know how would I go about it 🤔
I don't want to make my MonoBehaviourWithExtraMethod class, I want it to work with any Behaviour out of the box 🤔
is there a way to see all behaviours ever in the scene or something? 🤔
I feel that if this exists, it's something low-level-ish 🤔
interesting... it seems gameObject.SendMessage is the thing...
now... how do I see every object in the universe 😛
FindObjectByType<UnityEngine.Object>()
that makes sense! Thanks! 😅
At this point, I think that FindObjectByType can eat an interface and find me behaviours... so I might ditch the message system... 🤔
But this has been really useful! thanks ❤️
Actually you want https://docs.unity3d.com/ScriptReference/Object.FindObjectsOfType.html
Actually, FindObjectsByType is the faster newer alternative to FindObjectsOfType.
If you open your own docs link, you can even see they recommend using FindObjectsByType instead 😄
indeed but at least these return an array rather than just 1 which is what OP was looking for
Does anyone ever worked on a full body fps controller? if so I need help
Hi there im newish to unity jsut play around as much as i can why i wait for my other dev to do stuff ive come up with a idea for my game and wanted to know if there is any thing i need to install to make steam dlc work with my game so if i download one dlc and then get another dlc the game would pick up what i got and turn them both on at the same time. I hope someone can understand what i mean as i am dislexic and find it hard to say what i mean
what would you call it when you have a list of objects but you only add elements to it and forget to remove anything from it
that is still not a memory leak in ur book, yes?
the first case is not a memory leak in any definition of the word
what's the point of the garbage collector then lol
I'm aware it's not technically a memory leak yes c:
A list of objects not released but only added to is not a memory leak
It's still being managed by .NET
You can get a memory leak through allocating in unmanaged memory, *or circular references, otherwise it's very hard to
Note, memory leak doesn't mean you're forgetful and keeps growing, it means there is literately no reference to it by .NET, and you don't maintain any reference--it is unreachable by your process
GC will not clear your memory leaks, but it will free your list if you stop referencing it
There are several definitions of a memory leak. Wikipedia for example says:
"In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations[1] in a way that memory which is no longer needed is not released. A memory leak may also happen when an object is stored in memory but cannot be accessed by the running code (i.e. unreachable memory)."
I prefer to refer to the first one as a functional leak and the second as an actual leak. In the end, both have the same outcome, so why not call it the same for simplicity?
You can refer to it however you like ig, in my experience most people refer to actual unreachable memory as a memory leak, but if you say functional leak you can probably get your point across better.
The company I'm working with and whatever other companies we're working on as well always refer to a memory leak as just memory consumption growing up over time eventually leading to a crash. This is regardless of what engine or language we're using. Though, I must note that it's in Japan. And specifically in gamedev. Perhaps it's different in other countries/in the west.
I've never been a part of a game dev company, I've mostly interacted with people from database hosting/server management companies. I was just taught memory leak meant this--as in it's a leak because your cannot recover it. That kind of memory loss I refer to as just accumulation of wasted memory.
In the end, in the built application, you can't recover from both.
How would you set up a camera stack like this?
- Layer with post processing
- Layer without post processing
- Layer with post processing
I have this setup in my game with 3 layers
- Background/Everything else besides the player and UI
- UI
- Player
I have it set up with a camera stack so the player is always on top of the UI
but the problem is that whenever I try using my post-processing, if I only use it on the main camera, it affects everything except for the player, but if I put it on the player camera, since it's above the UI camera, it puts it on the UI which I don't want
is there a way to make the UI unnaffected?
first pic: only on main (non-player or UI) camera
second pic: only on player camera
you can see that the first pic is problematic because the player looks bad without the post-processing and the second pic if problematic because the post-processing gets applied incorrectly and it's affecting the UI
this isn't a code question. but if you just want the player on its own to be rendered above the UI but still have it and everything behind the UI affected by PP you could have the player camera render to a render texture that you display in your UI
whoops, where would I put this then?
also I was kinda thinking that but I hate messing with render textures lol
probably #💥┃post-processing or the relevant render pipeline channel for whatever rp you are using
heya, can anyone see a reason why the above DrawProceduralIndirect would not work, but the below DrawMeshInstancedIndirect does?
Respected,
I want to make a car racing game, but I am confused about the AI cars, can I use RCC plugin with Machine learning input and how?
Or any other alternative way?
if i am reading previous games correctly on a mechanic level, they have a set speed and trajectory involving the map layout. once you hit a specific speed/trajectory the NPC's will adapt, if you can overcome that distance they go back to a relative distance
if i want that some car hit the player car after some distance and some focus on the destination..
you will need some restraints via npc behavior. mainly acceleration and hitbox distance
Thank you
I will read about nps..
Respected, I also want to make this..
but after 1000 times try, I didn't achieve this particle system..
can anyone please help me
Ask visual effects questions in #✨┃vfx-and-particles
Hey all, when i create ListView in editor i give a List in a Scriptable Object as a item source.
The problem is when Bind elements invoked the added elements coming null in bind action.
I mean when i query the scriptableObject.SomeList[bindIndex] it returns null but i checked in debug mod the data is created and its valid in SO ?
What can i do i tried override listViewController and added two new action onItemsAddedBefore , onItemsAddedAfter then i call refreshAlItems or Rebuild after onItemsAddedAfter but still comes null ?
Should i markDirty and save asset in onItemsAddedAfter action or what can i do 😄
@short junco
If you are creating assets, I would expect that you need to actually create the assets, not really on the built in Add function
Just a random note because it cost me quite a bit of time chasing my tail.. Don't forget that IEnumerable.Append() doesn't modify the original list, but instead returns a copy of the list with the new item appended. Use Add(). 🪳 🪳 🪳
(have been writing too many tween sequences and Append()-ing tweens, and was stuck for a while wondering why something else wasn't working.. because I was appending items to a list.. which was showing up with 0 elements when it came time to consume the list)
Yeah it's LINQ, it returns a new instance and is evaluated lazily
Less so "a copy of the list," but more it returns a new enumerable where it goes through all items of the list first, and then the appended item.
Example:
List<int> l = [];
IEnumerable<int> enumerable = l.Append(42);
l.Add(0);
int[] result = enumerable.ToArray();
// -> [ 0, 42 ] !!!
Yeah. It just... surprised me, I expected it to work like Add(), I was chasing 'the wrong thing' wondering why it wasn't working.. I had a lambda that was creating this list and I was thinking the items inside were going out of scope (which is why it wasn't working)
LINQ is base on functional principle, it is what you really should keep in mind.
MessageBroker.Default.Publish(new MyStruct
{
OnStart = () =>
{
List<CommandBase> storyCommands = new()
{
new Thing(...),
new Thing(...),
new Thing(...),
new Thing(...),
};
}
});
This worked, but then when I needed to conditonally add an item to "storycommands" i refactored to:
MessageBroker.Default.Publish(new MyStruct
{
OnStart = () =>
{
List<CommandBase> storyCommands = new();
storyCommands.Append(new Thing(...));
if (something)
{
storyCommands.Append(new Thing(...));
}
storyCommands.Append(new Thing(...));
}
});
it suddenly stopped working.. and I was thinking it was something related to the lambda
Not my use of Append() which is.. what the actual problem was :p
hi guys i have an issue with an enumerator that changes my FOV for the player's camera. the problem is that when i call the function to change my fov, when I run it the first time, it changes smoothly, but when I finish (eg. when the player stops wallrunning and the fov needs to go back to the original), it does not change smoothly, it just snaps back instantly. the code is here: https://paste.ofcode.org/385M5nDQfeJuswndPTkvmVm. here's also a video to show what i mean. here's how the function is used in the sliding code as an example:
if (camFX.defaultFOV < 120f) { camFX.ChangeFOV( camFX.defaultFOV + extraCamFOV); }
// when I finish the slide
camFX.ChangeFOV(camFX.defaultFOV);
i didn't know if this was counted as an advanced problem, so I put it in here
This probably isn't an advanced problem.. the code is doing exactly what you described.. You'd have to lerp it back to the original
I'd probably actually suggest using Cinemachine for this type of stuff, there's a bit of a learning curve but you'll have a much easier time with camera switching with it
i have cinemachine already
thats the problem, before I used DoTween for this but now it doesnt work because of cinemachine
oh, then just... make one fov camera that's 120, and one that's the default (90?) and just setactive() the camera you want
yeah but the problem is when the user selects a different default FOV
this will be much simpler.. all you do is set the camera active (and the other inactive) for the camera you want to blend to.
for example if i want to set my default fov to 100 in settings, it becomes a bit of a mess
the problem with my original camera system was that it was lagging really hard which is why i switched to cinemachine - I used DoTween on the original one with cam tilt on wallrunning and fov change as well
I didn't see the video, that you had cinemachine.. so.. make two cameras, one for FOV120 and one for FOVDefault (90? 100? whatever the player wants in the settings) and then when you start the slide:
public void StartSlide()
{
FOVDefault.gameObject.SetActive(false);
FOV120.gameObject.SetActive(true); // cinemachine does all the magic for you
}
public void EndSlide()
{
FOVDefault.gameObject.SetActive(true);
FOV120.gameObject.SetActive(false);
}
doing it with DT is fine but is gonna be a lot more work .. whenever an action starts/ends you're gonna need to check if the tween is running and kill/complete it accordingly
the pattern I use (almost everywhere) for doing stuff in DG is to save a reference to the sequence tween and if it gets restarted/ended:
if (_someSequence?.IsActive()==true) _someSequence.Kill(); // or .Complete() if you need OnComplete() callbacks
yeah the DT function just wasn't working DOFov() didnt recognize the cinemachine cam as a camera
don't mix dotween camera stuff and cinemachine, you're gonna have a bad time imho
so no dotween
just make one camera for each different ... "camera" (whether that's a different zoom/fov/tilt/etc or an actual different camera view) and then just turn those cameras on/off as you need
cinemachine will take care of the blending for you, and won't be a pain in the jewels when you do things like swap to another camera while a blend is happening
you can still have options menu
just make it set the options on your "primary" cam
ok ok
wait, one question: can I assign a value on the fly on a cinemachine cam's fov, before I activate it, will that work?
Sure, although if a blend is in progress I'm not sure what would happen
like:
{
defaultCamera.gameObject.SetActive(false);
slidingCamera.Lens.FieldOfView = defaultCamera.Lens.FieldOfView + extraFOV;
slidingCamera.gameObject.SetActive(true);
}```
will that work?
er, yes, but ... that's probably not how you want to do it.. I'd probably just set it (once) at startup and again if the user changes their settings
and i'd probably just set it to 120.. if a user wants to play with 120 as the default it's probably going to get weird if you "zoom" to 180 or 150 even
thats the idea, if the fov is less than 120, if its not, it doesnt increase
just a SOLID principle - your camera zooming should literally just toggle a camera on/off (between zoom and normal cameras), not be mucking with the fov
ok
set the fov of the "zoom" camera and the "default" camera in as few places as possible so you aren't trying to debug it later and remember all the different places it could change
but.. yes, that should work
and yes if i use that setting it still does the same thing
I'm having a tough time understanding your code - why are you checking the default camera's fov each and every time you slide? i wouldn't do that at all.. just ... start slide = turn on the cam, end slide = turn off the camera
you can test this out more easily by setting the blend time to like 10 seconds, and then turning on the "slide" camera in the inspector in play mode
i believe this boi might be the problem
can you paste your entire Sliding.cs to pastebin?
btw stop comparing floats.. that's not gonna work..
if (Input.GetKeyDown(slideKey) && (horizontalInput != 0 || verticalInput != 0)) { StartSlide(); }
you'll have to google up why you can't compare floats, but that's not the problem here
the problem is your cameras aren't on the player object, they're just ... floating in space?
sliding.cs looks fine but... a couple of things.. if you parent your cameras to the player object (which you should, because you want the camera to be looking out the players eyes, right?) then your sliding.cs StartSlide and StopSlide that change the scale of the object are going to break the cameras
I'm not sure what you're trying to do with changing the scale of the player object.. usually you don't want to do that?
if you're trying to make your object bigger/smaller (pm.crouchYScale?) then make the mesh bigger/smaller, not the player object
thought problem for you: if you parent the camera to the player, and the camera's localposition is (0,0.5,0) (0.5m "up" from the center of the player), then if you make the player scale 50% - the camera will be 0.25m "up" from the center. Maybe that's what you want, though
In any case.. parent your cameras to the player, since otherwise you'll have to manually move these cameras around as the player moves around, which isn't something you need to do for a first or second person view
ok
i found out that if i use cut instead of ease in out on the cinemachine brain, it works fine
thanks for the help
One who is generally familiar with C#, which does not concern Unity ?
I'm programming a c# program to clean the PC.
If I clean independently in my program Manuel this works with browser cache data deletion and the history, but I have also written an automatic cleaning where that does not work. It cleans the recycle bin automatically