#archived-code-general
1 messages Β· Page 419 of 1
make sure your Selected graphic /quality setting is the one you're using in the editor
unity made it a bit confusing there
the lightest gray one means its the one selected
yeah it should be the right one
I deleted the other quality settings just in case, and it's still doing the the vsync despite being set to don't sync in the settings
yeah
unity 2021.3.11, BiRP, idk if it changes anything
I don't think so, but I'll check
I'm refactoring my code to use IDragHandler instead of OnMouseDrag and am running into problems.
old code : https://hastebin.skyra.pw/zoterepojo.csharp
new code : https://hastebin.skyra.pw/izovuwesed.csharp
The old code works just fine with some minor bugs in clicks with the ui going through. The new code I cannot even get to show debug logs. I have a Mesh collider on the object I want to drag. I have a physics2d raycaster on the camera. I also have an event system setup. Could you please take a look and give me a resource to look at to get Idraghandler to work? <reposting for visibility>
why would physics2d raycaster work with a mesh collider?
Mesh Collider is a 3D collider
it uses Meshes
I used a regular physics raycaster and that didn''t work either
did your mesh collider actually have a mesh ? cause that already sounds wrong
if its 2d why did you put mesh collider
unless it's somehow hidden in a script where it makes no sense, there's no targetFramerate stuff going on
It's 3d, I can't find an example of 3d idraghandler tho
any of the Event System functions will work if you put the proper physics raycaster
does ur mesh collider actually have a mesh in the slot?
yes
Yeah thats strange to me. You searched all the scripts in your solution through IDE right? maybe some asset or something was doing it ?
I even tried setting the target framerate to something else instead and it didn't change anything
are you sure its not your GPU ?
like maybe some setting your got in your NVIDIA/AMD Panel ?
oh lawd...I just thought of something
where should I look in the nvidia control pannel? I'm not very familiar with it
Can you check the Game View , click the Apsect Ratio resolution
oh?
Its explained with decent detail here, may be that the gpu is taking too long to complete the frame or something else: https://docs.unity3d.com/6000.0/Documentation/Manual/profiler-markers.html
it's disabled here as well, but I was profiling a build anyway
oh okay then
I might still suspect your GPU then
did you try another game or something to see if thats capped?
I would be surprised if it took that look to render though, this is a fairly low poly game with low res textures, it has a couple post processing effects but that's about it.
But I'll read the article
Some post effects can be quite costly, same for high resolution shadows with complex scenes. Ideally you add something so you can toggle these things on/off to inspect the impact they have on framerate
no framerate cap in my settings, and vsync is set to "use applications"
this is very strange
maybe try setting it to off hit apply and restart the game again
or you have something like GSync on or something
what is gsync?
oh its nvidia specific. Syncs Gsync monitors to Gsync compatible cards to basically do what VSync does but with less input lag
ah I see
variable-rate synchronization, in essence
Isn't the point of using Path.Combine() is that it uses the OS appropriate slashes?
string path = Path.Combine(Application.persistentDataPath, "UserContent");
path = Path.Combine(path, "TextFiles");
DirectoryInfo dir = Directory.CreateDirectory(path);```
Is it supposed to use conflicting slashes like this? I'm currently using unity 6.0000.0.31f1
> Creating Directory: C:/Users/phili/AppData/LocalLow/Company/OpSys\UserContent\TextFiles
> UnityEngine.Debug:Log (object)
it wont change existing seperators in the path
Most file systems, and programs that use file paths, will treat both Unix style / and Windows-style \ interchangeably
nah, I still got 5 to 10 ms of GfxDeviceD3D11.WaitForLastPresent and I don't know why
yes, but if combine is using OS appropriate slashes why is it not consistent with the path it's returning?
I see from the graph you are rendering 150k tris in that frame. Can we see an example of a frame? If you have a lot of overdraw it can really impact gpu performance
is it just in the build but also the editor ?
\UserContent\TextFiles is what Path.Combine created seperators for and thats it
it's called Gfx.WaitForPresentOnGfxThread instead but the same sort of thing happens in editor
Yeah I'm just confused why Application.persistentDataPath() and Directory.Combine() are not consistent with each other. I know the slashes are mostly interchangeable but I thought the entire point of .Combine() was so something like that didn't happen
Path.Combine uses your system file separator: \
Application.persistentDataPath is basically a static string and that string has / in it
What unity returned is what they deem to be correct for the platform but Path.Combine() will do what it thinks (and this is from the .net framework and not unity).
It will work anyway so dont worry. You have to use something that will re make the entire path to have seperators be consistent
I just tried removing most of the polygons from the scene, and aside from the rendering itself being a bit faster, it didn't affect the huge amount of GfxDeviceD3D11.WaitForLastPresent
try with a 100% empty scene, no post processing. If its still there then you can be sure its not the performance. Did you check the quality settings to see if vsync is enabled there?
I did, it's disabled
I'll try the empty scene
If you are using URP/HDRP do check the assets for those too incase some dumb thing was enabled there.
in my HDRP game, I control VSync entirely by setting QualitySettings.vSyncCount
also try logging
no I'm using built in
also I checked with an empty scene, the same thing happens, although amount of time it takes is a lot more inconsistent, and somewhat lower on average. Still takes several ms
logging?
void Start(){
Debug.Log($"vsync count: {QualitySettings.vSyncCount} fps target {Application.targetFrameRate}");
QualitySettings.vSyncCount = 0;
Application.targetFrameRate = -1;
Debug.Log($"vsync count: {QualitySettings.vSyncCount} fps target {Application.targetFrameRate}");
}```
Hmm that is puzzling. Can you check with the frame debugger that its not doing anything still? Also what framerates were you getting in this empty scene? If you saw it go above/below your refresh rate it would kinda disprove the vsync theory
ah yeah I'll try that
could also just be your pc is suffering already it cant run unity or your build well π
I'd be surprised, especially for GPU stuff
my CPU is kinda eh, but I have a 3060, so it's surprising that I'd have rendering issues on something like that
notably, i would also try putting a bunch of crap in the scene so that it takes longer to render
Hello :)
I'm trying to find all child objects inside a hierarchy of child objects whose name starts with a certain string, how would I go about doing this? I already have the gist of it but i cant for the life of me find something akin to Contains or StartsWith that would help me here
foreach (GameObject button in encounterButtons.transform.Find("Scroll Rect/Mask/Grid/")+ something)
You'd want to recursively walk the transform hierarchy.
Do these objects all have a certain script on them? using names isnt reliable and should be avoided when possible.
and, yes, this sounds like a bad idea
what're you trying to achieve?
not "find objects with a certain name"
im trying to find all these objects and destroy them, I knooow that i can find by tag, but i figured this would take less time as im not searching the entire scene when i know exactly where all these objects would be
they all have buttons?
The lovely ideal way would be that you have a list (serialized or made at runtime) of these objects somewhere so you can use that to destroy them later. Tags and names are not reliable.
If you created all of these objects via a script, you should hang on to them in a list
I do that all over the place in my UI code
that is true, they are being created in another forloop
var button = Instantiate(etc.
myButtons.Add(button)
ok ill do that, thanks guys
tags and names bad π
Transform content = dropdownList.transform.Find("Viewport/Content");
UGUI has forced my hand
disgusting
what are you trying to accomplish here
The Dropdown component recreates itself everytime you select it, so to actually modify it you have to grab the newly created objects
the funny thing is that is actually includes references to these objects when it creates them, but it's internally protected
oh yeah, it instantiates a template
pain in the buttttt
Any tips for what to do about this Z fighting? I added an offset to the scale and position of each instantiated game object but it just doesn't seem to take care of it all.
for (int x = 0; x < mazeWidth; x+=mazeScale)
{
for (int z = 0; z < mazeDepth; z+=mazeScale)
{
float offset = Random.Range(-0.001f, 0.001f);
mazeGrid[x, z] = Instantiate(cellPrefab, new Vector3(x + offset, 0 + offset, z + offset), Quaternion.identity);
mazeGrid[x,z].transform.localScale = new Vector3(mazeScale + offset, mazeScale + offset, mazeScale + offset);
}
}```
I just started using GitHub and have a question: Should I create a new repo for each new project I make? And I'm going to be using GitHub for my college projects, so should I create a new repo for each new college assignment or create one repo for the class and go from there?
yes
well tbh its preference
You can certainly have root folder and then subfolders for each assignment
Yes - 1 project == 1 repo generally
it will be much cleaner for sure
Although honestly, for a class, if it's only one person (you) contributing, one repo for the whole class isn't the worst idea in the universe
You may have to do cheeky things like different gitignores in subfolders for different projects though
Alright, thank you!
is there an actual # limit to repos or na ?
I don't think there's a repo count limit, more a total size limit in GB?
Github's policies confuse me, so I could be wrong.
ahh I even thought GB was per project, ig it makes sense if its total per account
there really isn't an official limit on anything but the'll email you usually if your repo does get too big
just says there is displaying limits
If a repository owner exceeds 100,000 repositories, some UI experiences and API functionality may be degraded. For more information, see About repositories.
pretty generous tbh
nom nom feed me your code
yeah that too
free research 
probably feeding all our stuff to the LLMs
Github copilot has entered the chat *
Sorry just saw this. Iβve played with the offset to the point the walls donβt even look right and there are still instances of z fighting lol. Could you elaborate on the pixel discard method?
Hi guys, can someone please help me out? i tried editing this script from an asset i've bought to make the player able to pick up/throw object, but i can't figure out how to make me able to pick the object up, the raycast just doesn't seem to hit the object in any way. i tried some debugging and neither the part for picking up object or the part for throwing them "detect" the object. can someone please help me to figure this out? thanks
i also tried increasing the raycast range but it didnt work
!code
π Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
π 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.
can you show inspector for the object you want to pick up
nvm saw video
also why are there two cameras
the object i want to pickup is not a hand parent, is a separate object
BRO THANK YOU SO MUCH
SO MUCH
I WAS USING MY MAIN CAMERA FOR THE SCRIPT THIS WHOLE TIME
the prefab included another camera i didnt notice
ahhh nice lol
np π«‘
Remove the overlapping geometry?
Er, yeah? Thats basically my question. How can I achieve that. I attempted to remove the overlap via a position and scale offset, but no luck. So I came here for help on how to achieve it.
I mean literally removing the side faces that overlap from the mesh.
Okay, how?
An easier way would be to align the walls so they don't overlap
Yeah that's what I tried to do with the offset
Open the model up, select the face in question, hit delete?
Or, as Carwash said, design them so they fit together better.
I know the geometry shouldn't overlap. I'm asking how do I do this.
It's procedurally generated
Y doesn't need an offset. Only X and Z do, and the offset needs to be the thickness of the wall
and only then, applied on the approiate axis at spawn (not both)
dunno why you're changing the scale
Alternatively, the easiest solution would be to add a corner column that hides the seam.
and improve the look
Might give that a shot, I was wondering what to do about the corners anyway. (aesthetically speaking)
Okay thanks folks
If you look into combining, you can discard intersecting geometry too that unity does provides some tools for
otherwise can do some tricks with stenciling/shaders but way more effort then the easiest solution and that's just don't let them z-fight
so mouse position in world space doesn't work in my second scene (works in first) and only when I move the camera down. The mouse keeps the y of the original camera position seems like.
What should I even look into here?
how are you finding the camera? are you just grabbing Camera.main?
if so, is there a MainCamera-tagged object in the second scene?
yes and yes
in fact
it's like a mobile game kind of things with levels, so I just prefabbed everything I need accross scenes and dropped it in the second scene
maybe something broke there
the camera moves
when I press the down or up button
it moves
but when I click on the screen, it's supposed to do something there
okay, but you should still check what Camera.main actually is
in the second scene, the click position is wrong only when I move the camera donw
you can log it like this
Debug.Log("The camera is: " + Camera.main, Camera.main);
the second argument provides a "context"; you can click on the log entry to be taken to the object
oh yeah
btw
my canvas doesn't render in the game view (it's there in the scene view and enabled in inspector)
When I reload scene, it shows up
maybe it's related idk
OK I figured out the bug...I forgot to delete the default main camera in the second scene, as the other one was included in the prefabs I imported in the second scene...of course
I want to make an invisible mesh to constrain 3d rigidbody dice cubes.. is there an easy way to make a cube mesh and flip the normals?
dice directly on the battlefield - like monopoly go
you could take an existing mesh and reverse the winding order of every triangle
that would turn it inside-out
so, 1,2,3 -> 3,2,1
Cool, yeah.. I don't have experience in mucking with the meshes directly but I asked a coworker and he said a cylinder with surface normals flipped is trivial so he's getting me one π
Followup - my dice are a little "floaty" and slow to roll, given the scale of the world. Can I .. make them ... work differently? I'm not exactly sure what I'm asking - maybe I want a different gravity for them?
(I'd just make it in Blender, instead of trying to do it via code)
They're probably way too large, yeah.
Yeah - unfortunately my world scale is already sorta.. set.. Any ideas?
You can compensate for this by increasing gravity.
either by changing the Physics.gravity value, or by just adding extra force to the dice
ah, extra force to the dice works easily
don't wanna change physics.gravity since i have some other stuff using it
nominally, doubling gravity will make the dice appear to be half as large as they actually are
So if you want the dice to look 10 times smaller, add enough force to get 10x normal gravity
ForceMode.Acceleration i assume?
hm... doesn't seem to be working:
private void OnEnable()
{
_rigidbody.AddForce(Vector3.down * 50, ForceMode.Acceleration);
}
great, thanks - i assumed the forcemode.acceleration would "leave" the force on the rb
no, it just affects how the vector is interpreted
nope. AddForce is a one-time thing
ForceMode.Force and ForceMode.Acceleration are meant to be used continuously
ForceMode.Acceleration and ForceMode.VelocityChange ignore mass
so what's the point of ForceMode.Impulse? or actually, I see from the docs acceleration ignores mass
gotcha
ForceMode.Force and ForceMode.Impulse care about mass
and ForceMode.Impulse and ForceMode.VelocityChange are meant to be called once (like for a jump)
oh this looks nice now
need a bit more Y velocity π but they fall and settle pretty rapidly
You'll now need to kick them significantly harder to make them go upwards
yeah, i'm using vector3.down * 50 so..
also i coulda just used the "invert normals" checkbox on the cylinder mesh instead of having my 3d guy generate one that's backwards π
er
"convex"
or maybe that's different - just for optimizing calculation of colliders? i'm assuming there's some math that optimizes convex meshes versus those that have "interior exteriors"
this is very different
a convex shape has no holes or dents, basically
when you check that box, Unity generates a convex shape that wraps around the mesh
Convex shapes are much easier to reason about. They have a clear "inside" and "outside"
By definition, a convex mesh collider can't be inside-out
I'm trying to calculate which of the six sides of the die are "up" but I'm getting some weird results. Anyone see any obvious errors?
private Vector3 CalculateUpVector()
{
Vector3[] upVectors = new Vector3[] { Vector3.up, Vector3.down, Vector3.left, Vector3.right, Vector3.forward, Vector3.back };
Vector3 closestUp = Vector3.zero;
// Find the smallest angle between transform.up and the list of upVectors
float closestAngle = float.MaxValue;
foreach (Vector3 up in upVectors)
{
float angle = Vector3.Angle(transform.up, up);
if (angle < closestAngle)
{
closestAngle = angle;
closestUp = up;
}
}
return closestUp;
}
this die is being identified as "back" (and should be "right" - 1, 0, 0)
er.. wait.. i need to be calculating each of the transforms vectors against world.up
not calculating each of the world vectors against the transforms "up"
im sooo tired so i'm gonna try to keep this brief.
i have a SceneHandler script which stores (among other things) a list of PassageHandlers. PassageHandler is a script which store (among other things) a PassageName and a reference to a SceneHandler.
i have a PropertyDrawer for PassageHandler to create a custom inspector GUI and it looks like this. You enter a name, a SceneHandler object, and then select one of the passage names from that SceneHandler.
my issue is that I can't change the Passage Name in the inspector panel after setting a SceneHandler. i can delete the text in the box and write my own but as soon as i exit the property field, it reverts back to the old name. if i delete the PassageHandler on the other SceneHandler, i am once again able to edit the name field.
EndChangeCheck returns true, so it realises that i've modified the fields in some way. ApplyModifiedProperties also returns true which i believe means it carried out a change to the serialized object? but...it clearly hasn't updated because the name reverts back to whatever it was before being edited.
am i missing something obvious here?
PassageHandler: https://paste.ofcode.org/PpSCG4NEFnx7SXk4yvBF59
PassageHandler PropertyDrawer: https://paste.ofcode.org/dALz8RQ2suuU3YTqVYK4HA
SceneHandler: https://paste.ofcode.org/rPwejgWS8C8e43v7uHM6QM
Hi, I'm really sorry for asking a question immediately when I'm new here..
But, I wanted to make a quick audio to text project using unity sentis and the provided sentis-whisper-tiny repository assets so that it would work even when offline. I'm currently using Unity 6 and the latest version of sentis (2.1?)
I've looked at a lot of different tutorial videos, sites and other resources but they all seem to utilise an outdated version of the sentis-whisper-tiny repository which is now different for sentis 2.1
I have no idea where to start or how to make it so any resources, advice or help that could help me get started would be greatly appreciated, thank you!
use the model from hugging face thats compatible with sentis 2.1
I'm getting this error when trying to build for Linux
The type or namespace name 'Switch' does not exist in the namespace 'UnityEngine.InputSystem' (are you missing an assembly reference?)
How can I fix this? Why isn't Switch supported for Linux builds?
Hello, is 'SerializedObject target has been destroyed. UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)' error critical? Cant find any info about it and it doesnt look lite it harm yet. I found out its caused by destroying object with SerializedDictionary which i got from asset store
Here is a code and problem gone if i comment 49-54 lines but this will break my damage system
https://hastebin.skyra.pw/udufufoviz.csharp
screenshot the full error?
maybe its a editor UI issue or something
full stack
I saw few peoples adviced to reload editor but it doesnt helped. Also error only pop up when i'm killing enemy
Not sure what do u mean
whats full stack of the error look like
Oh, its same as on screenshot
SerializedObject target has been destroyed.
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
if you select the error you dont see another bottom half bar ?
I only tried to restart editor, how can i reset layout?
top right corner of unity
though doubt it cause this seems IMGUI and not the editor ?
Switched to default one and it doesnt help
this only happens when exactly ?
When i'm killing enemy. I have a bunch of them but they all just inherit script i sent above and dont have any unical methods yet
when you call TakeDamage ? or when destroyed?
On destroy. If i deal not enough damage thru TakeDamage to call destroy then nothing happens
In case someone else will have similar problem, this line placed before Destroy(gameObject) helped
this.hideFlags = HideFlags.HideInInspector;
huh hiding before destroying an object ? weird..
must be some weird cleanup bug in dictionary asset
still points to editor only issue anyway
I've tried to move it to different script and destroy before destroying entity but it still return me error, either as a disabling it with this.enabled = false
unlikely that would fix it, the issue isn't how they are destroying the object, the issue is related to an asset that has editor code that doesn't appear to be properly handling the disposal of the serialized object
That looks like an issue in whichever serializedictionary library they are using
Is it possible to alter the timescale of a single object, or pause any scripts running on it for a certain amount of time without significant refactor?
the time scale is global, but you could always give your components some "timescale multiplier" that you use whenever you need to multiply by deltaTime
Thank you
When I build my game, unity makes a second black screen called Unity Seconday Display. Any idea why or how I can get rid of it? I only have one camera in my scene set to Display 1 and I have a few other cameras that are making render textures, but they dont have a display associated with them
Check the dot product of each direction converted to world space to world up. The one closest to 1 is the one you want.
Hello, i am developing an action rpg like poe/diablo and im not sure if the question is here in the right place. I have a hard time to understand how to create items the "best practices way". A phyiscal item can drop and needs to be shown on the ground and also have a little canvas where the item name shows up and by clicking on it, it gets destroyed and sends an event. After that the item should be in the inventory and i asked myself a question.
Should the item on the ground be the same item in the inventory or should i create an inventory item and destroy the physical item on the ground after looting it? Any tips would help, thank you.
Depends how much data you're working with. Gameobjects have some overhead to them compared to just having a general data object, but if this isn't like a large game where you've an infinite inventory then I'd say it's fine to just keep items in the scene as GameObjects.
For Diablo-type games I'd probably try to keep it all as data as much as possible though.
And to answer the question of if the item that spawns on the ground is the same item you pickup, I'd say don't roll modifiers or any operations unless the player picks it up.
Unless you do want to show a tooltip on hover for ground items, then you probably will have to.
Hey Mao, thank you so much for helping me.
I think there will be many item drops in the game and in generell the game needs to handle alot of items at the same time. Im having a hard time to understand how i can seperate a backend/frontend type of thing in unity, but one day ill figure it out whats a good architecture and when to use scriptable objects etc.
Yes, i will show a tooltip of an item whether its identified/not identified on the ground.
The only time an item needs to become a GameObject is when there's some sort of scene presence (mesh renderer), but otherwise it can just be data. So an Item falling onto the ground should initialize as a GameObject, with the actual weapon data wrapped in it. When it's picked up though, you can remove the wrapper and store that data.
Right now i use a hybrid model lets say. I use scriptable objects and also use class properties that gets the first data of the scriptable objects and after that i manipulate the properties with functions for each individual gameobject most of the time since everything needs to scale with level.
When you use that Item, such as a weapon, the data should include a blueprint to what type of mesh it becomes and then you will initialize a GameObject once again.
Understood, do you have maybe a reference?
Unfortunately, no. Just something I've done before myself ;p
Yeah i belive that. Most videos dont go that much in detail with complex architecture.
I need to think about that. Good advice, makes sense.
Having some type of constructor inside of a the data object is a good idea though so you can quickly construct a GameObject from it.
Or some factory type system where you can feed it that data object and get a GameObject from that
is anyone able to assist with this
the unity examples for property drawer don't seem to do change checks or apply changes so perhaps this is not meant to be done there?
It clearly isn't actually keeping the changed value if its lost once the drawer is destroyed.
originally the change checks and apply line wasn't there and the same thing happened
i dont think they affect the issue either way
Pretty sure you have do:
- serializedObject.Update();
- Draw property drawers etc.
- serializedObject.ApplyModifiedProperties();
Currently you are doing 231
Ah that's a property drawer, yeah you shouldn't have to manually call Update and ApplyModifiedProperties when using those
yeahhh
like i said, im able to change the passage name just fine as long as there's no SceneHandler assigned in the Target Scene Handler field
@sly shoal GUILayout does not work in property drawers
That might be causing the issues
You are supposed to only use the GUI versions, not GUILayout
hm interesting
yeah that does sound ass
I made a base class for my property drawers that has helpers to mitigate that
Like GetNextRect(ref rect)
try using the new visual elements instead i think 2022+ supports editor gui and visual elements together right?
so i just need to replace the rect = GUILayoutUtility... with a manually defined size?
Yes. Everything that has GUILayout has to go/be swapped
EditorGUI.Popup should work
I think i just recently did that in a property drawer
Wait no, I used a GenericMenu
Something like this on button press:cs var menu = new GenericMenu(); menu.AddItem(label, false, () => Debug.Log("TEST")); menu.ShowAsContext();
EditorGUI.Popup prob also works but you need to provide it a rect
Anyway this is #βοΈβeditor-extensions stuff
yeah just tried EditorGUI.Popup and it worked with a rect
o shit sorry, didnt see that channel
ill forward my original message over
how would i get the horizontal and vertical angle to the player?
doing this doesnt seem to give a result i can describe, but it's not what i want
Vector3 toPlayer = player.position + Vector3.up - (transform.position + Vector3.up * eyeHeight);
toPlayer = toPlayer.normalized;
Vector3 horizontalToPlayer = Vector3.ProjectOnPlane(toPlayer, transform.up);
Vector3 verticalToPlayer = Vector3.ProjectOnPlane(toPlayer, transform.right);
Debug.Log($"{horizontalToPlayer}, {verticalToPlayer}");
float horizontalAngle = Vector3.SignedAngle(transform.forward, horizontalToPlayer, transform.up);
float verticalAngle = Vector3.SignedAngle(transform.forward, verticalToPlayer, transform.right);
Debug.Log($"{horizontalAngle}, {verticalAngle}");
animator.SetFloat("LookUp", verticalAngle / 45);
animator.SetFloat("LookRight", horizontalAngle / 45);
...nevermind, i messed up my x and y axes
It's also not clear to me what "horizontal" and "vertical" angles mean
i've done something very similar before
you're recovering a pitch angle and a yaw angle
usually you'd use forward, up, down etc for directions
there's no vertical/horizontal in vector maths
Vector3 flattened = Vector3.ProjectOnPlane(entity.transform.forward, Vector3.up);
yaw = Vector3.SignedAngle(Vector3.forward, flattened, Vector3.up);
Vector3 rotated = Quaternion.AngleAxis(-yaw, Vector3.up) * entity.transform.forward;
pitch = Vector3.SignedAngle(Vector3.forward, rotated, Vector3.right);
here's how I did that
or use units instead... unitX, Y Z etc
what?
ye
i don't understand what you're talking about
you use axes instead of horizontal/vertical for directions
the point here is to turn a direction into a left-right and up-down angle
so that the animator can use those
I suppose you could also convert the direction into local-space and then pass in the X, Y, and Z components of that direction
but then you'd need to make a blend tree that can use all three of those parameters
importantly, the angle values are linear -- going from 10 degrees to 20 degrees means you play the "look right" animation twice as strongly
the response to a direction vector isn't linear
you turn less and less as a vector approaches, say, [1,0,0]
any good resources to learn how to make a node based editor window in Unity
like learning how to use Editor Window , and Unity GUI , pls help
π
pretty much the documentation
its pretty detailed
check pins in #βοΈβeditor-extensions you will find there lots of stuff
I noticed I had an unneeded XR plugin in my project, so I removed it. But now, many scripts from certain packages I'm using, are reporting errors because XRSettings is missing - but they're all within an
#if ENABLE_VR
precompilation block. Why is ENABLE_VR still true after removing the package? How can I disable it?
I don't have anything that is VR specific in my project - simply an unrelated plugin that offers support for it
I havent touched VR but isnt VR mode eneabled when you are in that build profile ?
and that's what's causing issues
which build profile? issue persists on both linux and android build profiles
oh okay mb never touched VR but ig its not a build profile, maybe under project settings somewhere
also nope - there are no xr-related settings in my project settings anywhere
saw this but idk seemed old ig
where is it?
Project Settings under XR settings
I don't have XR settings in my project settings
only XR Plugin management, and it only has a button to install it
ah okay screenshot is old then
what do you have under Scripting Define Symbols
where do I find it?
I'm on unity 6 btw
same place Project Settings
which subsection
oh sorry thought you typed in searchbar, its under Player i believe
strange there was a bug before on this
https://issuetracker.unity3d.com/issues/number-if-enable-vr-is-always-set-to-true-even-if-there-is-no-vr-support-enabled-on-the-project
How to reproduce: 1. Open the "case1175229_ReproProject" Project 2. Observe the console Expected result: Error message does not get ...
wild that it's a unity 2019 bug that's plaguing me in unity 6 - or at least something similar to it
yeah just wondering.. unless something hidden somewhere seems similiar lol
Hi, I'm starting to use Adaptive Probe Volumes in Unity 6, but I have a question about git and their data: do I need to include those .bytes files in git or just ignore them in gitignore?
π Large Code Blocks
π Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
π 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.
I remember seeing a video on how to make a Behaviour Tree with a custom node editor, though they were using UIToolkit instead of OnGUI for building it, if your not opposed to that approach, maybe you may find it helpful: https://www.youtube.com/watch?v=nKpM98I7PeM
This video is an hour long epic into how to create behaviour trees using ui builder, graph view, and scriptable objects. UI Builder accelerates editor tool development by visual drag and drop editing. Scriptable objects are used for serialisation, and graph view is the same node graph backing used by shader graph.
Project files available here!
...
Oh sorry.
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.
I'm trying to keep my player within a 2d level's boundaries. The issues is that I cling too hard to the edges.
so your player is stuck in the air on the wall and doesnt fall down naturally? @cyan mortar
Normal walls, no. Boundaries I set with the variables, yeah
it slides down more slowly
a lot more than if i didn't "push"
maybe try doing all that stuff in FixedUpdate thats generally better for Physics calculation
is this AI code?
yes
ok sorry i will delete
Bumping this
Having the same issue as them but it's very obscure so I cant find any solutions online
My code got improved with fixedupdate, but my player kinda vibrates once i push
is your movment (push) also in FixedUpdate?
yup
No specific advice but unity has an FPS and TPS starter assets controller, could probably solve a lot of issues by bringing one or both into your project and comparing and contrast with your own implementation
unable to load repositories sounds like you aren't properly signed in
or there's some kind of connectivity issue
how do i fix tht then
Or their servers are down
Make sure you're properly signed in for one?
Both of us chose a spring based approach to damper the jankiness oddities in terrain cause (and in my case I chose it for the style) so I don't know if this would really work
Brb
Did you actually set up Devops and version control through the unity cloud website?
do you have repos?
idk what that means π
Then that's your problem certainly
i jst started unity lol
WHy are you trying to add a project from a repository then
what are you trying to do?
someones helping me start a game and he inv me to organisation
i joined it and its not there
You need to pick the right organization here
if it's not there, then you haven't been properly added to the org, or you haven't been given the right permissions
Ah yeah idk either, best of luck
@cyan mortar Maybe set RB collistion to Continious idk normally i would say the issue is that theres Fixed Update somewhere and Update and that gets mixed up but if its both the same idk
theres nothing there
Clearly you have some kind of error happening base don that unable to load repositories thing
go look at the hub logs
Open Log Folder here
it already is continuous
rgb2d.transform.position = new Vector2(rgb2d.transform.position.x, yTop);never set a Rigidbody's position via the Transform- Just use colliders if you want to constrain a Rigidbody's position
- the fact you're setting the velocity to 0 here is almost certainly part of the problem of why you wouldn't be able to move them away
is that the issue
yeah it really seems you're not fully logged in - the access token is expired
I would just restart the hub and/or log out and back in
i logged out and in again but nothing changed
you know what you could just try this: (instead of the whole Fixed Update stuff) @cyan mortar
void Update() {
Vector3 pos = transform.position;
pos.x = Mathf.Clamp(pos.x, x1, x2);
pos.y = Mathf.Clamp(pos.y, -999, yTop);
transform.position = pos;
}
https://status.unity.com/incidents/271735
This is possibly related
[Scheduled] Unity DevOps will conduct a scheduled maintenance on February 6th, 10 PM-11 PM UTC. During this window please expect minor disruptions to Billing Services
i dont think its that cos ive had the same error for months now
yh i jst updated it a few mins ago
If this code is in Update I still stick to the wall
i guess u have to make some colliders then
Why does SerializeReference not show the picker thing with interfaces
You typically need a custom editor or editor code to use SerializeReference properly IIRC
Oh my god
Any good options for free?
It would be something you write
anything is going to be bespoke to your particular game
Is there any way to organize some of the folders that are dropped under Assets? Like TMPro Settings and others?
Or XR
They seem to be dumped in Assets, and you can't just drag them into a sub folder
Fairly sure you can
Yea, but, TMPro would be created under assets, so if you drag it, it won't help
what does that even mean? because you absolutely can put the tmp folder into a subfolder, i do it in every project
But if there is an update, wouldn't it recreate it under Assets?
that is not the TMP package itself, it is the TMP Essentials, and if there is an update, much like when you update any asset, it will find the correct folder because it's most likely based on GUID from the meta files and not the actual path
Ok, thanks
also none of that was code related
I'm struggling with how I should code something. What I want is to have a series of cards, in which you can select a card and drag it to a new position in the series. I have the cards as a list already and could reorder them using a placeholder gameobject. What I can't think of is how to make the card move and what it should look like making a new space. any help?
For dragging, Unity offers IDragHandler interfaces which helps a ton for this stuff. As for 'making space' I assume you mean the gap space between cards, and what I'd do is when you actively drag the card, make the neighboring cards in the list offset opposite of the current dragged card.
Okay, I get idraghandler stuff. What I'm still struggling with still is how to get the card to 'know' when it is between other cards
Yeah I kinda get what you mean. Thinking back, I don't think games like Slay the Spire allow you to do that
I guess how I would handle this is constantly raycast and when I'm over a card that I want to insert it into, I would look for the neighboring card depending on the side I've raycasted on and split them apart.
otherwise some comparison of *all card pivots and figure out where your dragged card is relative to that
Thanks for the input, I'm also tring to think how a raycast would work with idraghandler, since the current card would be under the pointer. How would using a grid work with this?
Just remove detection from the dragged card
The grid sounds like an idea too, assuming your cards dont move too much and just want to compare in those colldier areas
Hihi~
Not 100% it's the right chat to ask this, but:
I have various ScriptableObjects (SO's from here forward) of class, lets say AnimStateFile with AnimationClips member variables, which are exposed with the classic private variable, public get/setter property. But almost everytime I change the script of AnimStateFile all these SO's lose the reference to their AnimationClip.
This also happens with multiple other types of variables/objects, where they lose their reference or reinstantiate from a default constructor.
To avoid losing permanently this information I wanted to repo the SO's so even if they changed, I could atleast have the related information backedup on the repo but... I can't find a singular line on the "yaml-ed version" of the SO's. ("yaml-ed version" = the text version of the SO you get when you drag it into a text editor)
So, the question becomes, how can I backup the SO's information completely? And what could I be doing wrong to avoid losing all the links/references/instanced objects every time I change the script of the SO's?
what kind of script changes are you talking about? That shouldn't happen under normal circumstances
unless you're chjanging the names of the fields
or whether those fields are serialized or not
I don't have an example at hand right now, sorry. But the animClips are not serialized. Heck, can I serialize them?
Example of what kind of change I mean
if they're not serialized then of course you will lose the references
As you said - if you want them to show up in the yaml, they need to be serialized
serialization is what puts them in the YAML
If you see them in the inspector - they are serialized
unless you're using a plugin like Odin or something
Are you assigning data into them with an editor script?
or a custom editor
Perhaps it is not correctly saving the changes, in that case
Particularly if you're also generating the animation clips via script
In that case, they can look totally fine until you quit the editor
Whoopsies? yeah using odin
..and then they die, because they didn't actually get saved persistently
yeah if you're using odin and depending on the fact that Odin can show private variables in the inspector and not actually serializing them, that could be part of the problem
Fen also is making a good point about the clips themselves
Also no, just dragging them to the property in the inspector
The animationClips are "static", they are not being neither created nor modified in runtime
okay, so that rules out a bunch of really hilarious avenues
(ask me how i found out about all of them)
π₯
... how did you found out about all of them?
Also back on track:
[HideInInspector]
protected AnimationClip animationClip;
[ShowInInspector]
[TitleGroup("Anim state")]
public AnimationClip AnimationClip
{
get {return animationClip;}
set {
animationClip = value;
if(animationClip==null){
totalFrames=0;
return;
}
int frames = (int) (animationClip.length * ParametersNS.GlobalParameters.FPS);
this.SetTotalFrames(frames);
}
}
Yeah you haven't actually serialized that field
You need [SerializeField] on the first field to serialize it
that will put it in the yaml
Lemme check right away then
Odin is giving you bad Unity habits π
Oh, it is. IT IS.
animationClip: {fileID: 7400000, guid: 845dfcb4d2df19841837ae223cecff14, type: 2}
There we go
Thanks @leaden ice , @heady iris
how do i limit the change over second of a variabe
for dps caps
Track how much you're changing it and stop changing it when you reach the limit
mock code
float currentHealth;
float oldHealth;
float dpsCap;
void Update()
{
if (oldHealth - currentHealth > 1 / dpsCap)
{
currentHealth = oldHealth - (1 / dpsCap);
}
oldHealth = currentHealth;
}```
it cant be this easy right
no this would only let you limit how much it changes per frame
also... 1 / dpsCap? that's not the limit you want
yeah sorry math is off
dpsCap * Time.deltaTime or something would be the limit i want i think
I wouldn't use Update
there's no reason to use update
you would do this in the function where you change the health
public void DamagePlayer(float damageAmount)
{
float desiredHealth = currentHealth;
if (currentHealth < damageAmount && currentHealth > 1 && Random.Range(0, 4) == 0)
{
desiredHealth = 1;
}
else
{
desiredHealth -= damageAmount;
}
DOTween.To(() => currentHealth, x => currentHealth = x, desiredHealth, 0.1f);
}
this is where i change the health
i have no idea how i'd limit the change per second for this
this question has been plaguing my mind for weeks
You gotta keep track of time, which typically involves the update method and a few time fields on the class keeping state. Then just clamp the incoming damage to the desired maximum.
you could, for example, decrement a variable each update by the allowed rate and use incoming damage to fill it up, adding the delta to the actual damage counter.
but if i do that, then if i wait some time and then take damage, the allowed damage pool will be large enough that the dps cap is non-existent
i could reset the pool if i dont take damage within a certain amount of time but that feels.... wrong
Donβt make it more complicated than it needs to be.
what I described above is how any simple rate limiter works.
You can skip the automatic decrement and do it only on demand but that will typically have various problems in a game as you have noticed.
the problem i have with an automatic decrement is that it'll expand the allowed change when it's not necessary
unsure how to explain what i mean properly
im not sure what im looking for is even possible or even makes sense, to be fair
yeah i dont think the exact thing im looking for makes any sense lmao, thank you for your help
You keep a queue of all the changes in health over the last second.
Each time you update the health you insert that change in the queue and you prune the end of the queue for changes that are older than 1 second.
If you add up all the changes remaining in the queue and it's over your limit, you adjust down to the limit.
something like that
No need for Update
(note the entries in the queue must contain the time and the amount the health changed by. You can use a SortedList for this to make things efficient)
god, thank you, this is exactly what i wanted, idk how i didnt think of it mysef
Is there a way to write this cleaner or more compact?
if (playerMovement.moveSpeedMultiplier == 1f) PlayMotion(FootStepMotion(walkingHeadBob));
else if (playerMovement.moveSpeedMultiplier < 1f) PlayMotion(FootStepMotion(crouchingHeadBob));
else if (playerMovement.moveSpeedMultiplier > 1f) PlayMotion(FootStepMotion(sprintingHeadBob));
var speedMult = playerMovement.moveSpeedMultiplier;
var bob = speedMult == 1 ? walkingHeadBob : (speedMult > 1 ? sprintingHeadBob : crouchingHeadBob);
PlayMotion(FootStepMotion(bob));```
something like this?
you could use a pattern-matching switch statement too
your third else if can just be an else
whats that?
also yes that, I never thought about combining those ternary operator
Thanks!
public void Damage(float value) => CurrentHP = Mathf.Max(CurrentHP - value, 0f) this is similar to my own damage method
@hexed geode
You could do
public void Damage(float value) => health -= (CanHurt ? value : 0f) * deltatime;
We can go deeper! 
public void Damage(float value) => health = Mathf.Max(1f, health -= (CanHurt ? value : 0f) * deltatime);
Okay I'm done π€£
public void Damage(float value) => health = Mathf.Max(1f, health -= (RandomRange(0,4) == 0 ? value : 0f) * deltatime); untested, would be funny if it actually works
how do I get the first digit of a int?
can you explain the purpose of this before an answer is suggested? because that could drastically change the answer
I am trying to set a int as the first digit of a different variable!
i'm just gonna go ahead and drop this here: https://xyproblem.info
to do what with?
As in, 379 to 179? For clarification
I have a health int and I want to get the first digit of it and then set a different var to be equal to the first digit of the health int
are you talking to me?
Ye
like 379 to 3
again, for what purpose
Why? Are you using this to draw the digits one by one or something?
What's the end goal?
sadly yes, I have a entirely custom font with sprites with colors and I am going to just implement it manually
Ok so your actual question is "how do I loop over the digits in my number"?
one option is simply to format it to a string and loop over the characters
string numberString = myNumber.ToString();
foreach (char c in numberString) {
Debug.Log(c);
}```
you can also do something like this:
int myNumber = whatever;
while(myNumber < 0)
{
var character = myNumber % 10;
myNumber /= 10;
}
of course if you want specific characters from the int praetor's would be more versatile. my suggestion gets all of them (technically in reverse order)
What is the best tree data structure for rendering purposes? I have a dungeon and I want to implement a render pass feature that makes it so only the currently active room and adjacent rooms are rendered. I figure I should create a tree data structure that describes rooms and their neighbour. Whats the best way to implement this so its performant?
Sounds like a graph, not a tree (although a tree is a subset of a graph)
but yeah, pretty simple to do with a graph
You literally just need to iterate over the neighbors of the single node you're currently looking at
Technically it's a BFS with a depth limit of 1
alright thank you
correct
The only annoying thing is that you need to maintain the links in both directions
If you're building the dungeon dynamically, then you just make both connections at the same time
If you're manually punching in the connections in the inspector, then it's more of a nuisance
thats true
yo! I used it and it works perfectly! tysm!
#π₯βcinemachine
but also if you want a cinemachine camera to update while it is not live then use the Priority to determine which camera is live rather than disabling them. that will allow it to go into standby which you can control the update frequency of using the standby update property
aha I did not see there was a cinemachine channel, thank you. Should I repost in there or link to this post or what
you would repost it there and delete the original. but you'll get the same answer i just gave, don't disable the cinemachine camera components and instead let them go into standby so that they can update while not live
Do IEnumerator methods re-enter the function at the very beginning or do they re-enter in the loop they left?
For example if I had a loop that loops through indexes of an array, that only stops when the idx value reaches array.length - 1. Will the method re-enter at the beginning of the loop or at the beginning of the function where I initialised the idx value to 0?
They resume right from wherever the yield was they paused on
Okay thank you
Why would you need a render pass for that ?
I can rotate a thing along 2 axes by using an empty gameojbect and rotating 2 things separately
Can I achive the same result without an empty, reasonably? It's not that bad if you want just 2 rotations tho, but I wanted more and ended up in a nested hell
Hello, is there a dedicated channel for text mesh pro?
Depends if it's something to do with the UGUI, or the actual API
its about devanagari fonts
there's this asset
but im worried the plugin might not work, since the developer website is down
I'd probably say #π²βui-ux but maybe even #πβart-asset-workflow
Hey, so I just got this weird error https://pastebin.com/2GjX07m6
Any ideas where to even start looking for the cause?
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.
It refers to WorldGenerator.OreGenerationJob so constructors and fields in that class
ah didn't notice that, thanks
does anyone know why this might be happening?
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.
I thought it might be because of the Z axis but I tried clamping it and it still happens
Can you explain what we're looking at and what's going wrong?
ah my bad, its a ping system and its meant to clamp the ping to the side of the screen but when I turn around the ping appears opposite of where I placed it down.
when i'm not clamping it, if the z < 0 I hide the object
that works fine, but now that I don't want to hide the object I get this weird effect
I am sure that I have encountered this problem and I fixed it by, well
hiding the object by assigning it crazy coordinates
thats an interesting fix but I'm sure there is an easier and better option
I remember I just downloaded someone's assets to make UI markers on objects but on main canvas
and I saw this happening so...
this was my fix before
but this doesn't have it so the marker clamps to the side of the screen
I just hide it when the z is < 0
what do you get if you do world to viewport pos first?
it is done first?
im wondering if the z for viewport pos will be less than 0
viewport doesn't work
it sticks it at the bottom left of the screen
thats why I use WorldToScreenPoint
i presume its due to the projection causing anything "behind" to not behave
quite possibly
what is the reason behind not wanting to hide the object?
is the result different if you use worldToCameraMatrix instead?
I want flexibility, the option to have it hide or the option to have it stick onto the side of your screen, so it could even double as a hit marker thing to show you where you've been hit from.
I can try
In my mind im thinking if you can get a viewport normalised dir to the world pos then it would be usable π€
i solved this pretty thoroughly recently...
let me go find that code
You want to use a combination of two different techniques
and I did almost that too
- On screen, convert to screen-space coordinates and position the dot there
- Off screen, find the direction between yourself and the position, then put a dot on the edge of the screen
with a blend between the two techniques as you get close to the edge
...and I don't think I did it this way, I gonna try dig some code
I had 2 kinds of markers, one you described
and the second one which is simple af getting hidden if z < 0
https://paste.myst.rs/x7wvui1m
Here's my implementation. It's..slightly ugly.
oops, this should really take the camera FOV into account, shouldn't it
I think I might be onto something here
float angle = Mathf.Atan2(screenLocationUI.y, screenLocationUI.x); float slope = Mathf.Tan(angle);
I found this in the code
turns out I was using math
doesn't this simplify to screenLocationUI.y / screenLocationUI.x
well, not quite, since it's ATan2
I am not very bright and I struggle every time I need to do something and then it's done after watching guides I completely forgot what I just did
if it's something complex
It seems to fly down to the bottom but its better than what it was
if (pingsScreenPos.z < 0)
{
// Clamp the screen position to be within the screen bounds with a buffer
float clampedX = Mathf.Clamp(pingsScreenPos.x, pingClampDistance, Screen.width - pingClampDistance);
float clampedY = Mathf.Clamp(pingsScreenPos.y, pingClampDistance, Screen.height - pingClampDistance);
pingsScreenPos.z = Mathf.Clamp(pingsScreenPos.z, 0, pingsScreenPos.z);
rectTransform.position = new Vector3(-clampedX, -clampedY, -pingsScreenPos.z);
}
else
{
// Clamp the screen position to be within the screen bounds with a buffer
float clampedX = Mathf.Clamp(pingsScreenPos.x, pingClampDistance, Screen.width - pingClampDistance);
float clampedY = Mathf.Clamp(pingsScreenPos.y, pingClampDistance, Screen.height - pingClampDistance);
pingsScreenPos.z = Mathf.Clamp(pingsScreenPos.z, 0, pingsScreenPos.z);
rectTransform.position = new Vector3(clampedX, clampedY, pingsScreenPos.z);
}```
lol
Sounds like ADHD
sounds like being stoopid
a powerful website for storing and sharing text and code snippets. completely free and open source.
this is just a snippet of main method
I was doing this code like.. a year ago
and I struggling to grasp
I got a support for different fovs and different resolutions
and for markers which getting hidden out of sceen and markers which are sticking to edges
and it works I swear but I don't know why
these sorts of problems are best solved by identifying very small, very clearly defined sub-problems
I started by just using Camera.main.WorldToScreenPoint
Hey, this is going to sound like SUCH a stupid question, but how can I check for caps lock?
I have tried every method I've seen online.
They all return false ALL the time
I then identified a place where this doesn't work
So I had to decide:
- How to detect when I'm in this situation
- How to correctly calculate a position in this situation
I went through a few different ideas (like just trying to move the calculated screen point back onto the screne)
you can't do anything without doing it this way, right? I do that but... if it involves math, especially geometry which I hate with passion, I watch guides or yeeet someone else's code (which is the same) and then forgetting about it because I did not bother to investigate how this works
especially if it involves something harder than a concept of simple sin or cot
Perhaps you need to build up an intuition on your own.
Unity is actually a pretty good way to do that
you can use Debug.DrawLine and Debug.DrawRay to visualize vectors, and use the methods on Vector3 and Quaternion to manipulate vectors
At some level programming and especially game dev is going to appeal to people who enjoy math and spatial reasoning problems
It's not for everyone
as a backstory I fell out of physics math class because turned out I liked this stuff only while I was easily grasping it
It's a slog and it's not fun to learn that, what can I say
Maybe you just didn't have a good teacher
...here I can't disagree
Did they teach everything from books or did they use visual and hands on demonstrations?
People have different learning styles and maybe they didn't use yours
I was never a "math whiz"
I was pretty good at it, but I never had a great relationship with the subject
I've finally built up a good understanding (especially with linear algebra)
thanks vrchat
trig would been more interesting if it was based around 3D engines that's for sure
I was definitely a math whiz right up until calculus 3 and it stopped being easy so I also stopped enjoying it π
i took a computer vision class in 2015 in college
I have no clue what is calculus 3 but it's my story
that was the only D I've ever received
i did NOT understand linear algebra at the time
was a whiz, stopped enjoying right when faced a wall I having to slog through
turns out to be able to put effort you should either love the subject or hate yourself be really determined about you needing this knowledge
i learned linear algebra properly to make complicated VRChat shaders
I'm trying to use RenderMeshInstanced to render a trail. The max amount of matrices I can send over to the GPU at once is 1023. My trails can require several batches. I need an instanceId in the shader that relates to the total instances count. Problem is instanceId relates to the batch with the API. This means I need to let the shader know what the batch started at so I can add that to the instance ID. Setting the startIndex like below does not work because the process is not sequential and it'll just end up using the startIndex of the last batch for all batches.
Any recommendations?
for (var i = 0; i < batchesCount; i++)
{
var batchStartIndex = i * MaxBatchSize;
var batchSize = Mathf.Min(matrices.Count - batchStartIndex, MaxBatchSize);
material.SetInt(BatchStartIndexProp, batchStartIndex);
Graphics.RenderMeshInstanced(renderParams, mesh, 0, matrices, batchSize, batchStartIndex);
}```
It sounds like you need to include some extra instance data
Yeah.. I'm hoping someone has a workaround rather than sending all that extra crap to the GPU
@kind willow @heady iris @leaden ice
This is an update to where I am, its still got jank but its getting there lol
so apparently... calculus 3 is when you encounter vectors and basic vector math right?
and sin/cos functions and stuff?
funny circle graphs?
seeing calculus 3 is very confusing for me because I am from another educational system where it says nothing
I guess I was talking about something way before that
I think I fell out at mere pre calculus
at some point at life I would have to investigate the real math but I have no idea in which form it can be done other than going to university
sin/cos/etc. is all triginometry, which generally comes before calculus
I want to self-relearn all of the stuff I picked up early in college and then didn't wind up using much
I'm not aware of a way to pass per-instanced-draw data
those big sin cos tan ^ smth equations is where I lost it
I wonder if you could use RenderMeshIndirect
I can't. We ship for mass market and it requires compute shaders support
This requires compute--
yeah
and thus we get into the realm of Funny Ideas
I wonder if you can stuff the identifier into the object-to-world matrix
this sounds really evil
yeah, maybe. Would require the CPU to loop over all matrices but its definitely the lesser of the 2 evils
why is it often about choosing the least wrong solution 
realtime graphics rendering is fun
I would lean towards just including an index in the instance data
especially if you already have one or two other floats in there
(doesn't it usually wind up being 16-byte-aligned anyway?)
i'm a bit of a novice in this area
don't ask me, so am I
I might be thinking of compute buffers here
I dunno how I would profile the impact of this
I think I can just bake it into the last value of the matrix
especially since it probably only matters if you're constrained by bandwidth
last column is xyz and empty I think
yeah, the last column's first three components are the translation
The fourth one is 1 in an identity matrix (duh). I forget if it varies in other situations
something something, homogeneous coordinates
yeah, its prob used so that you can just ship the last column when converting to homogenous coordinates
I was just deconstructing a matrix for this purpose yesterday, haha
but I can overwrite that in the frag shader
I was implementing inverse-square light attenuation and only had the world-to-light matrix
i realized I could just use the inverse of its X-axis scale to turn a light-space distance into a world-space distance
bumps
Quaternion.AngleAxis!
you can compute multiple rotations around specific axes, then combine them
it takes an angle (in degrees) and an axis
q1 * q2 applies q1, then q2
q1 * v1 rotates the vector with the quaternion
I did exactly that and I didn't get what I want, somehow
I've definitely just used empties more than a few times before
wait...
yeah I think I got why I was getting not what I was expecting
or not but I realzied how to do what I need
there's also Quaternion.Euler if you're combining rotations around the cardinal axes (and you want to apply them in the ZXY order, in particular)
Quaternion.Euler(pitch, yaw, 0);
notably, this produces the correct rotation for a first person view
it first tilts the camera up and down, then spins it around the Y axis
Quaternion newRot2 = Quaternion.Euler(-10, 0, 0); Quaternion newRot = Quaternion.AngleAxis(Time.unscaledTime * spinSpeed, Vector3.up);
that's what I was doing to achieve a slightly tilted thing spinning
I was multiplying them and setting as rotation
hang on a second. my first person controller does this.
Quaternion turnRot = Quaternion.AngleAxis(yaw, Vector3.up);
Quaternion lookRot = turnRot * Quaternion.AngleAxis(pitch, Vector3.right);
that seems backwards...
anyway I realized that I just needed to remove newRot2 and use tilted vector instead of up
for my case
but generally I still don't get how to combine 2 rotations
in a way it looks like having an empty and 2 independent spins
hm, this makes a bit more sense now
so this also works correctly
Quaternion turnRot = Quaternion.AngleAxis(yaw, Vector3.up);
Quaternion lookRot = Quaternion.AngleAxis(pitch, turnRot * Vector3.right) * turnRot;
That more closely matches how I imagine this working
using a fixed Vector3.right means that we're rotating around the wrong axis
so the camera tilts to the left and right when we're looking along the +X axis
ah!
Rotating by the product lhs * rhs is the same as applying the two rotations in sequence: lhs first and then rhs, relative to the reference frame resulting from lhs rotation
The last bit is crucial here
relative to the reference frame resulting from lhs rotation
No that's geometry
Calc 3 is like manifolds and stuff
after applying lookRot, we have a new reference frame
so a rotation around Vector3.right is always correct
wha-what are lhs and rhs
quaternion multiplication is non-commutative
so there's some ordering to how you want to multiply everything out
I didn't realize why it was non-commutative until reading that
that makes a lot more sense now
I figured this out emperically
Unity does Eulers by ZXY rotations too btw
Although, I'm now unsure how I'd reliably rotate an object around a specific world axis
I guess you'd put it on the left hand side
Basically, stick to one quaternion rotation and don't diverge from it
What is a sensible way to go about upgradable properties, like this attack example
int attackLvl; // attack value upgrade
float baseAttack; // base value for attack
float powAttack; // Pow is raised by this
float attackAmount => baseAttack * Mathf.Pow(1 + powAttack, attackLvl - 1);
// the final value used to deal damage
```I'll need the 4 properties to find the final amount, but if I went with that approach, I'm going to end up with a giant wall of properties thats only ever going to increase in size as I add new properties
What type of data structure should I use if I'm pairing off units to fight one another in a card game? Multiple defenders can block one attacker, so dictionary is out.
Chunk it into method operations probably
Unless you're crazy like me who has tried a full parsing system of equations
a get accessor can have an entire block of statements
it doesn't have to be expression-bodied
I did not totally get the question
however just doing weird scriptableobjects were always a solution for making data structures for me
public float attackAmount
{
get
{
int attackLvl;
float baseAttack;
float powAttack;
return baseAttack * Mathf.Pow(1 + powAttack, attackLvl - 1);
}
}```like this?
like each unit is an SO and each unit have a list of units it can block idk
well, you wouldn't stuff all of those fields into the property, presumably
yeah I think I just did not get the issue right
yeah, I'll be accessing them properly
If the calculations start getting too expensive, you can lazily recalculate the value only when needed
you'd need to set a "dirty" flag when changing any of the inputs
Yeah, I like to cache my stuff out when changing equipment, but when it comes to your attack vs enemy defense, that's something you need to calculate right then
I wonder how bad am I never bothering to cash anything unless it's being done every frame
probably doesn't matter too much unless you're making some diablo-type game where there are hundreds of modifiers
also with the actual way the value grows as it upgrades, that expression works, though its pretty difficult to judge how it actually changes over time. The best thing I've come up with is to put the same thing into a spreadsheet
I would just slap an animationcurve ngl
not a bad idea, plus that enforces actual limits to be set for min/max
as in if there's a max of 20 levels for damage, that lets the curve time be evaluated correctly
animation curve is bff
What's the general advice on creating health bars in large(ish) quantities in world space? Let's say 100. Do people just do world space canvas? Some sprite renderers? Maybe a custom shader and instancing for optimization?
I just place them on main canvas
my enemies have a world space canvas that contains a slider
this feels like the most straightforward but worst performance wise solution
maybe, but until performance becomes a problem its not really an issue
Do you happen to have just a handful of enemies at a time?
when I was doing world UI markers I bumped on all solutions you described
https://www.youtube.com/watch?v=cUQVLgohAjY
has good tips on optimizing this use case
Learn how to make Health Bars that stay above the heads of units in World Space!
A common need in games is to show Health Bars over some enemy or unit. In this tutorial we'll take a look at one way to achieve that in a way that enables us to retain the benefits of sliced and filled Sprites.
I also discuss some of the "gotchas" that you may enc...
yeah
That's more than I assumed, good to know I can be a bit lazy.
There's per-canvas overhead. Then it's up to what your game is like and requires. If you can dump them all in 1 canvas, go for it. If you can use mesh renderers, go for it. If you can use the low level graphics API to render them all at once, go for it.
tank driving on a Ukrainian field moment (fpv drones)
ive been too lazy to do anything good like that π
Recently I needed to do something pretty common in many top-down games: render a whole bunch of health bars for enemies on the screen. Something like this:
Obviously, I want to do this as efficiently as possible, preferably all in a single draw call. As I always do before I start something, I did a quick search online of what other people are do...
Probably the best solution assuming you've hundreds
otherwise I think vertex coloring is fine too with srp batcher
I'd just give the enemy a quad and change the width as it loses health
and if the enemies will even have health bars in the actual final game, I couldnt say
I have to say that I never did profiling
does a vampire survivors like really need enemy health bars?
but having alot of canvases is clearly worse than calculation positions and sizes for one canvas, right?
oh almost definitely
This is what I'm just stealing at this point, which essentially just is a single Monobehavior and a shader π€·
canvas is just bad cause each one is a single drawcall
like this solution was the best for built-in and probably still the best for URP lol
I can't say I played many games
I think world space canvas is only good for like
Doom 3 alike monitors
I don't remember something like that in other games
where it's a UI interface of a computer you can interact with like it was a computer
it got it own UI buttons and mouse cursor
yeah I haven't play much games, it should be in many games probably but I don't recall
{
try
{
var relationship = await FriendsService.Instance.AddFriendAsync(playerId);
Debug.Log($"Friend request sent to {playerId}.");
return relationship.Type == RelationshipType.FriendRequest;
}
catch (FriendsServiceException e)
{
Debug.Log($"Failed to Request {playerId} - {e.Message} - {e.ErrorCode}");
return false;
}
}``` it returns true even if playerId is not correct. it also lists the not existing friend at FriendsService.Instance.OutgoingFriendRequests
any idea how to check, documentation doenst handle this
If I delete an account that has friends, these links are not removed either.
okay, so
in the end nothing worked for me, sadly
I am getting rotations like it's a top toy in the end of spinning
While I am trying to figure out how to just spin a tilted object along it's local upward axis
any ideas, anyone?
``
Quaternion lookRot = Quaternion.AngleAxis(Time.unscaledTime * spinSpeed, new Vector3(0.1f, 1, 0));
float pitch = 10;
Quaternion turnRot = Quaternion.AngleAxis(Time.unscaledTime * spinSpeed, Vector3.up);
Quaternion lookRot = Quaternion.AngleAxis(pitch, turnRot * Vector3.right) * turnRot;
``
same things
slightly different tiltness I guess but it's not what I care about
turning like a
you know those sticks on top of campfire
permanently tilted along one axis, spinning along another
and I don't want to make an empty
i mean you can rotate the Global rotation of the object Along X and Z and use the local rotation of Y to spin it right. maybe that works
I am not getting it
multiply its current rotation with Quaternion.AngleAxis(someAngle, Vector3.up)
so, transform.rotation *= ...
that's eh
yeah I figured it would be about doing transform.rotate or modifying transform
use some small value (based on Time.deltaTime) if you're summing up these rotations over time
but I want to rotate several objects in sync and not all of them are spawned right away
You can also use Transform.Rotate, yes
in that case, you need to remember the original rotation
so I think I want to be overriding rotation
At that point, using an empty makes a lot of sense.
You already need to remember an original rotation that you apply a modification to
why would I need to rememebr original rotation
they all spawn having zero
I mean identity or whatever
the task looks so simple
I guess I can rotate an abstract Quaternion
not actual transform
It's not too bad doing it this way
public float MagicResult
{
get
{
// the base value to scale the result by
float baseValue = MagicBase;
// the current level of the property
int currentLevel = MagicLevel;
// the min and max level that this property can be between
Vector2Int levelRange = MagicLevelRange;
// the curve that is used to evaluate, allows for different types of growth to be achieved
AnimationCurve curve = LinearCurve;
// the evaluation time for the curve as a [unit]
float eTime = NormaliseValue(currentLevel, levelRange); // Mathf.InverseLerp(minLvl, maxLvl, curLvl)
Debug.Log($"eval: {eTime.ToString("F3")}");
// the curve value that has been evaluated
float cValue = curve.Evaluate(eTime);
Debug.Log($"cValue: {cValue.ToString("F3")}");
return cValue * baseValue;
}
}```
I'll shrink its size down once I actually start using it, most of it is redundant
I always shove lerps onto animationcurves every time I can
public float MagicResult(AnimationCurve curve) => curve.Evaluate(NormaliseValue(MagicLevel, MagicLevelRange)) * MagicBase; actually, its really only a single lines worth of code π
InverseLerp is honestly incredible for how versatile it is
I use it to check how fast the vehicle moves in relation to its top speed
Mathf.InverseLerp(0f, VehicleObject.TopSpeed, Mathf.Abs(CurrentSpeed))
That way once this has a value of 1, I dont have to apply anymore force to it
are autoproperties like this
[field: SerializeField]
public int Age { get; set; }
the best approach for fields that could need custom get; set implementation?
If they need custom get; set; implementation you can't use an autoproperty
Vector3 targetVelocity = desiredDirection.normalized * MaxSpeed;
Vector3 velocityChange = targetVelocity - body.velocity;
Vector3 acceleration = velocityChange / Time.fixedDeltaTime;
acceleration = Vector3.ClampMagnitude(acceleration, MaxAcceleration);
body.AddForce(acceleration, ForceMode.Acceleration);
rate movement with limits I use
damn how do I format it to be in one beautiful black square?
```cs
code
```
this aint called autoproperty? autoproperty is only {get;set;}?
private int _age;
[field: SerializeField]
public int Age
{
get => _age;
set
{
if (value < 0)
{
Debug.LogWarning("Age cannot be negative.");
return;
}
_age = value;
OnAgeChanged?.Invoke(value); // Trigger an event if needed
}
}
as far as I know autoproperty is only {get;set;}
why do you have sarializeField on top of a property?
you should have it on top of _age I think
since Age is basically a method
not storing stuff on itself
I see
Is just that my code ""headers"" is so messy I wanted a way to make it simpler
is Quaternion.Euler (1,1,1) the same thing as transform.rotation of a gameobjects having 1,1,1 angles?
i.e.
[SerializeField] private Info info;
public Info Info
{
get => info;
set => info= value;
}
[SerializeField, ReadOnly] private Vector2 index;
public Vector2 Index
{
get => index;
set => index= value;
}
personally I don't get why would you want alot of properties
I only use them when I need some real logic behind it
they create so much clutter
Can you suggest videos or resources on solving Unity errors when migrating a project to another Unity version?
migrating to one of the LTS version throws errors which takes a lot of time sometimes. tell me the best practices and what should i do and dont's?
But how would you offers a way to Set or get some fields while keeping it [SerializeField] private?
I found myself having like 10 fields
and then something like
6 GetFieldMethod()
4 SetFieldMethod()
that creates clutter too
you can't I guess
I just don't mind having some things public
even if it's alot of things
I'm so afraid of leaving stuff public lmao
IDE can show you all references in two clicks
true
I would only get it if you are working in a studio having more than like 3 programmers
thats what my approach is
its a very basic force calculation
wait it just applies force till it reach the top speed
let me double check if it ends up making the speed oscilate once its at the top, becuase it might go 1, 0.9999, 1, 0.9999, 1, 0.9999 each frame
anyway that would always overshoot max speed and I can't stand it
it's clearly acceptable in a context of a game tho
ah yes
oh also
I remember
I used code I stated because I had crazy acceleration and low max speed
aka your fps character
it never overshoots
but I wonder how suboptimal it is
I'll put a TODO to try and fix it later on, I cant see it being much of a problem
on a vehicle it's not, on a character, it's at very least a jittering camera
thing is
@mossy scaffold Don't crosspost
nice mod avatar
I saw most implementations limiting velocity or applying backward force
but I don't get why if you can calculate exact force to not overshoot the limit
I guess if you won't go for overshooting that would make friction kinda more powerful?
since this calculation not accounting for drag or friction
anyway if someone share code how to achive this rotation
https://openusd.org/images/tut_xforms_spin_tilted.gif
by having a quaternion I can assign to different gameObjects I would very appreciate that
I am done breaking my brain over this seemingly simple problem for today
...wait the gif is from the site which describe how to code such rotation
AND it also shows how to do it wrong showcasing the wrong result (I got exactly that)
too bad it's not for Unity
just looks like simple rotation around an axis (the axis that goes through the center of the top)?
that's it!
to my shame I ve wasted like an hour on that and it's not working
I did try that and it didn't work
Does anyone have an idea?
I want to apply some fancy shader effects with a render pass to the rooms of the dungeon depending on how far away (in terms of the graph) they are from the room the player is currently in
if its true even though it doesnt exist you can make a check if the Player actually exists in de ServiceClass
What's best practice for using a physics based character while also using root motion?
It seems just using root motion allows the character to pass through other colliders. Using OnAnimationMove combined with RigidBody.MovePosition also allows the character to move through other colliders.
Is best practice to apply forces and/or set velocities?
not sure what you're specifically using it for but i would avoid root motion if you can and just use the rb.
I never tried root motion but not sure how it is even supposed to be compatible with any physics
Someone here has used git-filter-repo in here?
there any way to limit an integer field value between min/max without it showing a slider? i see a min but not a max
The issue is that there are some things that you want to use root motion. Imagine a shambling zombie that doesn't walk at a constant speed. Ideally, your animation is driving the motion on that... but it seems using root motion allows it to move through walls. Using OnAnimatorMove and applying the position deltas from the animation via rb.MovePosition also allows it to move through other colliders it seems.
first thing to check is what the natural orientation of your 3d model is.
but it seems like your rotation axis doesn't align with that.
I have no idea how to query this, i.e. with which using. do you know this by heart?
Have a strange issue with GameCenter on my iOS device. I'm sending achievement info to it. It seems to update just fine most of the time, but when an achievement takes a certain number of something before it unlocks (example, 10,000 damage) it seems to show itself as locked in the game center even if I seem to be sending it that we're at 2% (Example, 211/10,000 dmg done)
Has anyone worked with GameCenter before and had a similar issue?
Will move the question there
i dont know, depends on how your servic class works
how should I approach face culling? I want to generate voxel terrain, and faces that aren't visible should not be rendered. Should I change things in object's mesh filter?
Hello, I have a question about grids. I'm making a game with the same concept of a grid like Prison Architect or Rimworld. Currently while I instantiate each grid cell, I populate an array of GameObjects, and also of ObjectTypes using enums for "empty" cells where a player can place objects on top of. I also give each cell I instantiate a script that keeps its coordinates for when the player tries to click it, here using Raycast and a collider. Now this works great and I have also made placing and removing of objects (for example a bed) on top of this grid, using the enums.
My issue here is when I think about saving objects for when the player wants to load their game. Is my way of doing grid poor for this? I'm not exactly sure what would be the best way to handle saving. Would it be giving the placeable objects some kind of script with ID for type and the coordinates for prefab instantiating which I save in one big JSON file, then use that and populate my ObjectType on load? If I use this idea, I'm a bit unsure how to handle the grabbing of the scripts since it'll be many. I guess I can, "populate an array it goes through" when you save. Or is there a better way to do all of this?
save as much of the data in value types then just recreate those. IF tiles that dont contain data just track their type as you said, maybe a index that goes into an enum etc.
every cell you have has a Monobehaviour on it?
@kind willow @heady iris @leaden ice I got it fully working
It doesn't inherit from Monobehaviour. But another comment made me realise in general that I shouldn't do cells with game objects and scripts and instead do an array in the main script for the data and use world to mouse position for interacting with them
my grid stores a Tile class at a vector, and clicking returns a position which is linked in the grid dictionary
maybe this helps you in some capacity
That does help me with an idea of how to transfer away from how I'm doing tiles, thank you for that π©·
if you have any questions, just ask
Bit unsure about the first part you said. I was thinking of storing the data of the gameobjects coordinates and ID through value types but my question was how to do that. Would it be having scripts on the placeable objects which I have a reference to or would it be somehow storing it in a singular script?
Grid tiles themselves I have a better understanding of now.
are you doing it 2d or 3d?
I'm still unsure how to store the data for game objects you place on the grid. I would only need some kind of ID for the prefab and the coordinates but I'm a little lost what's the best way for this
2D with pixel art
you're not storing the actual gameobject though, just the data, the rest is just you using prefab to recreate that object from stored data
since my game is like a roguelike i cant freely move around,
but in your case, you can have empty gameobjects with colliders (with the sprites) saved in the EntityData class (their Transform)
while my logic revolves around grids instead of free-moving locations, for freemoving entities you only have to update their position in the list.
all my "Gameobjects" are Objects (Classes) stored in a mapping dictionary
and to access/update i only have to input the position of where i clicked / other logic
but if youre working with free-moving enties you can instatiate a gameobject with a sprite and store the transform in the entityData
natural orientation totally normal not tilted prop
Then it's your code