#archived-code-general
1 messages · Page 340 of 1
Hey everyone, in my side scrolling 2d platformer it looks like my player character is jerking when moving, but I have the input in Update and the movement method in FixedUpdate, isn't that right? Is there any other cause of the jerking movement?
maybe your camera
show code and other relevant info
it's only my player though, the other objects aren't jerky
if you're moving in FixedUpdate, that means you move 50 times per second
this may not align with your framerate
Are you using a rigidbody2d?
yes
try turning on interpolation
Does your camera follow your player?
void Update()
{
hMove = playerControl.Movement.Move.ReadValue<float>();
}
void FixedUpdate()
{
hsp = hMove * speed * Time.fixedUnscaledDeltaTime;
transform.position = new Vector3(transform.position.x + hsp, transform.position.y);
}
yes camera follows player
There is no rigidbody here at all
it's probably adding to x is the problem
If you're using a rigidbody on your character, you need to set the rigidbody's position
no, you should be setting the rigidbody's position
you are not setting the rigidbody's position anywhere in this code
you are setting your transform's position
Are you using cinemachine?
yes
fix this first before you do anything else
I've never moved my rigidbody before
add a Rigidbody2D field, assign a reference to the component in the inspector, and then set its position instead of your transform's position
I've always added to velocity or added to transform x
time to learn
so that's the right way to do this?
I guess you wouldn't be saying it if it wasn't
you want your physics object to be accurate with physics ofc its the right way
When you set the transform's position directly, you aren't letting the physics system know about the movement
it just finds out that it's in a new position (for no apparent reason) in the physics update
this grabbing the same transform
also, you can't add to a single part of the position like that
rb.position += speed * Vector2.right; would be more appropriate
do I need to do * time.deltaTime
Correct, actually!
I forgot
In FixedUpdate, Time.deltaTime will be set to Time.fixedDeltaTime, so you don't have to worry about that distinction
only with .position usually though, not if you were to use AddForce for example
The rule is that if you're changing something over time, you use deltaTime
You are gradually changing your position over time, so you use deltaTime
with AddForce, that's not the case: you're just saying "push on the rigidbody this hard"
i just changed it to my rb and it's still doing the jerking
Show your new code.
void Update()
{
hMove = playerControl.Movement.Move.ReadValue<float>();
}
void FixedUpdate()
{
hsp = hMove * speed * Time.fixedUnscaledDeltaTime;
rb2d.position = new Vector3(rb2d.position.x + hsp, rb2d.position.y);
}
rb2d is the rigidbody
Ah, you actually need rb2d.MovePosition
I forgot about that -- setting rb2d.position ignores interpolation
at least, that's the case for a Rigidbody. The manual isn't clear about that for Rigidbody2D
rb2d.MovePosition(new Vector3(rb2d.position.x + hsp, rb2d.position.y)); ?
this doesn't seem right either
doing this made it way worse, vertically and horizontally, it was just jerky horizontally, now it's extremely jerky in both dimensions
looks like stop motion now
hm, that's a bit unexpected
it may be the camera... the camera doesn't seem jerky
and everything else is moving smooth
nevermind
You could make the camera stay still and see how things look
when my camera is at one end of the level and fixed the player is still jerky
I suppose that MovePosition is resetting your velocity to zero
it's only jerky horizontally
Perhaps you can just set the velocity instead?
That'll avoid directly setting the rigidbody's position entirely
var velocity = rb2d.velocity;
velocity.x = hMove * speed;
rb2d.velocity = velocity;
that was it! Thank you so much!
in the Update method, is it more expensive to have a local variable or create a variable in a method?
meaning is it more consuming to create a variable in the class or in the method, I'm assuming in the method
*Heavily recommend using a character controller for movement if you arent doing anything physics based
A local variable is likely going to be faster than a class member, but the difference is going to be irrelevant. These are the micro optimizations that you should never do, and just focus on writing good code.
the reason I'm asking is because I have a 2d 16 bit game and it makes my fan blow hard every time I play it
it's probably something else
I'm not super great at using the Profiler, I want to lower those spikes
With any performance related questions, the first thing you do is to profile it and understand what's eating your performance budget. Randomly guessing what the problem is is not the right way to go.
the biggest chunk in profiler says EditorLoop
as you can guess, that is the editor. You can profile a build or just try to focus more on the player loop side of things
a build would show you how your performance actually is, since the editor has a ton going on around
I guess that makes sense, maybe it's the editor that's making my fan blow hard, but my computer is pretty good, the editor shouldn't be doing it either
you can expand the profiler data too and see what specifically is causing issues. Maybe open up task manager just to see if its even unity causing it in the first place
Well, how much fps do you have?
Don't cross post and #1180170818983051344
How do I reset something in visual studio 2022 where I stop getting these false errors in the editor:
What does the error say?
mind you, Unity compiles and plays.
I bet your game is just running at a billion FPS
If you don't have a framerate limit, your game will eat either 100% of your CPU or 100% of your GPU (whichever limit it reaches first)
https://docs.unity3d.com/ScriptReference/Application-targetFrameRate.html
You can use this to set a frame limit
Sorry, busy with my daughter.
That does not look like a false error. Been a while since I used unity ecs though. So you should ask in #1062393052863414313
mesh.uv2 = new Vector3[...]
and why do you expect these changes to persist? are you saving the changes to the asset?
Yup
I edit the mesh asset, but unfortunately the changes get cleared (?) when entering play mode
Show your code.
My understanding is that when entering play mode, all changes to the mesh are removed
Can't before tomorrow =X
Something like var smoothedUVs = some Vector3[] then mesh.setUVs(1, smoothedUVs) then save asset obviously
I want to see how you're doing the last bit.
notably, you aren't going to be able to rewrite a mesh that comes from an importer
It sounds like you want to create an AssetPostprocessor, actually
you can use that class to modify an asset after it gets imported
I'm trying to code a saving system for my Unity3d project. I searched online and I see recommendations for writing JSON files based on the game state with optional encryption/decryption for anti-tampering. Does this approach sound reasonable?
Addendum: Will scriptable objects auto-save since they are persistent, or are they only persistent within a session?
former is better
encryption/decryption aint worth it though
Not really a big value-add?
sciptable objects for a save is no good, values get reset in new run
not really
if the game is offline who cares what goes on
if the game is online then it has no reason to be storing encryption/decryption code in the client
Fair point. I was assuming standard practice without really questioning it
Last thing: Add-ons for saving. Are they generally worth it, or is hand-made saving reasonably efficient and feasible?
depends how complex you're going for and how much you're willing to code yourself, only you can know if they're valuable to your project
start simple first if you havent already played around with saving system first
adds complexities of first learning their system while learning saving in general
My main saving needs are stats, entity position, quest/event data, and related data
Okay, makes sense
yeah You can easily store that in a basic json/bin file
Are there any special gotchas when saving data in json format, like non-persistence or a special directory or mechanism to save json data? I'm looking at https://docs.unity3d.com/2020.1/Documentation/Manual/JSONSerialization.html right now
yes the Unity is limited to what it can serialize
properties are one of them that it cant
As long as the property has a referenced field, should be fine, right?
I usually use newtonsoft json.net
can serialize pretty much unity cant and more.
only issue it has is Vector3s
You can serialize properties too by serializing the backing field.
[SerializeField] private float example;
public float Example => example;
How do you serialize a backing field?
Or is example the backing field here?
[field: SerializeField]
Ah, okay
yeah for Dictionaries you also do it with structs etc
Ahh that might be annoying
I do not mess with structs too often and I have a few dictionaries in use. I imagine I have to convert and unconvert them to keep the mserialized?
json.net makes it easy?
Will definitely look into that
I've just finished migrating to STJ a few hours ago.
I was using JsonUtility, and honestly it's pretty alright. I only migrated because I do not fully control all of the JSON I'm consuming, which is a use case I assume most projects won't run into.
in unity i think 97% of the time JsonUtility is perfectly fine
but yeah like you said, certain APIs i need more control over the de/serializing part
Where are JSONs stored? I don't see any docs about a command to store the json in any local directory
For sure, and JsonUtility has very good performance, especially comparing to NSJ.
json is just a way to format text
you have to create a file to store it anywhere
Application.persistentDataPath usually
Last time I looked it seemed like a coin toss.
Oh really.
I haven't profiled it myself, but from an article that did the profiling, the number differences are pretty big.
Nvm, it's a bit slower at worst and much faster at best.
https://www.jacksondunstan.com/articles/3303
https://www.jacksondunstan.com/articles/3714
(At least in 2015)
Ah yeah I think those are the articles I remembered.
The allocation is especially nice.
whenever i rotate objects flicker for some reason, ive tried messing with clipping planes and that didnt help at all, my only guess is its cause its in update and not fixed update but that doesnt make much sense to me
https://hatebin.com/sfwvjjhqtk
Objects flickering is unlikely related to your movement code
Changes to transform prevent rigidbody interpolation. Make sure interpolation is on.
Ah yeah if by "flickering" you actually mean stuttering then yes
you should not be rotating your player's transform but rather its Rigidbody
transform.Rotate(0f, movement.x * sensitivity, 0f);```
Should become
```cs
playerBody.rotation *= Quaternion.Euler(0f, movement.x * sensitivity, 0f);``` @fiery spruce
yep that did it, thanks a ton
weird how that behaves different then playerBody.transform.Rotate(0f, movement.x * sensitivity, 0f);
because as mentioned modifying the Transform breaks interpolation
Yeah, moving the transform is never recommended when using a rigidbody. Even teleporting can be done via the rigidbody instead
interesting, nice to know
Hi, can someone please explain to me why does Unity keep asking me to update UnityWebRequests in 2022.3.26f1 with the Script Updating Consent popup? Did they change something because the documents are still using the same old flow.
where does it say that?
Here you go. I dont understand why the most basic one is obsolete.
Edit: Content Type was always set auto by default in unity no?
Does Unity only limit one drawn raycast at a time?
wdym by basic one, there is one you can just use the form data.
Are you talking about the string data only one?
no
For some reason this doesn't seem to be working then
Direction = new Vector3(0, -1, 0);
Ray ray = new Ray(this.transform.position, Direction);
Debug.DrawRay(ray.origin, Direction * Distance, Color.red);
are you sure the script is running
Yup the string data only one which is just a json.
I'm certain because the rest of the code is functional
oh so now they want you to specify content type for that.. gotcha, i usually use the form one thats why.
show the rest of the !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.
Probably because it might be confusing. When you see a code that posts a string, your immediate reaction isn't "this string is being interpreted and posted as multipart form data."
Either way, best to migrate away from obsolete API even if it still technically works.
So I'm trying to make a custom Timeline track that uses Spline Containers.
My clips have a field that allows me to define which spline container it is using.
The problem is that once the clip is created, changing the value of the field does nothing.
The code is just this.
public class SplineBehaviour : PlayableBehaviour
{
public SplineContainer splineContainer;
public AnimationCurve curve;
}
[Serializable]
public class SplineClip : PlayableAsset, ITimelineClipAsset
{
public ExposedReference<SplineContainer> splineContainer;
public AnimationCurve curve = new AnimationCurve(new Keyframe(0, 0), new Keyframe(1, 1));
public ClipCaps clipCaps
{
get { return ClipCaps.Blending; }
}
public override Playable CreatePlayable(PlayableGraph graph, GameObject owner)
{
var playable = ScriptPlayable<SplineBehaviour>.Create(graph);
var behaviour = playable.GetBehaviour();
behaviour.splineContainer = splineContainer.Resolve(graph.GetResolver());
behaviour.curve = curve;
return playable;
}
}
I understand that what's likely happening is the value of splineContainer is getting passed to the behaviour only on playable creation.
Aka a change any point after is meaningless.
Is there anyway to have it recreate the playable when I change that field?
Or will I need to wrap the SplineContainer in something?
@rough scaffold It's referring to these.
oh i see i see
thank u so much
@dawn nebula and vertical would be w and s essentially>?
open the vertical axis and see 😛
looks like an internal error, does the last error give any more details
Hello! Let me check
Here
No details whatsoever
hello
I think I got it working ! Could you check if that's how I'm supposed to use the AssetPostprocessor class ?
What problem do you want to solve ?
Yes, this looks right to me.
Annoyingly, you can't just add extra options to the original asset importer. So you can't add a checkbox that lets you turn the baking on and off.
I don't understand why do I get this error? even though I couldn't find any null within the unity nor the script
UnityEditor.Graphs.Edge.WakeUp () (at <0e6f69b30d82405f98d87804eacb548a>:0)
UnityEditor.Graphs.Graph.DoWakeUpEdges (System.Collections.Generic.List`1[T] inEdges, System.Collections.Generic.List`1[T] ok, System.Collections.Generic.List`1[T] error, System.Boolean inEdgesUsedToBeValid) (at <0e6f69b30d82405f98d87804eacb548a>:0)
UnityEditor.Graphs.Graph.WakeUpEdges (System.Boolean clearSlotEdges) (at <0e6f69b30d82405f98d87804eacb548a>:0)
UnityEditor.Graphs.Graph.WakeUp (System.Boolean force) (at <0e6f69b30d82405f98d87804eacb548a>:0)
UnityEditor.Graphs.Graph.WakeUp () (at <0e6f69b30d82405f98d87804eacb548a>:0)
UnityEditor.Graphs.Graph.OnEnable () (at <0e6f69b30d82405f98d87804eacb548a>:0)```
And the game doesn't receive any error at all. And if I exit and rerun the editor it's gone
Restart the editor.
This is a problem with the code that draws a graph window (like the Shader Graph).
There is nothing to fix in Arc's code.
graph window?
like the Shader Graph editor, as I just said in that message
I know what the post says. I've read it before. It is irrelevant here.
Unless you're suggesting that Arc should go diagnose and fix an editor bug, it is not at all helpful here.
hmm if it goes away after a restart/console clear i wouldnt worry much about it
random unity shenanigans most of the time...
I've seen this error quite a few times
(both in questions here, and a couple of times in my editor)
Which is why I suggested that immediately, yes.
thanks!
Sounds like you are trying to refactor it because you're having a hard time time having it be extensible is that right? SOLID is def a good guideline to follow. How about events? Maybe scriptable objects to help decouple some stuff too ? I try to limit also how much I do abstract classes vs just utilizing interfaces when possible.
Is it possible to access the current deltaTime inside Fixed Update ?
Why do you need it? I'm not aware of a way
It's identical to fixedDeltaTime
If you want to reachout to Update deltaTime, you'll have to choose which one of the overlapping ones you want
FixedUpdate isn't bound to frames so it usually doesn't make sense to use deltaTime in FixedUpdate
the equivalent is fixedDeltaTime (which you wouldn't use in Update/LateUpdate either)
So probably a very simple question... I have an object I pick at random that I want to zoom in on, I was planning on setting it to a new parent with a larger scale, but of course this just adjust's the object's local scale down to maintain the exact same size. What's the best way for me to have such an object obey the parent's scale without impacting position and rotation?
you could just store your local scale before reparenting, then restore it
That's a good point... but I just realized that even if I have my way with this, the object will just suddenly pop to the new scale 😅 I'm gonna have to animate this to grow larger, aren't I? 😆
Yes, you will.
(I'd just "animate" it through code, of course)
rather than using an actual animator
Are you trying to "zoom in on" the object, or are you trying to make the object bigger
Make it bigger 😅
So doing that on the parent itself and just set the child to the parent, then fire the zoom in trigger should work since the modification is happening once the child is parented (I might have multiple children to make bigger)
I realized that starting a Coroutine during FixedUpdate meant that, during the first frame, the dt was much bigger.
But adding WaitForEndOfFrame(); at the beginning of the Coroutine solves it
I'd just use yield return null; to wait until the next frame
but that'll let you start moving on the same frame that you start the coroutine, i suppose
yeah, that makes sense
print(Time.frameCount);
yield return new WaitForEndOfFrame();
print(Time.frameCount);
=> prints 101 101
print(Time.frameCount);
yield return null;
rint(Time.frameCount);
=> prints 101 102
There is one very minor issue to worry about here
WaitForEndOfFrame() doesn't work if you don't have the game view open
(e.g. if you switched to the scene view)
Not a problem for the built game, but it could be a nuisance in the editor.
Oh I didn't know about that
Actually it feels somewhat counter-intuitive that the first block returns 101 101
Yes. It's deeply suspicious that the frame count isn't changed after waiting for the end of the current frame.
well, it's not waiting until after the end of the frame
Waits until the end of the frame after Unity has rendered every Camera and GUI, just before displaying the frame on screen.
Unity is done preparing the frame, but we haven't moved on to the next frame yet
That was sarcasm 

Good to know !
So that means that whatever happens after will not be rendered this frame
Everything that happens between the yields will happen in the same frame
So when waiting for the end of the frame, everything after that will happen in the current frame and stop just before reaching the next yield return
// frame 101
yield return new WaitForEndOfFrame();
// frame 101
transform.position = ...
foreach (...
yield return null;
// frame 102
// ...
Will that transform.position be rendered to the screen in frame 101 ?
but the point of WaitForEndOfFrame is that it waits until after everything is rendererd
this runs after the main camera has already rendered
you will not see the new position until frame 102
How would I go about dynamically creating text at runtime which starts above 2D scene position (x1; y1) and ends above (x2; y2)? I am trying to create something like this:
you mean making sure the text fits inside of bounds?
nvm, solved in another place I asked
Looking for some suggestions about namespacing.
I have an abstract class called Anatomy. It has properties for different points of interest on an entity: where its "center" is, where you'd look at to "focus" on it, etc.
I have derived classes like HumanoidAnatomy and ObjectAnatomy.
Which would you prefer?
- MyGame.Entities.Anatomies.Anatomy
- MyGame.Entities.Anatomies.HumanoidAnatomy
- MyGame.Entities.Anatomies.ObjectAnatomy
vs.
- MyGame.Entities.Anatomy
- MyGame.Entities.Anatomies.HumanoidAnatomy
- MyGame.Entities.Anatomies.ObjectAnatomy
I only ever reference Anatomy, if that changes anything.
I'm using [SerializeReference] so that I can pick a specific child class in the inspector
i don't have much experience with the c# ecosystem and how namespaces are usually named, but to me having MyGame.Entity.Anatomy.*Anatomy would be cleanest
with the Anatomy class in the same namespace
whats good fps for 1.5M tris in unity
I have made and been making changes to the code despite that VS editor error. Unity plays and runs no problem and unity itself does not detect any error. Originally, this "popped up" after I updated unity and that was 4 minor versions ago, and been living with it since. someone from the DOTS forum told me to delete the VS cache, etc, and though I thought I've done that, I may not have done it correctly and wanted to make sure if someone else might know better. but ultimately, I just want the editor to not see that line as an error.
errors appearing in VS but not the console usually means you just need to regenerate project files. if that doesn't fix it you might need to regenerate the entire Library in the project
ahh, how do I "regenerate" the project files? im pretty sure that's a manual process, can you point me to instructions?
in the external tools settings in the editor preferences
In unity, go to the external tools menu, it is just a button
For the library, that just means wholesale deleting the library folder from the root of the project folder while unity is closed. It will take a while to reopen unity because it will regenerate it
sorry, where do i find the external tools menu?
in the unity editor you need to open the preferences in Edit > Preferences
Is the return function no longer used in Unity?
huh?
well, the return statement sure still exists
the year is 20XX. C# is now 100% continuation passing style
Well when I TRY to type in return I just get something completely different
why don't you share the actual error and relevant code instead of making wild assumptions
Perhaps you are not in a context where return is legal
Show what you are trying to do.
Doing a regenerate files does not do it. I will try the deletion of the library files and see
Make sure to close your code editor and reopen it
so just simply delete the library folder in the project? anything else I should do as well?
Before you delete the library folder, I mean
When you do that, close unity, delete the library, and reopen unity
Your code editor may not notice the new project files until after you reopen it
you are trying to return from a class
look at your indentation
it is outside the method
i can't recall if I did close the editor when I did this before, so Im reopening the editor now after deleting the library folder. crossing fingers
Your code editor is doing its best to turn return into a legal statement
re: this, assuming you're talking about it replacing return with something else
yeah this is what I meant
Oop this
well, write your code inside of the method
You'll need to reopen unity for it to regenerate
deleting the Library wasn't enough. Once deleted, I open Unity and then do a Regenerate project files, that combination seem to have fixed my VS. Deleting the Library folder alone still did not clear the false errors. thank you all for your help.
Yea, that was a real annoying problem that crept out of nowhere seemingly. I'm glad I don't have to see that anymore 😄
next time (if there is a next time) as well as deleting the Library folder delete the .sln and .csproj files as well
Usually, I use the name of the company instead of the game. Given that script could be reused throughout multiple project. After, it makes more sense in my eyes to put the Anatomy into the Anatomies namespace.
Am I initializing this component wrong? I created that "PositionChangeTracker" component and every time I initialize it as the variable "pct", pct is null
I would rather just initialize the component in the script rather than having it be a public variable that I need to drag and drop yk
you don't really need to initialize components, you just need to retrieve them
that code looks correct, but make sure you're on the right gameobject
serialized fields are better, because they don't require extra work at runtime
they also make it more clear what object you're using
Show the entire inspector
also, what component is that script on the left from?
you don't get bonus points for showing really tiny crops; please provide more complete information
Thanks for the advice brother. No need for hostility, here you go
how are you verifying that pct is null? you aren't checking or using it
Right, I would rather it be private than have to drag and drop it. But it won't let me initialize it the same way I can initialize my rb2d. Yes pct is null if it is not dragged into the public variable, I debug.logged it
Line 19 is where I have the problem
you're grabbing the sibling PositionChangeTracker on the gameobject, overriding the value you set in the editor
do you want it public and set in the editor, or a separate component automatically grabbed from the gameobject?
If PositionChangeTracker is on the same game object as PatrollingSecurityBot, then GetComponent<PositionChangeTracker>() will retrieve that component correctly
right right that is what I am trying to do. I want to override it
I don't want to set it in the editor I want to set it in my script
You aren't using it anywhere else in your script, so I don't understand how you know that pct is getting a null reference assigned to it
Are you looking in the inspector at runtime?
then make it private
or a property
or add the nonserialized (i forget the name) attribute
That is the problem. When I make it private and initialize it that way it is null
One sec, I will show you
...why were you showing working examples before? why didn't you lead with the actual problem? 
If you got an error from somewhere else in the script, then I'll need to see that part of the script
Nothing in the code you shared uses pct.
!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.
Sorry! I was showing my workaround and trying to explain my problem. 🤦♂️
@fen. I can show you, but that isn't the problem part
I bet it really is.
unless it's just later in the Update method
Either way, I'd like to see the full code that's causing the problem, with no modifications
I fixed it 🤦♂️
I really don't know what the heck it was but when I put the code back the way it was when there was an error it works.
Perhaps you hadn't saved.
Probably something stupid like that. Thanks for yall's input. What does the serialized field do anyway?
it lets you set the value in the editor
But why not just use public? Just so other scripts can't access it?
Correct.
You want to minimize how much "stuff" is visible from outside of your class
That helps you to separate your interface -- how you interact with the class -- from its internals
it also tidies up your editor suggestions
you don't want to see 100 random variables when you do myClass. in VSCode
[SerializeField] tells unity that you want that field to be serialized, which means that it gets saved as part of scene/prefab data
Huh, I gotchu. Is that an optimization thing or just a quality of life thing?
the opposite is [System.NonSerialized], which indicates that a field should not be serialized
which is appropriate for public fields that you don't configure in the inspector
The latter.
It's particularly important if other people use your code
More than just QoL, it's how you build maintainable software.
"quality of life" is getting stretched a bit here, yes 😛
which, in my opinion, includes yourself half a year down the road
encapsulation helps enforce modularization/separation of concerns
Gotchu. That makes sense!
I have fallen in love with the unity events system for modularity. It is a godsend
It's especially important if you work in a team, if the internals of a class are always exposed and other team members can just publicly alter your internals, then if you ever want to change internals you can't, you have to also start modifying other team member's code which are using your internals.
That's really interesting. I have only done solo projects so I haven't had to worry about that lol
Yeah a huge part is that you want to maximize team members' ability to work independently and not stepping over each other. If you making one small change to your class means that you need to modify everyone else's code, then no one can be working simultaneously.
In a solo project, it's still nice to not have to go analyze every single random public field, too
All of my old code is 100% public fields (whenever I needed serialization, that is) and I don't like it
There's no point in having a 10 person team if only ever 1 person can be working at a time 😄
fortunately, all of the bad code was written by Past Me, not Present Me
clearly not my fault
I feel like I should have learned this foever ago. No way I am going back and changing all my code now though 😂
you can incrementally make members private
check if you have references from outside the type
if they exist, see if you can get rid of them without too much work
once there are no external references, make it private and add [SerializeField]
That's a good idea
My components often start out as just "bags of data" with a bunch of public fields
then I add methods to interact with them and make the fields private
(especially for stuff like UI prefabs)
Right, even in solo project you are still technically working with multiple people if you want to branch your code base, the other people are just you who are working on the other branches.
aren't collision and trigger calls suppose to be sort of propagated upwards and and call any trigger/collider calls in parents?
Fundamentally working on one part of the code base blocking the ability to work on other parts of the code base is just not ideal.
Nope.
They do get sent to a parent object with a Rigidbody on it, though
Triggers get sent to both the collider's object and the rigidbody's object
Collisions only get sent to the rigidbody's object
well I know this is wrong
But that makes sense, the rigidbodies in the parents
I was like I know i've seen this behavior before
Anyone here who can help me with object pooling?
Unity has built-in pool classes
for example
ObjectPool will use the methods you give it to correctly create and destroy pooled objects
the example on that page turns off the particle system when you return one, and turns on the particle system when you take one
dang well i really need to rethink my life
not ideal, sometimes unavoidable
I tested this a month or two ago. Are you seeing something contradictory?
yes, I just double checked myself before saying it's wrong, and I've done it before too.
so you have a Rigidbody component on a parent object
and you received an OnCollisionEnter message on the object with the collider?
I am trying to write a shader to fade between the color of objects in my scene and the skybox color based on distance from the camera, but my distance calculation method is not working. It is returning all 1, resulting in the objects being invisible because only the skybox color is being shown. Does anyone know how I could fix this? https://paste.ofcode.org/GmNB7J5gQULwRT7aAcpsNq
I had a rigid body on an object, which I had collide with a collider that had a script on it logging OnCollisionEnter messages.
how does terrain pixel error work
That is not what I'm talking about.
I'm talking about an object with a parent that has a rigidbody on it.
Ah okay, yes that I know. I thought you were talking in general for all those messages you sent.
I did discover that this is more complicated than I originally thought, though.
I wish the documentation clarified exactly what happens :/
- Rigidbody
- Collider <- trigger
If this hits a collider (trigger or not), both objects receive the message
- Rigidbody
- Collider <- non-trigger
If this hits a trigger, the Rigidbody's object gets a message
It is very opaque here, yes
I'm thinking of making a WebGL project that demonstrates the different behaviors. Might be useful.
- Object (non-rigidbody)
- Collider <- trigger/non-trigger
And here, only collider receives it.
Right, that's expected
My code is supposed to add movement on the X and Y as. When I try to run, it gives a compile errors. I cannot seem to find what I did wrong. Could I get some help with this please?
||
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
//Movement controlls
public string forwardMovementKey = KeyCode.W;
public string backwardMovementKey = KeyCode.S;
public string leftMovementKey = KeyCode.A;
public string rightMovementKey = KeyCode.D;
//Movement
public float movementSpeed = 5.0f;
private Vector3 movementDirection;
// Update is called once per frame
void Update(){
movement();
}
void movement(){
if (Input.GetKey(forwardMovementKey)) {
movementDirection += transform.forward;
}
if (Input.GetKey(backwardMovementKey)){
movementDirection -= transform.forward;
}
if (Input.GetKey(leftMovementKey)){
movementDirection -= transform.right;
}
if (Input.GetKey(rightMovementKey)) {
movementDirection += transform.right;
}
// if (Input.GetKey(KeyCode.Space)) {
// jump += transform.up;
// Prevent diagonal movement being faster (optional)
if (movementDirection.magnitude > 1.0f){
movementDirection.Normalize();
}
// Apply movement
transform.Translate(movementDirection * Time.deltaTime * movementSpeed);
}
}
||
!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.
if you could say what the errors are too that would help
its how to make funny code blocks
like this
backtick, `
not to be confused with apostrophe, '
// using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
//Movement controlls
public string forwardMovementKey = KeyCode.W;
public string backwardMovementKey = KeyCode.S;
public string leftMovementKey = KeyCode.A;
public string rightMovementKey = KeyCode.D;
//Movement
public float movementSpeed = 5.0f;
private Vector3 movementDirection;
// Update is called once per frame
void Update(){
movement();
}
void movement(){
if (Input.GetKey(forwardMovementKey)) {
movementDirection += transform.forward;
}
if (Input.GetKey(backwardMovementKey)){
movementDirection -= transform.forward;
}
if (Input.GetKey(leftMovementKey)){
movementDirection -= transform.right;
}
if (Input.GetKey(rightMovementKey)) {
movementDirection += transform.right;
}
// if (Input.GetKey(KeyCode.Space)) {
// jump += transform.up;
// Prevent diagonal movement being faster (optional)
if (movementDirection.magnitude > 1.0f){
movementDirection.Normalize();
}
// Apply movement
transform.Translate(movementDirection * Time.deltaTime * movementSpeed);
}
}
ok so what's the issue you're having
It gives a compile error. I have no clue what is wrong and would like to receive help how I can figure out where the error is
erm whats the error
It's a syntax error
Probably cannot convert from key code enum to string implicitly - unless there's an overload.
But yeah, you'd actually have to provide the error
it's an enum, so maybe
I decided to be nice and execute foreign code on my computer
ok so
Keycode.W is not a string
you didn't execute it, it has a compiler error
@umbral bolt so if you're not gonna let us read the error, at least read the error yourself
scroll up in the console, and have you set up your ide
No I don't think I have set up my ide yet
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
It's suppose to be key s or w
go set up your ide so your ide can tell you
fun fact of the day: hovering your mouse over a variable can tell you what it is
not if your ide isn't set up
ive always wondered, doesn't unity install come with visual studio?
minecraft font 
ive used it for two years my friends say its unreadable
lol as long as you can read it all it matters
but i love it
just thought it was funny
🎊
i know someone uses calligraphy font so you're safe xD
that is actually the old MSDos system font
you do have to select it, and it's deprecated for mac now.
It's an option
idk what happenign but my code has a sound effect when i shoot. the souns isnt playing when i shoot https://pastebin.com/WWRfMuSH
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.
quick survey react if you use vscode
or codeblocks 🧱 for unity
ahh so it is.. minecraft ripped it off haha
codeblocks is shit...
i want to see how many vscode users i run into in the wild
Make sure to inform folks if there are any errors
i know right, someone recommended it to me to learn java
no errors
never again
whats codeblocks?
i mean, my options are between that and rider, i think i'll go with vscode
Code::Blocks is a free C/C++ and Fortran IDE built to meet the most demanding needs of its users. It is designed to be very extensible and fully configurable.
i was in a computer olympiad and the stock computers had vscode, sublime, and codeblocks. literally noone i knew used codeblocks
why did they recommend it to me for java
no clue
alphabet 🤗
as much as I hate java intellij is so cool
did the logs print ?
Make sure to show the logs that would suggest it should but isn't.
i use android studio for non-android java... intellij just doesn't like to work for me for some reason...
isnt android studio a fork of intellij?
yeah the logs ran fine when something was wrong but im getting no indecation that the sound is working. i hear nothing
yes
that is very interesting
yeah i have no idea what's up with my situation
for me i was the opposite I used intellij with android for one of my modules
simply because I prefer modern intellij UI
wasn't even like. static analysis or anything fancy that broke either
I wish I could make UIs like them 
the whole damn ui broke
the layout was right but the background color was the warning color except in the gutter and at the very top
so perplexing
Every time I open Android Studio, it hogs all the RAM to itself.
isn't that all google products though
No clue.
Maybe they just expect people who use Android Studio to have infinite RAM or something.
but with the sponsor of today's video, oper-
put one inside the gunshot statement
nothing is wrong so i got no logs about it. but when something was wrong it popped up
no idea what that means
if you don't get a log you can't know if the values are correct or if that check just wasn't reached
yes I see the else statements are there if component is null but was simple asking to add debug.log inside here
if (audioSource != null && gunshotSound != null)
{
audioSource.PlayOneShot(gunshotSound);
}```
it could be hitting it and maybe their volume is muted or low, thats why we triple check and debug 🙂
meanwhile me deleting all the logs after "fixing" it only to have the same issue a few minutes later and have to rewrite all the logs
if you have vs set up for unity you should try pressing the big green button
I didn't know about this until 2 years after starting unity
I get so many questions everyday on my videos of people asking why their code isn't working. Sometimes its a simple typo you can infer from an error message, other times its a deeper issue.
Many beginner tutorials first tell you to start putting Debug.Log statements everywhere, which can work and if done well can be a good practice - but its mu...
fun watch but atrocious font
this will help you a lot in your journey rather than spamming Debug.Log everywhere(I still do that)
take great care in your art, especially because you prob wont come back to it later
my philosophy is that you should either:
- do it as fast as possible as a placeholder
- do it really well
if you spend a while but still need to replace it, then that sucks
plan out the classes you need first.
an inventory has a list Items. an Item has a name, icon, description etc.
public class Inventory {
List<Item> items = new();
}
public class Item {
string name, description
}
now you need a system to read from inventory. you also need a prefab to act as an item icon.
public class InventoryDisplay {
[SerializeField] GameObject p_itemIconl
void ShowInventory(Inventory inv) {
// for each item in Inventory.items, show the item icon and count.
}
}
something like this
I should make a tutorial on this
anyone able to help me understand why i cannot get an object to enable and another to disable
this seems so simple
how can we help you if you don't provide enough info
Ui -> Button (Text Mesh Pro)
Can get game objects I want when I click a button to enable and hide what I want properly
But using the legit same script to revert it back to the previous enabled/disabled state of the game objects
does not work.
so you
• add a event to the button to set a gameobject active
• add another event to the button to set a gameobject inactive
wat doesnt work exactly ?
if you want to toggle it, you need a script rather than depending on those two events
We have no idea what your script currently does
at very least in code channel you should be sharing the !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.
using UnityEngine;
using System.Collections;
public class PondCloseButtonScript : MonoBehaviour
{
public GameObject gamePanel;
public GameObject pondPanel;
public float switchDelay = 10f; // Time in seconds to switch to the pond panel
public float revertDelay = 10f; // Time in seconds to switch back to the game panel
public bool showDebugLogs = true;
private void Start()
{
// Ensure the gamePanel is active and pondPanel is inactive at the start
if (gamePanel != null)
{
gamePanel.SetActive(true);
}
if (pondPanel != null)
{
pondPanel.SetActive(false);
}
}
// Method to switch from gamePanel to pondPanel
public void ShowPondPanel()
{
if (gamePanel != null && pondPanel != null)
{
StartCoroutine(SwitchPanelWithCountdown(gamePanel, pondPanel, switchDelay));
}
}
// Method to switch from pondPanel to gamePanel
public void ShowGamePanel()
{
if (pondPanel != null && gamePanel != null)
{
StartCoroutine(SwitchPanelWithCountdown(pondPanel, gamePanel, revertDelay));
}
}
private IEnumerator SwitchPanelWithCountdown(GameObject panelToHide, GameObject panelToShow, float delay)
{
float countdown = delay;
while (countdown > 0)
{
if (showDebugLogs)
Debug.Log($"Switching in {countdown} seconds...");
yield return new WaitForSeconds(1f);
countdown--;
}
panelToHide.SetActive(false);
panelToShow.SetActive(true);
if (panelToShow == pondPanel)
{
Debug.Log("Success: Switched to PondPanel.");
}
else if (panelToShow == gamePanel)
{
Debug.Log("Success: Switched to GamePanel.");
}
}
}
i do not understand why this does not do what intended
well is the object that started SwitchPanelWith countdown get disabled?
is your Timescale set to 0 ?
so i designed this since for whatever reason I already have designed in a much larger web of scripts does not swap me back to begin with. So i copy pasted the button that originally did this and added an empty game object and put this on it to try and auto hide it after 10 seconds and even this doesnt work.
so im starting to think its something based on game objects or something i legit have zero unity experience im just making something for fun
well no zero, ive made vr chat avatars but with cs i am brand new
none of this answered my questions but ok 🤷♂️
it doesnt get disabled no
did you change timescale anywhere
put debug.log both inside where you cal StartCoroutine and the Coroutine itself
i think so but on another script
oh well then thats a problem
Realtime
yea WaitForSecondsRealtime
There's other places in your code that needs it
hmm lemme go study rq tyty
so I have some scripts in my Assets folder that need to use scripts in my Packages folder, and it seems that in order to do that I need to use assembly definitions? So I tried creating an Assembly Definition in the Packages folder that I need to use scripts from but I get the error:
"FolderAsmDef.asmdef has no meta file, but it's in an immutable folder. The asset will be ignored." it seems no meta file is being auto generated for the asmdef...
erm I don't think that's how it works
what package are you using
its probably in a namespace
its a crypto wallet SDK... i've tried adding the using namespace to the script i want to use it from but that doesnt work
well the weird thing is i can use certain parts of that name space but not this one part that i need...
//using Solana.Unity.SDK; -- the one i can't use
using Solana.Unity.Wallet;
using Solana.Unity;
what error does it give?
but i can do "using Solana.Unity.SDK" in a different script which is in my Assets folder
just not this one
could be a .meta file issue, in file explorer go delete the meta file for the script
nope, still same problem, it made a new meta file and same thing
yeah, ok i'll try
ok, the problem is till there
seems like something to do with compilation order
Deleting a .meta file will make Unity thing you've deleted the old script and created a completely unrelated script asset with the same name
.meta files are not temporary files.
This is not how asset importing works.
Are you talking about the Packages folder in the root of your project, or are you trying to modify the contents of Library/PackageCache ?
guys i made an active ragdoll but i wanted to make that when he picks a weapon the hands attach to the 2 empty gameobject (leftHandPlacement, rightHandPlacement). But how do i do that? I don't know if i well explained the problem
You could use a joint, or some IK with unitys animation rigging pack
can it work with an active ragdoll? I made the active ragdoll using configurable joints
and a target animation so the ragdoll follows the target rotations of the target animation
Yes but itll slightly take away from the "active" part. Like a joint would be preetty tough to configure so it actually holds the gun up, not an easy task at all. you'll likely just have the gun by itself. In which case you'll need the joints to pretty much always stay firmly on it, or the gun will visibly be floating.
Animation rigging directly takes away from active ragdoll because it controls the transforms directly
Stuff like this you'll need to consider what holding a gun even means, or how you want it to play out when the ragdoll gets hit in the arms
the gameplay is all ragdoll active. It's like controlling a dead body
that's what i wanted to do
i guess it was Library/PackageCache if i open the folder but i was trying to add the asmdef through unity editor here:
How did you get this package?
through Packange Manager and github url
show me the repository
You can't modify the contents of Library/PackageCache. They're generated by Unity automatically, and, as the warning told you, they're immutable
Well yea I read that. That doesnt mean much though. If you look at an active ragdoll in popular games it widely varies. Apparently GTA uses one, which I consider a large stretch of the term "active" ragdoll since it's all directly controlled by animations. Then you look at games like human fall flat where clearly you can see it's not controlled by animations
The package already contains asmdef files. They're also set to be auto-referenced, so they'll be accessible from the default Assembly-CSharp assembly
Are you using asmdefs in your own code?
what if i use a hinge joint to attach the gun to the hands and all the bodyparts between them? After that i'll put a box collider in front of the player like its children and apply forces to the arms when the weapon is not inside the box collider so the weapon is in the center of the screen
not really, i think i had to edit an asmdef once a few weeks ago though
the gameplay is first person
find out by searching your Assets for t:asmdef in the Project window
If your own code is included in an assembly definition, then you need to make that asmdef reference the Solana SDK assembly
You'll quickly find out why I said this is gonna be pretty tough to configure
The asmdefs in the package are set to be auto-referenced, so code that isn't included in an asmdef will automatically be able to see it
But if you create your own assembly definitions, all references must be assigned manually
ye i know it's pretty tough but i want to try. At this point i'll use no animations but just forces to make the weapon on the center of the screen and the arms attached to it by hinge joints
Forces alone wont solve the actual issues, like if your weapon or arms get caught on anything. A single wall would be enough to bug it out
well i have several asm def's popup when i search t:asmdef in Assets, i do recall now i had to include something in one of these before
Do you know what an assembly definition is?
from the name sorta, but not exactly what the purpose of it is, no
ty
You'll need to make your assembly definitions reference the package's assembly definition(s)
You won't be modifying the package's contents at all
i can try to solve it by just checking if the box collider is colliding with something and the distance between the center of the boxcollider and the object is greater than the half of the side of the boxcollider. If it happens it won't apply forces anymore.
Hey! I have quite a big problem: no matter what I try I can't know which camera (main camera or scene camera) is rendering. The best I can do is check if the focused view is scene view or game view but that means if I click on another window it doesnt work anymore
Sure, if that's the gameplay you want from it where the gun can just kinda stay far away. I'd really consider just having the gun not be a non-kinematic rigidbody though. Unless you really need it to react like the rest of the body, itll likely be better as a child object. Theres a ton of conflicting ideas between an active ragdoll, and being able to firmly grab something or do something in an exact pose. A lot will break
if i put the gun as a child object it will not move even by an inch
tytytyty, was able to resolve the issue
however i will try and see what happens
I joined this server to ask for help. For whatever reason, when i move a camera every frame using a script, the camera seems to try to move back to it's original spot right after.
Here is a video of the problem, and the code that seems to be causing the issue.
THE VIDEO CAN POSSIBLY POSE AN EPILEPSY RISK, SO WATCH ON YOUR OWN DISCRETION.
i've also tried changing this line of code to this (2nd image), but to no avail.
what is it you're trying to accomplish here
you can just use cinemachine
a simple mirror effect, via code and not shaders
all i want is just a solution to my problem, and i'll be good
how's a mirror effect relate to positioning
hold on lemme draw a sketch
i'm trying to achieve something like this, if it's not ideal, then i could happily take some feedback
is this fpv ? why not just use another camera and a render texture?
this is supposed to be a mirror script, that mimics how a mirror in real life works
I'm fully aware what a mirror is
i'm kind of confused, what are you asking again?
it was half a question and half a suggestion statement.
do you know how to fix my issue though? that's all i need, lol
if you already have a second camera, output it to a Render Texture, use it on a quad
what you're doing with position does not make sense to me, take the advice or don't
alright, i'll find a different solution to make a mirror effect. Thanks for the advice, though! 😃👍
Why is unity so buggy when it comes to booleans?
For your approach, The main issue i think thats happening there is that every frame you are applying the same logic, and since you are moving the object that you are also using as a reference it keeps switching, IDK if maybe changing
mainCamDistance = (MirrorCamera.transform.position - mainCamera.position)
to
mainCamDistance = (this.transform.position - mainCamera.position)
, since I assume you want the x value between the mirror and the main camera, not the mirroCamera and the main camera. I might be misunderstanding though
ok so basically the "MagicMirror" script/component is gonna be in a gameobejct which holds the mirror's rendertexture and camera
there's that, if it helps
(and yes i had it enabled when in play mode)
My code stopped function properly entirely all of a sudden, it was functioning properly before but it all of a sudden stopped working as intended...
The LustValue in the if statement is reached but it won't return as true for some reason
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.
Here is the other class used for it, the HDS https://pastebin.com/gaD0AD3p
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.
regardless of the setup, i want to point out something: Imagine your case when mirrorcam.x is 3, and mainCam.x is 1 and mirrorCamOrigin is 0
you do the math in one frame and end up with
mirrorcam.x being -2
next frame you have mirrorcam.x being -2, mainCam.x being 1, mirrorCamOrigin being 0
you do the math that frame and end up with
3
so, thats why it keeps going back and forth, as for the whole approach I cant say much about it, been a while since ive played around with render textures /cameras
You may actually never be hitting the exact value of 95f, you may be jumping from 94.90 to 95.6 in a frame for example, and your check wouldn't work.
Try printing the value in your update and see what the value is when you are expecting it to be 95.
You could try doing (int) HDS.lustValue == 95 to round the value to an integer and compare that, or do another approach at detecting when the threshold is reached. like maybe having a bool "lustReached" that is false and do
if(!lustReached && HDS.lustValue > 95)
{
Debug.Log("Reached");
lustReached = true;
}
the not-exactly-95 issue is probably caused by this:
Lust.value += 10f * Time.deltaTime;
what if the max is 100f, and it will only trigger if it reached 100f. It tried doing that multiple times but still not working for some reasons...
oh wait-- hmmm...
you would need to detect somewhere and actually program the cap
if(value > 100)
{
value = 100
}
dont have slider behaviour in my head atm so im not sure if the max is set to 100 if it would be able to go above it via code
but your line 37 in first script will be improbable to trigger. you would probably need luck to have the exact number be 95
it won't go above 100 if you set the max value of the slider to 100.
My if statement was 100f to trigger before but changed it to 95f to debugg somethings... I don't understand why it stopped working altogether because of those booleans
did you also change your sliders max to 95? if not then your value probably goes from less than 95 to more than 95 without being exactly 95 at any frame thus the check not being true
you could print the value in the update before your check to monitor and see what is happening
I change my value to >99f, then it finally started working
{
Debug.Log("Lust trigger");
// Climax, won the event
TouchArea.enabled = false;
HDS.isPanting = true;
Climax = true;
if(climaxMaxCount == climaxCount)
{
StartCoroutine(PantingWaitFinished());
}
else
{
StartCoroutine(PantingWait());
}
}```
are sliders really that inconsistent??
Im trying to think of a way I could manage different "surface contact" in my game for footsteps, things like walking on metal, grass, wood, etc, rn the best approach that comes to mind is to make a dictionary with a texture/material name as Key and a list of audio files as Value, but this relies on every texture/material in the scene to have a specific name, and I feel that could be difficult to manage - the only other alternative I can think of is to add a script to every surface in the scene with a enum, then the dictionary can be a enum Key instead, but this also means every walkable surface and prop/physics object needs a script with a proper enum assigned for every map, and that sounds like it can be easy to forget when building and changing map designs, any ideas on an alternative approach or is this enum-list key/value script on every surface probably the best for my use case?
@soft shard hii
Anybody know how to do a logical check for the velocity of a Rigidbody? I'd like to do a gate such as "if object.velocity < however you're supposed to represent a Vector3 type"
in order to check if the object is moving less than however many units per second in any two or three directions
Do you mean like this?
float value = 1f; private void Update() { if (rigidbody.velocity.magnitude > value) { // do X } }
A rigidbody's velocity is a Vector3, but by getting its magnitude you can see how "big" it is
I'm having some trouble with setting a direction for my particle system... Some help would be great.
Current code: https://hatebin.com/qawwlzwilk
I've tried a few things, but nothing seems to work as expected. I seldomly use Quaternions, and always struggle with them.
When testing, my current code sets X to around 4, while it should be 180.
I'm spawning the ParticleSystem on character A, and the PS needs to look at character B.
The current Y and Z rotations are correct, I only need to modify the X.
So let's say character A is standing at (0, 0, 0) and B is at (5, 0, 0), then I would need X to be 270
If character A is at (0, 0, 0) and B is at (-9, -9, 0) X would be 135, etc.
Z is always the same (2D)
All advice would be immensely appreciated!
direction is a quaternion and you are taking the x component of it and treating it as angle. You should never access the individual components of quaternions unless you know them "inside out" as the documentation tells and I myself defitely don't
I resorted to tinkering with the Quaternion directly as I couldn't find an answer of how to translate a (normalized) Vector3 to a direction. I did see the line in the documentation, but at some point I just resorted to trying everything I could think of and seeing what would stick
I think I got it, however, but I still need to do some more testing:
Vector3 direction = (target - particleSystem.transform.position).normalized; Quaternion rotation = Quaternion.LookRotation(direction); float x = rotation.eulerAngles.y; // Not sure why the Y rotation corresponds to the expected X, but it seems to work
You cannot translate a normalized Vector to direction.
If you're referring to the Vector, which means position, there is no way to simply get the direction out of position without any additional variables
Really? I'm definitely not a math whiz, but it feels so simple to just translate a position to an angle on paper, I would expect there to be something similar in code
What I mean is, if you have a position and no other variables, it's impossible to translate it into direction
But it seems that you have 2 positions in the code you've provided, so it's fine
I get it! Yeah, that would be difficult. I think it's easier for me if I understand the actual maths first, so I'll follow some maths tutorials and then see how those can be (/ are already) implemented in Unity. I'm pretty sure I had this math in highschool, but it seems very alien now haha
Also, I suppose, that the y axis corresponds to x, because the default 2nd parameter for the LookRotation method is Vector3.up, which is 1 on y axis. You might consider changing it to Vector3.right, which is 1 on x axis.
Quaternion rotation = Quaternion.LookRotation(direction, Vector3.right);
There is really nothing hard to understand in what I've just said.
Imagine having a branch on position (1, 1, 1).
Now you're asked what's the direction of this branch.
Well, how would you know its direction if you're only told its position?
If you're now asked what's the direction in which the 1st tip of the branch is facing, which is the difference between the branch's 1st and 2nd tips, you can now surely answer it.
I have no idea what you mean, sorry. I think we're thinking about this in different ways at the moment.
I'm now reading into the mathematical function to translate two positions A and B into the angle from pos A to pos B (which I'm fairly sure is atan2), and how to use it.
// Returns the arc-tangent of f - the angle in radians whose tangent is f
Mathf.Atan(offset.y / offset.x);
// Returns the angle in radians whose Tan is y/x
Mathf.Atan2(offset.y, offset.x);
Atan2 is just a fancy way to write Atan with 2 parameters
You can have this link as a reference
In your case A is A and B is C
I see! This, allong with your image, explains it marvelously! Thanks a lot. My tests are succesful as well:
Hey does anyone have the specific page for me that involves lambda capturing on this website?https://unity.huh.how/
I know it's there but I cannot find it
There's a search field at the top right side, type "lambda" there
ah
I did search that but I saw that the result was only IndexOutOfRangeException, so I assumed that was not it
Thanks!
{
if (inputSeed == "")
{
SetRunSeed();
}
else
{
SetRunSeed(inputSeed);
}
}
private void SetRunSeed()
{
//Create an 8 digit long seed.
for (int i = 0; i < 8; i++)
{
currentRunSeed += Random.Range(0, 10) * Mathf.RoundToInt(Mathf.Pow(10, i));
}
Random.InitState(currentRunSeed);
}
private void SetRunSeed(string _inputSeed)
{
currentRunSeed = _inputSeed.GetHashCode();
Random.InitState(currentRunSeed);
}
How would I go about converting my randomly generated seeds into strings I can display to the player that have the same seed when passed into the hash function?
GetHashCode should not be relied upon to give the same result for the same string every time.
Would you explain?
There's no requirement that it has to return the same value for the same object every time besides in the same run of the application, so it's possible that a string generates one hash code in one run, and you close the game/reopen the game and it generates a different hash code, effectively making your random seed unstable.
So unity's hash function is somehow based on the random seed they generate on startup?
This has nothing to do with Unity, GetHashCode is a .NET thing, and it's not required to be implemented to be stable across multiple runs.
It may be stable, it may not, that's why you shouldn't rely on it.
I'm feeling like that clashes with my understanding of the purpose hashcodes/tables but I'm probably misunderstanding something.
I guess my question is what would you suggest I do instead to get consistent translation between seeds?
Use an algorithm like SHA1/SHA256/murmurhash/MD5/etc, depending if you care about it being cryptographically secure.
GetHashCode is used as a preliminary step to speed up comparisons. It's not designed to be stable across multiple runs of the application because it's only meant for comparisons within the same run of an application.
Thanks for the help. This is the solution I came up with, exited out of unity a few times and everything seems to be working.
{
if (inputSeed == "")
{
GenerateRandomSeed();
}
else
{
SetSeedBasedOnInputSeed();
}
}
private void GenerateRandomSeed()
{
Hash128 newHash = new Hash128();
int randomlyGenoratedSeed = 0;
//Create a random 8 digit long seed.
for (int i = 0; i < 8; i++)
{
randomlyGenoratedSeed += Random.Range(0, 10) * Mathf.RoundToInt(Mathf.Pow(10, i));
}
//Add it to our hash, converting to string.
newHash.Append(randomlyGenoratedSeed.ToString());
//Set the inputSeed variable to the random number we just generated.
inputSeed = randomlyGenoratedSeed.ToString();
//Compute Hash
currentHashCode = newHash.GetHashCode();
Random.InitState(currentHashCode);
}
private void SetSeedBasedOnInputSeed()
{
Hash128 newHash = new Hash128();
//Add our input string to our hash.
newHash.Append(inputSeed);
//Compute Hash
currentHashCode = newHash.GetHashCode();
Random.InitState(currentHashCode);
}
That still does not guarantee to work, please just forget about GetHashCode existing at all.
It's from a different class. It's the implimentation within Hash128
Once you have the hash, extract whatever amount of information you care about and then use that as the seed directly, do not pass that through GetHashCode again.
This piece of code is not guarantee to work correctly:
currentHashCode = newHash.GetHashCode();
Random.InitState(currentHashCode);
It looks like this particular struct does have a deterministic GetHashCode implementation
public override int GetHashCode()
{
return u64_0.GetHashCode() ^ u64_1.GetHashCode();
}
Even if it does, that's just not something you should be relying on. It's not required to have this exact implementation everywhere.
Why can I not change my playersVelocity with this?
Vector3 playerRotationAngle = playerRigidBody.transform.rotation.eulerAngles;
playerRigidBody.linearVelocity = Quaternion.Euler(0f, playerRotationAngle.y, 0f) * playerRigidBody.linearVelocity;```
I want him to keep his velocity/momentum, but it just spins him in circles
I don't see any other way to extract the result from Hash128, other than turning it into a string and then truncating it
I don't see any reason to do any of this, though
Maybe use something else that allows you to directly extract an int out of it then. The point is that it's just a misuse of what GetHashCode is meant to do, even if it just happens to work for this case.
this is all superfluous. Just generate a random number.
They're implementing a string based seed, but UnityEngine.Random expects an integer.
The only feature this adds is that players can input strings as seeds.
Are strings allowed to be completely arbitray strings?
Your code generates a random 8-digit number
Yes. Only because I was unsure how else to handle generating a random string.
You can see that the input will take whatever string you provide it. It's just that the system will only randomly generate 8 digit numbers as seeds if one is not provided.
You can simply:
- For the case of completely random, randomize an
intand pass that to theRandom.InitState. - For the case of user inputting a string, use a deterministic digest algorithm (not
GetHashCode) and extract anintamount of data out of it, and pass that to theRandom.InitState.
GetHashCode is not meant to be used in this way, even if it just happens to work.
here's what I would do:
string input = "asdfjadsfklafjds";
var bytes = Encoding.UTF8.GetBytes(input);
var hashFunction = SHA256.Create();
var hashed = hashFunction.ComputeHash(bytes);
int result = BitConverter.ToInt32(hashed.AsSpan(0, 4));
Run the string through a hash function and truncate the result to 4 bytes
I've seen software which gives different result when run on different operating system, because they used GetHashCode for the wrong purpose.
You now have a completely random integer
This will work for any string, no matter how long it is
including 0-length strings and strings with emojis in them
today's random seed is 💯 👻
I'd use SHA3, but we don't have that yet 😭
Yep same as I said, digest the input, grab an int amount of data and use it as seed.
Isn't SHA256 overkill for this? Especially since you're discarding 224 of the bits it's computing?
sure, but the difference between it and, say, MD5 is going to be basically meaningless
You can plug whatever hash function you want in there
Hello
needed to know if this is possible
suppose i have a binary reader
in a specific class
that reads a specific file format i created
ScriptableObject proper event subscription & unsubscription
now suppose i am using a file explorer and loaded 3 files and used that custom binary reader class i wrote for reading the file format i created
i loop through 3 files
and load all their data
could you just send a single message to explain your problem
but is there a way to do this asynchronously
like when one file is loaded
it tells back
the other file is loaded
it returns the name of the file
more like a loading bar that completes when all the files are loaded
rather than the whole game pausing till the code is not finished loading all those files
in my case
I am loading more than 200 files
so i need a way to create a loading bar
sorry
I will make sure it doesnt happen next time
Depends on if your loading is IO bound or CPU bound.
i dont know
i am using a binary reader
Then profile it to figure out.
and i am loading mostly everything in memory and after getting the information
i release all the unused memory as well
Also what is IO?
Reading the files from disk, in your example.
If it's IO bound, it's very easy to just change only the IO to async and keep everything else in main thread. If it's CPU bound then you'd need to move things to a separate thread to do your deserialization.
input/output
the input/output between your cpu and peripheral eg your disk
public void InitializeRun()
{
if (inputSeed == "")
{
GenerateRandomSeed();
}
else
{
SetSeedBasedOnInputSeed();
}
}
private void GenerateRandomSeed()
{
string generatedSeed = "";
for (int i = 0; i < generatedSeedLength; i++)
{
generatedSeed += possibleSeedCharacters[UnityEngine.Random.Range(0, possibleSeedCharacters.Length)];
}
inputSeed = generatedSeed;
var bytes = Encoding.UTF8.GetBytes(generatedSeed);
var hashFunction = SHA256.Create();
var hashed = hashFunction.ComputeHash(bytes);
int result = BitConverter.ToInt32(hashed.AsSpan(0, 4));
outputSeed = result;
UnityEngine.Random.InitState(result);
}
private void SetSeedBasedOnInputSeed()
{
var bytes = Encoding.UTF8.GetBytes(inputSeed);
var hashFunction = SHA256.Create();
var hashed = hashFunction.ComputeHash(bytes);
int result = BitConverter.ToInt32(hashed.AsSpan(0, 4));
outputSeed = result;
UnityEngine.Random.InitState(result);
}
Alright. We good with this?
const int generatedSeedLength = 10;
const string possibleSeedCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Your GenerateRandomSeed can just be replaced with generating the seed directly, rather than generating a random input string and have it go through the same digesting process to get out a seed.
does this seem ok?
you might want to be able to tell the user which seed was used
(But it doesn't do that, so...)
UnityEngine.Random.Range uses an inclusive range, you would need to use Length - 1
(but also what burrito said)
It does save the information so I can later.
Okay then that makes sense. You can abstract away the repetitive code.
the int overload is max exclusive
oh wtf
The thing you are profiling for is that you need to be able to answer:
- How long (in milliseconds or whatever unit) does the entire loading process take?
- What % of that is in IO vs deserialization?
Then you can decide the strategy afterwards.
this is cursed then lmao
yeah, that's for floats
sorry
my loading is cpu bound
i guess that does make more sense though
if you meant by file stream
some files which are not packed are IO bound and are read through file stream
but some files are packed and then are unpacked and then read through memory stream
i dont know what the solution would be
Well, it doesn't seem like you have numbers to answer those two questions yet.
sorry
Whenever comes to a performance related question, the first thing is always to profile it, so you have concrete numbers to analyze. Guessing what the problem might be and throwing random solutions at the wall is never the way to go.
ok
let me see
how to check the % of IO and deserialization?
CPU usage while loading one file
28.978 ms
is it enough or need some more info?
You need to figure out how much time is spent reading the files vs decoding.
Fair point. I wound up using a name that isn't exactly the same as the game name
So it's halfway there :p
Hi frens
My coworker is producing code like the following, and I'm curious as to the general consensus.
I'm not crazy about the syntax or string comparison, but I could be convinced it's fine. My real concern might just be that in context, I just see it as hacky workaround used to perform logic based on the name of the game object instead more robust solution.
How could I phrase the theoretical "programmatical" solution in contrast to this solution based in string checking. imo, the script where the name checking switch statements should just be configured with the proper references, maybe with dependency injection. I would prefer just a chain bunch of if-else with string comparison over this strange use of the when keyword in a switch, but maybe that's just me being a curmudgeon.
Opinions?
switch (caseSwitch)
{
case string s when s.Contains("someValue"):
// ...
break;
// ...
}
when itself is not strange. This is just pattern matching.
However, basing your game logic off of the names of game objects is weird.
instead of the gameobject name, maybe use tags?
If this is a simple case, it might be best to actually keep it as a switch-case/if-else. To make it better you can wrap it in a function.
If this is case is more complicated, you might want to use Reflection, Dictionary or any design pattern that can be adapted to the situation. But, given the information you gave us, it is hard to know what could be better.
And if tags aren't enough - because Unity tags are limited to one tag per object - you can make your own interface for a custom tag system, and then any class can implement it
Sometimes the switch's case's would be all the possible names of the game objects that might be spawned instead of creating a variable to selection functionality.
Ew 😦

more than weird, it's fragile
Tags are horrible, that’s my input.
(Please do educate me if I’m wrong, sometimes I think I know stuff when I don’t)
Do any of the possible gameobjects share functionality?
Are you unable to share the full script?
I can't/shouldn't share the whole thing. He's used the pattern a few times, but I just had never seen the use of "when" in a switch like that before.
both the syntax and the use threw me off
when is fine, but the entire concept is bogus
It's not horrible, but is very limited, since you can only have one Unity tag per object. If you never need more than one tag per object, it's fine.
Otherwise, yes, you'll need a custom system of your own to replace it.
For a while I was using tags in OnCollision methods to check if the object was in the right ballpark before calling getcomponent, but I did some research and it's not usually worth it. unless you're dealing with a lot of collisions that don't carry the comonent you're looking for
I use when sometimes when I want a switch statement that operates on Vector2/3 or its Int versions. If I know I am dealing with a variable that will be equal to Vector2Int.Up or Vector2Int.Down, I can check for them. Otherwise you can't use Vector2/3/Int in a switch statement
Well, to be specific, you can't check if a case is equal to Vector2.Left (for example) because that isn't a compiler constant
In what context would you use a tag instead of layers and or components?
I don't think I use tags at all in my game, other than for MainCamera
bceause if I want to be able to put something in Group A, I also might want it to be in Group B
You can only have one tag
Yeah tags are a modularity-killer
Components are heavier than just having simple tags or custom tags. I wouldn't want to give objects empty components just to denote their types and other descriptive features.
So if I want to denote a creature is undead, incorporeal, a member of a certain faction, and other minor traits, I could use a custom tag system
well, you're going to implement that with a component, aren't ya
I use an interface for it
an interface implemented by what?
Ah, you're saying you don't want extra empty components on top of your existing ones
That is reasonable, especially if the "tags" can only be meaningfully attached to something with that existing component
Yeah, any monobehaviour can implement it. Like my base Character class, or Trap class, or Item class, etc.
in fact, it's more than reasonable in that case
it would be wrong to have a component that denotes an "Undead"
because you could slap it onto something that isn't even a character
that would be semantically wrong
interfaces are underrepresented in unity dev
my game is all-in on composition, so I don't really have "tags"
an Entity is a "foo" if it has the component that allows it to be a "foo"
Interfaces can be over or misused, but they're an excellent tool to break out of OOP overinheritance issues
You can use GetComponent with an Interface type, its so good.
Tags are also fragile because they are just magic strings.
Yeah, unity tags are. I usually don't use those
An alternative to scriptableobjects as tags in a custom system would be a flags enum (though then you're limited to 32), or a list of enums.
you can have a ulong flags enum so, 64
Is there any way to add assembly references? I'd like to use Span2D from Microsoft.Toolkit.HighPerformance.dll since I cannot use System.Span2D since that is a later version of c#.
if the dll is compatible .net version you can likely use whatever assembly you want
will it do what you want in unity 🤷♂️
it is compatible with .NETStandard 2.1 and .NETStandard 2.0, but I cannot figure out how to add the reference...
I just want it for the 2D span, since it was in this assembly before it was added to C# in the System namespace.
put the dll in your project and reference it in your asmdef
oh so I don't add it through the regular way ok
the "regular way" would be using nuget which unity does not support yet
Can i kindly point towards NugetForUnity
I have a mysterious asmdef used for nothing in my project that i'm afraid to delete
It works with all the libs i currently need so there's that
Even my own multiplayer lib works there
I use it for a couple of libraries. It has behaved well.
I guess as long as they support netstandard 2.1 it's fine
I tend to just extract the package and drop the dlls in, unless the transitive dependencies are getting too deep and it's too much manual work.
yea, thats why I was confused how to add
do you have version control? If so delete away
True (:
i personally use UnityNuGet which is curated so anything available is pretty much guaranteed to work.
however that doesn't mean that my statement about unity not supporting nuget was wrong though. and it's kind of silly to install one of those for just a single dll they need
Hello, I hope im in the right section. Sometimes when I close a project all the level layout disappears but only the game objects, but the scripts and the assets are still there. Anybody has any idea why this happens?
this is not a code problem. it sounds like you have the wrong scene open
if your library is being regenerated for whatever reason then you will need to open your scene again
Certain things will have it switch to a new untitled scene by default on start so you just need to find your main scene in your assets and open it back up
i have only one scene, the samplescene
look, this is all i have. It doesn't seem like I have any new scene
where did you save your scene to
Well, I just ctrl+s and than close the project. The scene must be saved manual every time?
if the scene got the * on the name, there is unsaved changes
you have to be mindful of looking at that
Create a cube. Save the scene. Close and reopen the editor.
The cube should still be there.
That sounds like exactly what I need, thanks
For UI, what's the difference between Image, Raw Image and Panel ?
Raw Image displays any type of Texture, while an ordinary Image only a Sprite. Panel is just a set up Image for your convenience
I'm seeing framerate spikes only when profiler is recording on remote machine. I suspect the spikes are due to profiling over network. Is there anything i can do to get an even clearer picture? Can I profile to like a dump file that I then check? Would a direct ethernet connection between game host and profiler help? Or should I just ignore the spikes that seem to only hit when profiler running and just look at the other frames
Not a code question #📲┃ui-ux
!collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
i have a class with a list of Stats, i want to populate the list with all Stats in my database of Stats
so in the default constructor i call this populate function, however it doesn't work when not in runtime since my database is a singleton mono with a list of scriptable objects (i'm simplifying, the scriptable object is a separate class with info to construct the Stat class)
if this a a good way to go about this, what's a fix to this to make it work in runtime or another approach to this?
Hey there everyone, so I'm currently working on a Friday Night Funkin Sandbox game in Unity 2D and I have made some progress, now the original game uses a different game engine which didn't agree with my laptop. I have created what's necessary for the game but I'm not capable of making a score/misses system so if anyone would like to help or volunteer that would be great, feel free to reach out to me!
Hey, I have a public float x = 2f; in a scriptable object, but it is set to 0 in inspector, any ideas why?
okay i added another temp field and then x refreshed
whats happenin
you probably didnt recompile after adding the =2f part. values serialized in inspector dont magically change when you assign a default value to anything, that'd break a lot of logic
am i supposed to trigger recompiling manually?
it should happen automatically after i save script and go back to unity right?
you can, by default i believe its whenever you change code and go back to unity. theres an option to change so you have to trigger it manually
why guess, just check it. also still doesnt affect what i wrote, i just suggested a possible reason why your value was 0. In that it was probably set to 0 before you added that =2f part
why guess how can i check it?
in preferences, there's a setting for "Auto-Refresh". if that is disabled then it will not automatically recompile when you save because the assets are not being refreshed automatically
there's also some assets that mess with the compilation process like Hot Reload. though theoretically that should be triggering more compilations, however I have seen issues where it was somehow preventing a compilation 🤷♂️
i have it enabled
i dont have Hot Reload enabled in this project
I will just call it a bug and move on
call what a bug? if you create a new asset does it still set the default values to 0?
nope.
I had existing asset. I added line of code public float x = 2f; and saved. Went back to unity. Checked asset. x = 0. Added another temp line of code. x magically changed to 2
Something is probably missing from the story here. For example you removed the field temporarily or reset the component
hm yea i guess thats a bug. unless you renamed the variable from x to something else
dunno, maybe Praetor is right and I just did something by mistake
we will never know what exactly happened
Any idea what causing this ? i trying to rotate single camera bone with mouse y and x
It's very very very hard to say anything without seeing the code
can someone please tell me the bind-pose of a bone of a skinned mesh, its relative to what? is it the world matrix or some matrix relative to root node or what
i'd expect it to be in the local space of the root bone
because that's the space that the local bounds are computed in
you're definitely doing something wrong with your rotations
!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.
Try changing the "Relative To" setting
Your local X and Y axes change as you rotate
it was worst with "relative to world"
one thing is missing but what
okay i solved
i sepereted x and y and made y related to self
Am I guessing right, that something like this cannot be invoked without a corresponding wrapper method?
events can only be invoked from within the object that owns them
thought so. thx
So, wrappers it is
If you need wrappers for events, then you probably are not using them correctly. An event is supposed to be invoked by the object's internal logic, not from outside of it.
I know i know
If you just make a wrapper to call it, then it's not an event at all. You might as well remove the event keyword
I just wanted to keep them in a one event class, but I now took them apart and put them in their respective parent
I wanted to be able to call them from one space, like a relay station and evryone would subscribe there (so i don't need to remember which event was where)
but yeah... just an idea, not good style
what you've described is basically an event bus
if you search that up you could see many different ways to implement that pattern
What's the best approach for a spatial inventory system from games like Tarkov and Arma: Reforged?
Quick question where did you even discover that the magnitude property exists in the first place because it's not in the documentation anywhere?** **
what you suggested works but I'm just curious
https://docs.unity3d.com/ScriptReference/Vector3.html
what do you mean its not in the docs?
it is the first property
oh it's a property of Vector3
I was thinking it was supposed to be a Rigidbody property
or some kind of sub property of its velocity idk
thanks though
no, they accessed the magnitude property of the velocity which is a Vector3
There any way I might be able to check for specific axes of the vector, like say just X and Z and exclude Y?
just access those properties on the Vector3. or do you mean get the magnitude of the vector without the Y axis
copy the vector3 into a local variable, assign 0 to the Y axis then access that object's magnitude
for context I'm using it to find a threshold for how fast the object is moving to determine whether it's stationary or not
and I'm doing that by comping the magnitude
Huh, that sounds a little hacky but it might just work, thank you friend
that's the best way to do it without actually affecting the velocity on the rb
one day when unity finally finishes upgrading to the CoreCLR we can use the with keyword to make that even easier. it could be var velocity = rigidbody.velocity with { Y = 0 };
That will be nice but I'll probably forget about it completely
What's the best approach for a spatial inventory system from games like Tarkov and Arma: Reforged?
stop reposting the same question over and over in multiple channels
try doing some actual research
Chances are if somebody knows how to help with your problem they'll see it in due time somewhere and will respond, and if it's something as general as an inventory scheme you're probably going to have to do as the above person said and figure most of it out yourself because that shit is almost always complicated and case-specific** **
best to just give it a go and then come with the smaller problems you encounter
Also what do you mean by a "spatial inventory"? They just look like a regular inventory with slots, is there a special feature in how they function in these 2 games specifically, compared to any inventory tutorial online?
also best to decribe it, i am assuming it is just the kinda where objects take up x amount of cells and can be rotated and what not to fit
So the difference is an item that is bigger like an ak47 could take up multiple slots, whether its dimensions are 2x3, 3x3, wahtever.
yep
I am not sure what approach I should take is it
would first get a inventory grid working
then after that when you drag things its just a matter of having each item define a shape, and checking for all cells within the shape if they are occupied or not
a quick google search of "unity tarkov inventory" brings up several tutorials, have you bothered checking any of them out?
really? lol I have only looked up spatial inventory, sorry for being so close-minded
Ah, that sounds like the same inventory as Resident Evil, which seems to be a game more covered in game development, you could try looking up research on how that game builds their, a keyword I found for that came across "tetris inventory system", could be another search term you could try, or just "unity C# inventory grid" or similar
yeah Res evil has it
how should I define the grid, just like a 5x5 array of images?
The grid doesn't need to be related to gameObjects. It can just be a 2d array of ints, where each int corresponds to an item id or null.