#archived-code-general
1 messages · Page 189 of 1
yes, that worked nicely, thanks!
is there a simple way to set up moving between selected buttons via dpad/arrowkeys without using a script?
i’ve been coding everything by hand, but now that I get into more hard-coded menus, I’m wondering if there is a better way
well, by default, you get automatic navigation
which tries to figure out where to go based on screen position
did you run into problems with that? I know I did.
i have not tried
my arrow keys normally move a cursor on the screen
maybe i need to decouple it to gain that feature?
StandaloneInputModule should handle it
New Input system also has ui input module
is it fine to use the new keyword to create a new instance of a class that inherits from ScriptableObject, using a normal class constructor, or do SO's have some issues with new like MonoBehaviors do?
Is this valid?
public event System.Func<IEnumerator> ShotBall;
This is the script that listens for the event but when I invoke it it seems to not be activated:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DistanceDisplayer : MonoBehaviour
{
[SerializeField] private float collisionDelay = 0.1f;
ProjectileLauncher projectileLauncher;
private void Awake()
{
projectileLauncher = FindObjectOfType<ProjectileLauncher>();
}
private void OnEnable()
{
projectileLauncher.ShotBall += DelayCollision;
}
private void OnDisable()
{
projectileLauncher.ShotBall -= DelayCollision;
}
private void OnTriggerEnter2D(Collider2D collision)
{
Transform passedBall = collision.gameObject.transform;
print(passedBall.position.x);
}
IEnumerator DelayCollision()
{
print("Off");
GetComponent<BoxCollider2D>().enabled = false;
yield return new WaitForSeconds(collisionDelay);
print("On");
GetComponent<BoxCollider2D>().enabled = true;
}
}
dont think so
as in it's not fine or it doesn't have the same issues as monobehavior? 😄
its still an Object from unity, so it works similiar to MB iirc
This works with a normal void function but I'm wondering if I can make it work with events
if you want to create one at runtime use thishttps://docs.unity3d.com/ScriptReference/ScriptableObject.CreateInstance.html
also they do run Awake()
so thats kinda like your constructor for it ig (ofc is not a real constructor)
hmm ok. this is fine, just wasn't sure. thanks.
i havent use event (i use system.action) and i think this is weird if your event have return value
int i=ManyFuncReturnInt.Invoke();
how can you determine i value?
update: both invoke and () returns void
afaik, garbage collector won’t destroy it automatically
the whole point of an SO is to not be destroyed
if you are creating an SO at runtime, your usecase is probably wrong
if you need persistent data saved between playsessions, you should save to a proper file like a JSON. Or use playerprefs.
if you need to just store data that can be created and deleted during runtime, a POCO might be better.
yea I was simply creating a "bleed" status effect that was inheriting from "StatusEffect", and simply doing new Bleed() and send in the variables on creation was an easy way to generate new bleeds with variable values. However I also wanted other status effects that would work better as SO's so I was trying to see if it worked so just do new on an SO.
It does complain but it also works, so I guess it would be fine if I manage it myself, but I can also just instantiate the bleeds as SO's and then change the values on the clone so it's all fine I think.
Hmm never heard of this before
hmm
ie don’t inherit from Monobehaviour, nor scriptable object
Not really, the point is that you have a single reference containing your data. The only reason why it does not collect it automatically is that as long as you use it, it is not destroyed or collected by the GC.
An SO is great because it reduces memory usage since all your reusable data is in a single reference rather than multiple primitive/complex fields
Anyone have any suggestions on how to store timestamped data for quick access? Essentially my gamestate is driven by IRL timestamped events. This is sort of a DSA question. I don't think a hashmap/dictionary would work well because the timestamp would have to match exactly when trying to key in on the time.
if you use an SO, then you have to manually destroy it later to clear it
because you are creating it, and you are now responsible for destroying it
Users need to be able to navigate back and forth between the timestamped data, and ideally they should be able to change the time scale as well to essentially move through the data at say 0.5x or 2x
Linked List and Binary Search
It is not normal to use an SO and to use new() or anything like that. You are supposed to make an SO in your editor, and then reference that inside your components. Making multiple instances of the same SO beats the purpose of a SO.
hmm maybe. it's just that i have some use cases where i'd like to have a custom status effect that I can then do a comparison to, where just popping in a scriptable object to compare to would be nice.
i'll consider POCOs so thanks for the suggestion
and if you fuck up the creation/destruction process, your project will have a bunch of SO files lying around
skip list/sorted set
you should basically never make a new SO during runtime, and only in editor
I'm not familiar with a skip list, I'll check it out. Thanks!
i make clones of them sometimes but that's it. i guess i need to handle destroying those too.
But why make clones? They store data
That's definitely possible. Lookup would be O(logn) though as opposed to O(1), but there may not be a way around that since I don't think I can use a hashmap as mentioned
If the data changes, make a new SO in the editor
but you cannot get o(1) unless you know the exact Timestamp
Yes, that's a good point
so, I have an EntityDataOriginal class. This tells exactly all the vulnerabilities and deets of an enemy. It is basically an immutable SO. During runtime, I make a POCO duplicate of it, which is mutable. This way I can make multiple entities which can have their vulnerabilities change during runtime, separate from each other, without altering the original.
and the GC automatically clears the mutable copies whenever enemies are destroyed
this is an example for robin
this maybe better but i havent implement a interval tree before
https://www.geeksforgeeks.org/interval-tree/
@hard viper thanks
How do I know if a point is to the right or to the left of my character if the character might be on a tilted plane, tho not too much so?
are you in 2D or 3D
and what do you mean by “right”
transform.right points to the right, after adjusting for rotation, but not for scale
so… what is “right”?
Let me draw
Well you could use the dot product here, against the player's right direction and the direction to the enemy. If dot is greater than 0, it's on the right, if less than 0, it's on the left.
Depends on the character's rotation
so you mean the character’s right
Yep
can the character’s scale be negative?
No, never heard of anything like that
negative scale mirrors you
Also it's important to consider that the player is always standing perpendicular to the plane it's standing on
in this case. transform.right is a vector that goes to the object’s right
given any applied rotation
I need to know not the character's rotation but whether a coordinate point is to the right or to the left of the character
if your character is straight on the plane, then transform.right is along the plane. If the character is always straight up (world up), then transform.right just points to the right given rotation
this is important to establish because if you are mirroring your character, transform.right is pointing to the non-mirrored right
Okay
so now you have a vector pointing from character to his right, yeah?
Yeah
so (pointOfInterest - transform.position) is a vector that goes from your character to the point of interest
which could be an enemy’s position or whatver
then we have transform.right dot product with (pointOfInterest - transform.position).
if this dot product is positive, then the vectors share enough component to be in the same direction
if it is negative, they are opposite
if zero, then it’s straight perpendicular
do you understand so far?
Everything besides the dot product
do you not know what a dot product does, or how to do it, or what?
School was so long ago I've forgotten it
you should learn again. vector math is important for this sort of thing
vector v dot u = v.x * u.x + v.y * u.y + v.z * u.z ….
I also saw cross product being used for these things. Which is better?
cross product and dot product are two totally different things
dot product takes in 2 vectors (can have any number of dimensions), and outputs a number
cross product takes in 2 vectors (usually must be 3D), and outputs another vector (also in 3D) which is perpendicular to both
totally completely different
dot product is bigger if two vectors are in the same direction
when working in spatial coordinates, dot product of zero means perpendicular. more positive means they are more oriented together. more negative means more oriented opposite
vector2.up dot vector2.up = 1.
vector2.left dot vector2.up = 0
vector2.down dot vector2.up = -1
make sense?
Does, does, tho I think I need to give it more thought to understand how it works with vectors which don't have a 0 parameter
Okay, thanks. Evidently I need to know at least this much
yeah. it’s basically mandatory to work with vectors
i will say dot product shows up a lot more than cross product.
cross product gets you a vector that is perpendicular to 2 other vectors. dot product generally tells you how aligned 2 vectors are.
but i work in 2D, so I never need cross product
I wonder if you didn't consider some cases which won't work in 3D with dot product
dot product is dot product
you can have 69-dimensional vectors, and its interpretation does not change
If we want to know how aligned are your vectors in 1 dimension still
same thing
Not complaining, just stating
linear algebra is rarely taught with a specific number of dimensions in mind
only bad teachers will force learning in specifically 2-3 dimensions
Okay, thanks, gonna code it fast and go learn right after that
gl
sounds like one of the gameobjects is destroyed when you switch scenes. It needs to be marked with DontDestroyOnLoad(this)
#💻┃code-beginner if your manager needs references to an object that's destroyed when you switch scenes, you need to find a way to make sure either that that object isn't destroyed or that you generate a new one
I have separate animations for when my character is going slightly to the left or slightly to the right, it's controlled by a boolean animator parameter called TurnRight. The character is moved by root motion. So when it moves to the left or to the right, it almost always gets a bit off and needs to slightly turn to the other side. It results in a twitching animation. What do I do with considering that I would like my character to go as straight as possible?
it depends on how you are moving
you need to expess your turn in a variable that does not change instantly like that
Will make a blend tree I guess
Atm I'm trying to make a sub-state machine in my animation controller, but I can't find a way to exit from any state in the sub-state machine. I can make transitions neither to Up (Base Layer) nor to Exit. What do I do?
public IEnumerator SpeedUp(float speedMultiplier, float duration)
{
float timeRemaining = duration;
while (timeRemaining > 0f)
{
movementSpeed = Mathf.Lerp(baseMovementSpeed * speedMultiplier, baseMovementSpeed, 1 - (timeRemaining / duration));
timeRemaining -= Time.deltaTime;
yield return null;
}
movementSpeed = baseMovementSpeed;
}
I have this decaying speedup function in my player script that basically enables on certain conditions (e.g. colliding with a speed boost causes the speed boost to call this function), however this has unintended behaviour once i pick up multiple speedups. How do i go about ending the previous coroutine? Can i store a reference of it on the player script?
changed my public method to be this instead:
public void SpeedUp(float speedMultiplier, float duration, string name)
{
if (coroutine != null)
{
StopCoroutine(coroutine);
}
coroutine = StartCoroutine(SpeedUpCoroutine(speedMultiplier, duration, name));
}
I guess in the future i could hold a list of coroutines instead and iterate or key/value them if i have buffs that are multiplicative
I would store a reference to the Coroutine.
private Coroutine _boostCoroutine;
void SpeedUp(...)
{
if(_boostCoroutine != null) return;
_boostCoroutine = StartCoroutine(SpeedUpCoroutine);
}
yep, ended up doing that! The coroutine there is the reference, i just made it stop and reapply a new one since in my case i wanted it to refresh
You could just not restart the routine but instead reset the time remaining (implies it's a class member) ?
True, that could also work if i stored the timeremaining outside the scope of the function
The coroutine will stop as soon as the code has been executed.
So, he will have to have a while loop in a coroutine.
I don't think that it's an optimal solution.
He's already got a while loop and it's preferred over restarting coroutines, iirc
I don't know if it even matter performance wise.
Coroutine is designed to do some stuff and exit.
Even it's name implies that it's a co-routine.
if there's a better way to handle that than a while loop i wouldn't mind changing that too. I just needed a decaying effect and am not too familiar with the tools unity/c# offers out of the box
Maybe garbage allocation can be an issue though...
Generally you'd let the routine run as long as possible - often times with infinite loops (not preferable in your case though). The condition to continue is something you can easily manage as a member of the class.
I don't think that it's the best approach, since coroutine runs on the main thread.
A big reason to use coroutines is that they can yield the main thread for other code to run, and RESUME later.
Hey
So
sorry to interub yall
but
I tried to code something and it kinda buggs out
Please type a paragraph instead of one word messages
I have a preety problem with that
I made a script that breaks a capsule in 2 when you press B, but that makes the capsule dissapear
You can show the !code like the bot below will say. We can take a look
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
I just don't get why to use a coroutine not for a something task-like, if you need to run something 'forever' as Daphlat wrote, just use an update method.
It won't allocate anything.
For me, makes delays easier. I prefer a waitforseconds that I allocate once in awake over accruing deltaTime
But yeah, it's a choice
Hmm, and that destroy call is destroying the miniCapsules?
Weird. They aren't being parented or anything
Why do these have different positions when they're in the same place?
Talking about the x component here
Do you have any other scripts attached to the capsule?
Definitely so and very applicable in his case however if you've got a lot of statements that require yielding at different intervals, it could be annoying to manage those states and the states of the delayed intervals.
No.
Well, it was a question. Are the two minicapsules dissappearing?
They are dissapearing
Do they perhaps have the same script on them?
It would be similar to using delegates with events versus calling functions directly.
Can you show the inspector for the minicapsule prefab?
Sure
They SAID no scripts attached. But that's part of why I asked for the inspector
There is nothing in the code that should make them dissappear, and obviously no other scripts on them...
Can you make a short video showing it happen?
yes
Can it be, that they spawn, but because of the prefab offset, they do it in the wrong place?
They definitely spawn, try resetting offset of the prefab transform.
Also try freezing rigidbody position.
How would I do that?
man, look ar your heirarchy, they have not disappeared
Order of ops SHOULD make the offset transform.position + (2,0,0) or (-2,0,0).
They are getting chucked, or are below the plane?
Here, right click transform and then click reset
The capsules tip, so the offsets are weird too, more up and down than left and right
Pause after you press b, select one of the minicapsules in the hierarchy and press f
Now what?
where is it
Well where did it take you
in the air
hmmm
Lower force a lot maybe?
debug.log your spawn position and force
Also freeze the og capsules rotation
You have no mesh renderer
#archived-code-general message
they do not have a renderer
You may wanna recreate the prefab
Did you make an empty gameobject and add the collider and rigidbody?
Create a capsule instead
well do you see it now?
You ADDED a renderer? It should come with one...
Mesh renderer
@toxic helm create a separate capsule
compare your capsule to the unity one
figure out the difference
apply the changes
on a empty smth smth
Guys, can someone get the exact world position of a screen touch with a perspective camera?
on the way you can also read what different components do by clicking the help button to the right of the component title
Don't use empty.. go to 3d, select capsule
After this what?
there is no exact position for a perspective projection, you get only 2 axis x,y from the screen space, Z is arbitrary, you chose it
Do whatever, that's it. In your case you wanted a rigidbody, right?
describe your task and ill help with best method to find valid Z
I'm trying to do a top down game, can you get the position for only the z and x axis as if it was x and y for a 2D game?
the height will remain constant?
doesnt matter really, this is a clear case of Plane struct
when you click, you create a Plane that points up, then you create a camera ray and do plane.Raycast
well, not really. But I basically don't want to get the y axis at all.
this will give you the point on said plane
to modify height you just change the supplied position when you create the Plane
is it possible to just ignore it and get the touch in the x and z coordinates?
alternative to this is a cumbersome method of calculating distance from the camera
you need to provide a Z when you compute screen to world
since camera can be anywhere like -21.4f z
and your ground plane can be 1
the resulting Z of the point before convertion will be 20.4
you can do all that or just use the plane
It's probably not because of your code. Reboot, make sure your GPU drivers are up to date, install another version. That bright red Windows Update icon might have to do with it lol
just updated rtx drivers, imma try to update windows as well
ps. I changed ssd by cloning all of my data
is that a laptop
nop
idk
did layout reset?
at first only hiearchy was rendered well, but when resetting layout everything turned to black
I also posted on #archived-hdrp for something similar
related also to the editor
If nothing helps you can try DDU (Display Driver Uninstaller)
Download it from guru3d
Load in safe mode
Open it, select your gpu and click delete and reboot
Exit from safe mode
Install drivers again
im updating windows
and then if nothing helps ill try what you told me
and dont install geforce experience
right
GeForce: Experience Pain
installed it once with the driver back when it released, uninstalled and never reinstalled it since
So true
Am i just so lucky to never have a bad experience with "dreaded" sofware?
ohhh
always worth doing that
nop
you can get some wild gremlins in there
nope
ok imma try
ps. the project was with HDRP
should i create it completely blank? (i assume so)
okk
I could see a rendering error in the scene view causing the rest of the editor to explode
true
may crash the driver even
test blank, if ok, test empty hdrp if ok, its Library/Temp or something specific to the project
right
Its kinda better but I still see weird behaviors that i've never seen, like wrong icons on wrong buttons that if i hover they look what they should look like
and still weird things
tried reinstalling the editor itself?
I tried to reinstall it three times
even different versions
nothing helped
everything happened after I changed SSD nvme
which I cloned
from my old 256gb ssd nvme with a tool
never had these problems before
Just did what you said
Did it help?
Im just going to install drivers
Can someone please explain to me why having a perspective camera affects things like converting screenToWorld position or ViewportToWorldPos when you put the z-axis to 0 even though you don't want to use it?
I just want to achieve the same result as by using an orthographic camera
is there a drawback of using a number I got from trial and error? I tested using distance of 10 and it now works and clamps devices with different screen sizes.
The first one is a range variable, whats the second? I wanna look up a tutorial but no idea what to even search
not sure about that one sry
Sounds neat.
how to connect to planetscale, and get data? I am currently stuck on:
Assets\Database.cs(5,7): error CS0246: The type or namespace name 'MySql' could not be found (are you missing a using directive or an assembly reference?)
but I can't
dotnet add package MySql.Data --version 8.1.0 to unity
from terminal in project folder, ./Assets, or parent
if i had a function in a script that i wanna ignore if i check a box in unity editor, how would i write that? basically when i turn on the checkbox it turns on the function to appear in the editor like the variables in the function
if (boolVariable) return;
^ this is an early return. Put it at the top of the function
That's the best I can say
The method will still be CALLED. It just won't do anything
well i know that but what i want, is if its check to true, the variables of the function being checked show in the edtior, and if its checked to false, the variables dont appear
Is this an editor script? What do you mean "variables of the function"? Like local variables?
Are you using "function" to mean script? Maybe that's why I'm confused
yes, like when i check the box to say i wanna use that function, THEN everything having to do with that function appear in the editor
no
I have no idea what this means. Sorry. Maybe someone else does?
think about it, when i check a bool in the inspector, saying for example, "i wanna use jumping" then the variables in the script for jumping appear in the inspector, but only when the "i wanna use jumping" box is ticked to true
Those aren't local variables like I asked before. Those are just variables in the script. I think the confusing part is that you're talking about a function, but really that is kinda irrelevant to what you want.
But no, I have no idea how you'd do that that without a custom drawer
Maybe something like naughty attributes or odin could get you that functionality
yeah i explained it weird myb
is there any easy way to change all the fonts of every TMPro textfield in the editor? only other option I'm seeing is to make a script TextManager that deals with it on runtime... but that seems crappy
ehh well i dont really need it to do that but i was just thinking it help organize my scripts easier
What you want is to toggle serialization
And I don't know how
Sounds interesting though
just use "find objects of type" then make a array and put each one in the array, then make a for loop saying to change each or font
yeah idk i just thought there was a simple function or something to do it but maybe not
Seems like what you wanted
Like I thought though, it's a custom editor script
I didn't find any attribute for that unfortunately
so that works for my scene objects, sadly it doesn't for procedurally generated objects, since they are initialized after Start() I would need to somehow put a timer in update and only run once there instead?
like wait 0.2 seconds in update with a Coroutine, then check all the GameObjects?
damn i dont like this solution 😦
dang uhh well for the editor idk about that
you could just get the objects every time you instantaite them tho, but that would be resource heavy maybe
hmm intresting, thanks for looking 🙂
maybe there's a way I can just override the default loader for TMPro
to force a font whenever anything loads it
so that way it's before runtime
ya know?
well, sorta at runtime
sorta before
yeah look at the TMPro documentation maybe
Do find at the beginner, and keep that in a list. And like ghostguy said, keep a reference when you instantiate them and add that to a list? Then just iterate the list
Might be a better way but I dunno
Maybe the Localization package could help?
Nothing I've ever done
yea but when do i iterate that list? cuz its after Start(), it could make some wonky looking behavior in the game
as in all the fonts will visibly change on the screen
Whenever you wanted to change the font.
Are you saying you want to just change them NOW, outside runtime? Must have misunderstood, sorry
yea i just want a way to load one font into all my TMPros
before the game starts
i used a font i dont like, and i want to change it. but i dont want to have to change every tmpro in my editor
and also, if i want to change again later, its even more work
im investigating an override solution for some of the TMPro classes
Uhhh, this looks really hacky.... but
https://gamedev.stackexchange.com/a/202702
LOL! i was thinking of doing a nameswap thing too, but so janky
so keep same name, but replace the reference in that file. it would work
there's gotta be a better way
maybe I just change the default font, and then remove the font from all the tmpros in my editor?
so then it just falls back to the default
ill try that out and see
nah doesnt work, it just changes them at the time you set it to None in the editor
do the default
short of just attaching a script to each tmpro and then hooking that up to a textmanager
yeah I mean that works, its annoying to attach a script to every TMPro GO, but it's only the ones that are prefabs
so not too bad
Is it the correct behaviour for the Editor to crash on stackoverflow? Isnt there a way I could somehow keep it alive (if, for example, I catch the exception in debugger).
You can catch the exception in your code.
I'm not sure if a debugger attached to unity editor can break in error automatically. Might want to check the relevant settings in the debugger.
And yes, depending on where it is thrown, stack overflow might crash the editor.
[SerializeField, HideInInspector] private GameSettings gameSettings = new GameSettings();
[ShowInInspector, ShowIf("@gameSettings.hasLoaded == true")]
public GameSettings GameSettings
{
get
{
if (gameSettings != null)
return (gameSettings);
else
return (null);
}
}
GameSettings is a POCO class with [Seralizable], Would my GameSettings property be getting a reference to gameSettings here or making a new instance/copy of it
any advice for getting like the framework of 3D dungeon generator
like placing rooms, etc.
would i need to have a room prefab, or could i just generate using the floor tiles, wall tiles, etc. of a room
Classes are passed by reference, so yes.
Also that null check is redundant. As well as the parenthesis around gameSettings and null.
Either one is possible. It's all up to your system design.🤷♂️
will never be null
guys, how can I create a plane to get the worldpos like in this article? https://unity.huh.how/programming/specifics/screentoworldpoint#interactive-diagram
What I don't understand is the warning
Yeah was just figuring that out haha, swapped it out for a better check 👍
some gibberish
what i mean is that SerializeField will create an instance
unity doesnt allow nulls on objects
yee
and if it were null at any point
@gameSettings.hasLoaded == true would throw
whats up with the ( ) btw?
i just like ()'s around my returns...
My camera is set to perspective and I'm trying to clamp my player's movement with this code and it worked. Just that I solved it with trial and error until I ended up with the number 10 for the z-axis (for some reason).
Do you know a better way to do it? Or should I just leave it like this?
i explained this already in detail to you
the 10 comes from distance of the camera to ground
reread our previous conversation its all there
what are you clamping?
player position?
yes
make a trigger collider, use its .bounds to get min max
modify it in the scene to setup the playable zone
bounds are axis aligned so dont rotate it
okay
Hey guys, I'm receiving this error when trying to open a script to see its content in the inspector. Any ideas as to why this might be happening?
public class DischargedSpellcast : NetworkBehaviour
Share the whole script.
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Sharing the details of the error/info messages would be helpful as well
Unity.Netcode.Editor.NetworkBehaviourEditor.RenderNetworkContainerValueTypeIEquatable[T] (System.Int32 index) (at Library/PackageCache/com.unity.netcode.gameobjects@1.6.0/Editor/NetworkBehaviourEditor.cs:146)
System.Reflection.RuntimeMethodInfo.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) (at <1c8569827291471e9db0dcd976e97952>:0)
Rethrow as TargetInvocationException: Exception has been thrown by the target of an invocation.
System.Reflection.RuntimeMethodInfo.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) (at <1c8569827291471e9db0dcd976e97952>:0)
System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) (at <1c8569827291471e9db0dcd976e97952>:0)
Unity.Netcode.Editor.NetworkBehaviourEditor.RenderNetworkVariable (System.Int32 index) (at Library/PackageCache/com.unity.netcode.gameobjects@1.6.0/Editor/NetworkBehaviourEditor.cs:102)
Unity.Netcode.Editor.NetworkBehaviourEditor.OnInspectorGUI () (at Library/PackageCache/com.unity.netcode.gameobjects@1.6.0/Editor/NetworkBehaviourEditor.cs:268)
UnityEditor.UIElements.InspectorElement+<>c__DisplayClass59_0.<CreateIMGUIInspectorFromEditor>b__0 () (at <a47f8e4b37a644dfaac5a6945ff77d47>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)```
Something with a network variable I guess.
beast
it was a declared network variable that was never used
I'm surprised it would throw such an error
what gave it away?
There's RenderNetworkVariable method in the stack trace.
Awesome, thanks again
ERROR:
Unable to resolve reference 'Google.Protobuf'. Is the assembly missing or incompatible with the current platform?
Reference validation can be disabled in the Plugin Inspector.
Unable to resolve reference 'K4os.Compression.LZ4.Streams'. Is the assembly missing or incompatible with the current platform?
Reference validation can be disabled in the Plugin Inspector.
Unable to resolve reference 'BouncyCastle.Crypto'. Is the assembly missing or incompatible with the current platform?
Reference validation can be disabled in the Plugin Inspector```
CONTEXT:
can't find any of these in C:\Program Files (x86)\Microsoft SDKs\NuGetPackages even though it seems they are installed in nuget in VS. also in VS there are issues, but in unity I get the above err and
I have tried to solve the missing MySQL.Data.dll in 2 ways. Through nuget, which wasn't recognized in namespace in Database.cs file, and by installing MySQLConnector and OBDC and copying a MySQL.Data.dll to Assets/Plugins which was recognized by both unity and VS..
ADDITIONAL ERRORS:
```Assembly 'Library/ScriptAssemblies/Assembly-CSharp-Editor.dll' will not be loaded due to errors:
Reference has errors 'Assembly-CSharp'.
and
Assembly 'Library/ScriptAssemblies/Assembly-CSharp.dll' will not be loaded due to errors:
Reference has errors 'MySql.Data'.```
or should I just try to connect to DB through python script? what an annoyingly difficult task this is.
Your message is really hard to read. It starts with an error and it's not even clear where the error ends and where the explanation of the issue is... Some proper explanation of what is going on is required: what happens, when happens, what causes ?
You can format errors with this
```
```
So it looks like this
Mah big error stuff
Is bad
Don't like
they are installed in nuget in VS
Unity doesn't use Nuget
it seems as though it does? I was able to target the unity project in VS by selecting a file in scope, then Project->Manage Nuget packages
It doesn't
Unity generates its own csproj files
Either use a package that makes it support it via an editor window https://github.com/GlitchEnzo/NuGetForUnity or install all the dependencies manually.
so, I manually satisfy the missing Google.Protobuf','K4os.Compression.LZ4.Streams','BouncyCastle.Crypto' and also put them in Assets/Plugins?
ooh, ill try
😖
I.. I think I got it. I had to install Nuget for Unity. Then I updated 'Google.Protobuf','K4os.Compression.LZ4.Streams','BouncyCastle.Crypto.dll'
And I changed the .Net target to .NET framework from Standard 2.1
and was getting another error for System.Text.Encoding.CodePages and updated that through NuGet.
Kinda silly to have old broken dependencies on a fresh install of newest LTS, and had to third party plugin manager
Is there anything else I should know as a Unity noob? (aside from Scriptable Objects, I got that one)
Kinda silly to have old broken dependencies on a fresh install of LTS
It's not a fresh install, you added a random DLL to the project without the dependencies
DB connectivity is not stock? Or is it just Azure
Most games don't use databases. You'd usually use a database for backend server, not necessarily based on unity engine.
so im not sure if this is the best place to ask this, but how do i change the "simple name" of an assembly file?
apparently i imported an assembly with the same name and im trying to keep both, so im opting to try to rename one and keep the other. but simply renaming the file doesn't change the fact that it's "simple name" is still the same.
Afaik, you don't. Why do you have two with the same name?
ah, 2 different unity packages uses the same name, but they're different versions so i wanted to keep them both and designate one as old
Is there not a way to just use the latest? What packages import the same assembly but different versions? Usually it'll just use the latest
I need a list<T> that only keeps the 10 latest items added to it. Does a collection like this exist for c# already?
something that works like this?
var list = new SomeTypeOfList<int>(3);
list.Add(33);
list.Add(71);
list.Add(22);
//after the following is called remove the oldest added value(in this case 33) from list and add 12 to the list
list.Add(12);
queue
The simplest way to do this may be by dequeueing the object at the front after a specified size is reached. This will maintain a queue of any size. int counter = 0; int size = 10;//size of queue if(counter < size){ //Enqueue counter += 1 } else{ //Enqueue //Dequeue }
that just constantly resizes past the size selected in instructor
Awesome. Funnily enough the last post is the best answer.
public class FixedQueue<T> : Queue<T>
{
private int threshold;
public void FixedEnqueue(T value)
{
if (Count >= threshold)
Dequeue();
Enqueue(value);
}
}
``` this is what i came up with and it appears to be working
To avoid using the wrong method by accident, you can completely replace it with your new method.
public class FixedQueue<T> : Queue<T>
{
private int threshold;
public new void Enqueue(T value)
{
if (Count >= threshold)
Dequeue();
base.Enqueue(value);
}
}
Also, I suppose you want to make a constructor that accepts a threshold parameter?
you'd probably want to make that Enqueue(value) to be base.Enqueue(value) or else it end up with infinite recursion
Totally.
Ah right, my mistake.
How do I assert for a Debug.LogError in a [Test]?
So im making a game but every possible collision detectiong tutorial i find dosent work i have rigid bodies, colliders and everything but nothing works, anyone know a way i cat get collision to work?
You'll have to show what you have for anyone to tell what you're doing wrong
post the code and screenshots of the inspectors of both objects
ok
void OnCollisionEnter(Collision col)
{
if (col.gameObject.name == "Player")
{
Debug.Log("It Worked");
}
}```
oh now ive seen what i've done
thankyou
what was it?
i had it on enter instead of stay
Does anyone know if there is a setting to hide/show these:
I have various projects that don't show them, and some that do. Others working in the project have them, but I don't
Maybe that's more of an editor question but I don't know where to ask or what terms to search for.
I like to double click these to open the script, or single click to locate in project. Impossible to do the latter now without typing a search
They could be using a custom inspector for the script on their system. Is it the same scripts that you're referring to that is not visible on there system?
There's no custom inspectors involved, for me it's every script in the entire project, for them, they're all there
And the panel isn't set to Debug mode i'm guessing.
I can see it the equivalent in debug mode, but not normal
If it's not Unity it may be a plugin, like Odin, but I've spent too long looking, and I don't know what it would be called
Is that how it looks on your side right?
Can you show a small snippet of how it looks?
Have you tried creating an empty project to make sure that everything is working fine in your version of unity?
Yeah this is all my side, the screenshots are from a personal project, I'll show one where it's not, 1 sec..
Hmm, that's a strange one. I'm not sure now, just thinking about it.
So every script you make for that projects, even an empty one, will look like that?
Yeah 💯
Does it happen in a new empty project?
Which would suggest there is something in the project that is causing this override.
Just checking
True, though we have ~24 projects that we're all in, I have the issue in all that I've recently opened
No 🤔
You mentioned Odin, are they using this package in the project? There could be some conflict somewhere. I'm assuming you are not the original creator right?
Could someone pls help me? Im trying to make player movement for an endless runner but i don't really know why my code doesn't work.
Yes Odin is in all of them, I'm not the original creator.
I thought the same there could be a clash. The ones blurred are part of our SDK, Odin is in one of those, it's the only editor plugin we use 🤔 I don't see anything else that would be causing it
I haven't used Odin personally. But does it affect new script that you create? if its not an Odin script? (Sorry i'm not sure on the setup of it).
Cracked it! It's odin. There's a setting in preferences. (Literally the very first one) However something is borked with my installation because that page of the preferences is blank
@halcyon radish ^ Thanks for your help!
huuh - @ tag fixed
i have a question and im not sure what i need to show to get help, i have a animation for run jump fall and idle, run and idle work just fine, i have a SetBool for IsJumping and i have code for it to be true on jump. issue is when i jump no animation but the weird thing is if i jump again before i hit the ground the animation will then play, so the jumping animation only works if i press jump two times
Very, very late reply but if you want to have the same functionality, you can use this. 
Used like this [Restrict(Restriction = typeof(IMyInterface))] public Monobehaviour _iMyInterface;.
Can't do IMyInterface as a field type, it won't show in the inspector, so ya have to cast it.
public IMyInterface I_MyInterface => (IMyInterface)_iMyInterface;
Awesome. Glad i could help.
What package is the [Restrict()] attribute from?
Oh that's really cool, thanks @loud wharf !
Literally on the attached cs file. 
Clicks expand and facepalms, sorry looked past it. Nifty!
I actually just copied this code off a yt tutorial, then added Exclusion and Attributes. 
Idk, might be handy. Maybe not. 
I've needed similar in the past and it was a custom attribute solution then, would be a nifty one to be a unity native
I ~really~ wish you could just make a field of type IWhatever that gets serialized as a UnityEngine.Object
Yeah i tried it whilst having that attribute, unity won't serialise it. 
just trust me, editor 😦

i swear i'll put the right thing in it
but yeah, that's not a half bad idea
the property smooths over the wrong type
Unity could just do interface fields as implicitly scriptable-objects/monobehaviour only but explicitly accepts any scripts that implements said interface.
Or maybe an attribute. 
🤷♀️
yeah
How do I change a tile based on it's neighbors?
Not talking about changing the sprite (this I know how to do), but changing this tile to another tile if all of the neighbors aren't this tile.
For example, if water tile is surrounded by 8 ground tiles, change this water tile to a ground tile
The solutions I find online only changes the sprite, which isn't what I want.
I didn't know where to ask this tho, I assume here because talking about scriptable tiles
hi, i want to make a curtain that simulated real life, and i am bit struggling where i could fold the curtain in realtime, anyone have a solution for that?
You could try unity cloth system. Or use an animation software to create an animation
i tried using cloth system but can i attached it to other game obj?, i only know that it could be interacted by assignt collider on what obj that can be interacted with
oh,and this will be used in VR
Cloth in VR is not a good idea.
Make an animation
i see, thanks for the suggestion
genuine question, why would cloth in vr be a bad idea?
im guess GPU is already pushing limits being vr and all, never worked with cloth stuff before. is it that bad?
if im not wrong cloths mainly use CPU to calculate physics
and VR basically just glorified android phone
for quest 2 at least
ah makes sense.
bit of a question regarding marking a game object as static
If i where to instantiate the gameObject that's marked as Static at runtime, would that still conserve the usefulness of static game objects?
asking because i've been working on a dungeoncrawler and the time to make the dungeon generation has come, i've been thinking about multiple ways to approach this and i think the best one would be having rooms as Prefabs and instantiating said rooms at start to build an explorable dungeon
however, i dont know exactly if this still allows said prefabs to leverage the ability of being static, considering i'm spawning the rooms on dungeon creation
if i do this prefab aproach i would ideally use or create some assets like this one on the asset store, but i'd still like to have some sort of feedback/ideas on how to tackle this issue in the best way possible
https://assetstore.unity.com/packages/3d/environments/dungeons/ultimate-low-poly-dungeon-143535
at least i know that i'd have to use bounding boxes to detemrine the sizes of rooms, thankfully i've already solved that issue by using the bounds.encapsulate method, pretty handy
From the unity docs: https://docs.unity3d.com/Manual/StaticObjects.html
if a GameObject
does not move at runtime, it is known as a static GameObject. if a GameObject moves at runtime, it is known as a dynamic GameObject.
Many systems in Unity can precompute information about static GameObjects in the Editor. Because the GameObjects do not move, the results of these calculations are still valid at runtime. This means that Unity can save on runtime calculations, and potentially improve performance.
i have a json file
which has some data in it,and i want to upload it into my c# script and put it inside a dictionary
what is the most straightforward method to do this
How does the JSON looks like? You might be able to do it in one line of code
{"Data":[{"Name":"name1","Job":"Job1"},{"Name":"name2","Job":"Job2"}]}
That would map to a class containing a List<T> more than a Dictionary, but that's still doable
and how would i really approach it
You need a class to contain individual { string Name, string Job } objects, and another class that stores a list of it (the outer object { List<TheClass> Data }
do i have to add [System.Serializable] over the classes ?
No
public class EmployeeInfo
{
public string Name;
public string Job;
}
public class EmployeeList
{
public EmployeeInfo[] Data;
}
something like this right ?
Yes
and use json.fileutility ?
JsonUtility.FromJson<EmployeeList>(str)
public TextAsset fileData;
public EmployeeList eL=new EmployeeList();
public class EmployeeInfo
{
public string Name;
public string Job;
}
public class EmployeeList
{
public EmployeeInfo[] Data;
}
private void Start()
{
eL = JsonUtility.FromJson<EmployeeList>(fileData.text);
}
good ?
Yes, but you don't need to do new EmployeeList() in the field initializer, as you'll be replacing it anyway when Start runs
got it
FromJson takes care of creating a new instance and filling it out for you
public TextAsset fileData;
public EmployeeList eL;
public class EmployeeInfo
{
public string Name;
public string Job;
}
public class EmployeeList
{
public EmployeeInfo[] Data;
}
private void Start()
{
eL = JsonUtility.FromJson<EmployeeList>(fileData.text);
Debug.Log(eL.Data.Length);
}
Error on line 21, you tried to access something on a null reference
Either el was null (deserialization failed totally) or .Data was null (failed partially)
this works if I use [System.Serializable]
I guess JsonUtility needs it to be serializable
I use the Far Superior™️ Newtonsoft.json
how to solve this error
More information in the stack trace, as always
i mean, yes, i did read the documentation, but i'mm still curious as to wether spawning the prefab and keeping it there constantly would mean its static or not
Select the log to see more information in a box below the console
Anyone know how I can structure a class to be the deserialized version of this json object?
{
"totalPages": 1,
"data": [
{
"lastUpdate": 1694187564809,
"targetName": "Black Box VR Global Feed",
"actors": [
{
"name": "qatest"
},
{
"name": "city_m"
},
{
"name": "deejed"
}
],
"actorsCount": 58,
"description": "qatest, city_m, deejed and 56 others posted in Black Box VR Global Feed"
}
]
}
dont cross post
{}=object
[]=array
so [{},{},{}...] array of some objects
and "key": value of this key, (the data type is implicitly stated here eg string is quoted, bounded by ")
eg the first field of this json will be
public int totalPages;//the value is 1 means it is an integer
Sorry about that guys, but selfishly so, I got help here and not there, so I'll delete it there.
This is what I had so far:
public class AmityNotificationPage
{
public class Data
{
public long lastUpdate;
public string targetType;
public string verb;
public string v_tarid_uid;
public bool hasRead;
public string imageUrl;
public string avatarCustomUrl;
public string targetName;
public Dictionary<string, string> actors;
public int actorsCount;
public string parentTargetId;
public string lastActionId;
public string lastActionSegmentNo;
public string targetId;
public string description;
}
public int totalPages;
public Data data;
}
so since [] = array, data should be an array?
But it has key and value pairs?
Ah so it's an array of <string, string> pairs
actors is not in form of a Dictionary<T, T> in the JSON yeah
It would be more of a class containing a single name field of type string
I'll simplify the original json I sent here cause once I know how to do 1 of them, I can do the rest
data would be a list of Data
notice how the json you posted above looks like this
data: [
{
}
]
The hard part is just how to structure data and then actors
True, since they both have the same [{}, {}, ...] form
List of type string?
No. List<Data>
List of string would be serialized as [ "a", "b", "c" ] so no
your Data class is mostly correct, except that actors is wrong
because actors should be a List<Actor>
Every time you see a [ ], that means you need a List of whatever you see inside the square brackets.
hmmm why can data have its own class, but actors doesnt need to.
is it cause actors has the same key for each entry ("name")?
Doesn't this imply there can be more than 1 data in this single object?
but you're right... that's exactly it, true
Indeed.
it just so happens we only have 1 here
One way to do this is to work from the inside out
start at the innermost object or array you can find
if it's an object, make up a new class for it
if it's an array, then remember you need a List<T> (where T is whatever's in the brackets)
public class AmityNotificationPage
{
public class Actor
{
public string name;
}
public class Data
{
public long lastUpdate;
public string targetType;
public string verb;
public string v_tarid_uid;
public bool hasRead;
public string imageUrl;
public string avatarCustomUrl;
public string targetName;
public List<Actor> actors;
public int actorsCount;
public string parentTargetId;
public string lastActionId;
public string lastActionSegmentNo;
public string targetId;
public string description;
}
public int totalPages;
public List<Data> data;
}
This look better?
so I might take these steps
{
"totalPages": 1,
"data": [
{
"lastUpdate": 1694187564809,
"targetName": "Black Box VR Global Feed",
"actors": [
Actor,
Actor,
Actor
],
"actorsCount": 58,
"description": "qatest, city_m, deejed and 56 others posted in Black Box VR Global Feed"
}
]
}
{
"totalPages": 1,
"data": [
Data
]
}
AmityNotificationPage
and then we're done
That's looking good.
oh I seeee. Makes it simpler to break it down
Thank you @heady iris and @simple egret
np!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using System.IO;
public class EmployeeB : MonoBehaviour
{
public TextAsset fileData;
public EmployeeList eL;
[System.Serializable]
public class EmployeeInfo
{
public string Name;
public int Wage;
public int Number;
}
[System.Serializable]
public class EmployeeList
{
public EmployeeInfo[] Data;
}
private void Awake()
{
}
void LoadDataFromJson()
{
eL = JsonUtility.FromJson<EmployeeList>(fileData.text);
}
void SaveDataToJson()
{
string j=JsonUtility.ToJson(eL);
File.WriteAllText(j,fileData.text);
}
public void BackButton()
{
LoadDataFromJson();
eL.Data[0].Number += 1;
SaveDataToJson();
}
private void Start()
{
}
}
here is my code
i can't seem to get the hang of writing the data into json file
please suggest me a better way to handle the json
Hello! First of all, you have to understand what parameters File.WriteAllText takes.
It takes path as its first and contents as second parameter. Both are strings.
so in your code I don't see where you are supposed to get a path to your file
you should probabaly create a method for this ?
public string GetPath() => $@"{Application.dataPath}/Your/Desired/Json/Location/fileName.json";
so you get a string from a class and write is using a path
This smol registercallback invokes a StackOverFlow Exception. Any idea "why"?
Oh let me send you updateRotationCallback too
!code, please
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Sure
public override VisualElement CreatePropertyGUI(SerializedProperty property)
{
// Create a new VisualElement to be the root of our inspector UI
VisualElement container = new();
// Load and clone a visual tree from UXML for next values
VisualTreeAsset visualTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/Scripts/Addressables/Editor/InstantiationParametersSerializableUXML.uxml");
visualTree.CloneTree(container);
// Get Properties
SerializedProperty rotProp = property.FindPropertyRelative("m_Rotation");
SerializedProperty rotHintProp = property.FindPropertyRelative("m_RotationHint");
// Bind Vector3 m_RotationHint property to Quaternion m_Rotation property with a callback
var rotationHintElement = container.Q("RotationHint");
// This is the callback causing the StackOverFlow
Action<Vector3> updateRotationCallback =
(value) =>
{
rotProp.quaternionValue = Quaternion.Euler(value);
property.serializedObject.ApplyModifiedProperties();
}
;
// Initialize Rotation for first time only
updateRotationCallback(rotHintProp.vector3Value);
// Update current Rotation based on m_RotationHint's VisualElement value on change
rotationHintElement.RegisterCallback<ChangeEvent<Vector3>>(
(evt) =>
{
updateRotationCallback(evt.newValue);
}
);
// Return the finished inspector UI
return container;
}
This works when you create the object of property drawer normally. But when you create an array of that object, it gets broken somehow.
I haven't ever worked with VisualElements, hope you don't mind if I try to help you
you trigger the same callback when you call updateRotationCallback and modify serialized property
so it leads to infinite while loop
What i first try is, putting property.serializedObject.Update(); which is aborts the unsaved properties and i got this error:
UnityEditor.RetainedMode:UpdateSchedulers ()```
Okey i am going to remove it
Gave me the same error 
I don't know if it's gonna work, but you can try to check if you're not modifying it right now
using mere bools
bool isUpdatingRot = false;
Action<Vector3> updateRotationCallback =
(value) =>
{
if (!isUpdatingRot)
{
isUpdatingRot = true;
rotProp.quaternionValue = Quaternion.Euler(value);
property.serializedObject.ApplyModifiedProperties();
isUpdatingRot = false;
}
};
perhaps you should try it
what if you check if they are not the same?
Action<Vector3> updateRotationCallback =
(value) =>
{
Quaternion newRot = Quaternion.Euler(value);
// Check if the new value is different from the existing one
// They may be the same and this can cause an infinite while loop
if (rotProp.quaternionValue != newRot)
{
rotProp.quaternionValue = newRot;
property.serializedObject.ApplyModifiedProperties();
}
};
Hm it does downgrade the exception to
UnityEditor.RetainedMode:UpdateSchedulers ()```
oh..
it probably existed before, but was not send due to stack overflow
google doesn't have this error
Yep people usually face this issue with unity's packages lmao
I think i need to recreate this one
To solve
I guess you have to make sure that all properties are set correctly
#↕️┃editor-extensions will probably be more helpful
@swift falcon also make sure that the path is correct
Ive been here for months but never saw this channel lmao
lol
can someone help me name my class? It just holds a few cancellation token sources and cancells them when needed. right now it's called AsyncApplicationCancellationManager but that's a bit unwieldy.
CancellationManager, TokenManager
AsyncHandles
I like that one
what is the best way to make a grid with 1x1 squares?
what sort of grid
to spawn my items
so I will drag them on that grid
I actually can do that via code
but it should be done with grid better?
what are you asking, how to create the ui, visuals, underlying structure?
is there are nice way to create a non-ui grid for GameObjects?
its just a 2d array + positions snapping
nested for loop probably:
for(float a = startPoint.x; a <= endPoint.x; a += spacing) {
for(float b = startPoint.y; b <= endPoint.y; b += spacing) {
// grid stuff
GameObject a = new();
a.transform.position = new Vector2(a, b);
}
}
for a vector3 just add another for loop.
oh, it's spawning gameobjects
oh, you're asking how to snap to a grid?
I instantiate different items on an empty area, those items are not saved in any list now, they are then saved in the json file (from Transform _environment)
yeah, probably ?
if that's possibly
point *= Mathf.Pow(PointDistance, -1);
point.x = Mathf.Round(point.x);
point.y = Mathf.Round(point.y);
point /= Mathf.Pow(PointDistance, -1);
this is what I use currently.
where PointDistance is your grid size
class Slot
{
public GameObject value;
public Vector3 position;
}
Slot[,] grid;
bool TryPlace(GameObject obj, Vector3 at)
{
Slot slot = grid[(int)at.x, (int)at.z];
if(slot.value != null)
return false;
slot.value = obj;
obj.transform.position = slot.position;
return true;
}
I do the inverse power to get the denominator of the fraction that the decimal represents (essentially. Not actually what's happening but easier to understand). So if I make my grid size 0.25, it would correctly snap to 4 positions along a 1 unit line. If I did not do the inverse pow like i'm doing I would have to make my grid size 4 to snap to 4 positions per unit, which is a bit conter intuitive imo.
I see, so there is no smth like build-in way to build a custom grid
but why do you have to pow it..?
no but that's easy enough, it snaps a position to a point.
I explain here @gray mural
you could drop the pow, but then when you set your grid size it's a bit counter-intuitive. A grid size of 4 would not be 4 unity units per grid unit, it would be 4 grid units per unity unit. (if I don't pow it) If I do pow it, a grid size of 4 would be 4 unity units per grid unit.
grid snapping exists in the editor but it is for non runtime
I hope that makes sense, it's a bit confusing to explain.
it's quite confusing for me as well
let me draw something rq lmao
I actually don't want to make a fixed size for it
I just want to to drag my items in grid
no there is no fixed size for my method. It just rounds the object's position to a point in space.
so it's probably just manipulations with an item using mouse position
I see, and will the object be in the middle of the mouse this way?
if you use mouse position, it will be the position from which you derive object position
mouse moves freely, object snaps
oh, yeah, that makes sense
should be some offset
I will just have to make it snap just when the mouse is inside the 1x1
initial click to object position, which is then added to current mouse position, from which you get the snapped position
i think we already had this discussion before
you can also lerp the object pos for juice 🙂
Each black square is a unity square unit. The left is with the gid's size powed to -1. The right is if it's not.
So if I put a grid size of 0.5 without powing it, the right is what I'd get. With powing it, the left is what I'd get.
If I put a grid size of 2 without powing it, the left is what I'd get. With powing it, the right is what I'd get.
I think. May be wrong on the right side one, but the left side one is correct. I hope this gets the point across.
i think i use this for snapping/
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float RoundTo(float value, float to)
{
return Mathf.Round(value / to) * to;
}```
i think it works, so far
that's what I do too, but for me it's easier to think that for example 0.5 grid size is a point every 0.5 units instead of a point every like 2 units or whatever it would be. So instead of passing in 2 as to, I would pass in 0.5 as to and then pow it with -1 (which gives 2)
so I may be wrong, but using that formula, if I have (5, 5) vector, it will give me (6, 6)
yeah it works
public static Vector3 RoundTo(Vector3 value, float to)
{
return new Vector3(
RoundTo(value.x, to),
RoundTo(value.y, to),
RoundTo(value.z, to));
}
oh, hold on, the size isn't 2 this way..
it depends on what your grid size/spacing is. If your grid size is 6 with my formula, then yes (I'm pretty sure at least. Not good at quick maths.).
but why do we have to use grid size if it fully depends on it?
we can just round it actually?
I think we can just round it without using grid size?
no
What [MethodImpl(MethodImplOptions.AggressiveInlining)] does there?
you cannot pass a float to round towards in the round function.
instructs compiler to attempt to inline this AGRESSIVELY 😡
@ashen yoke ik what it does but I was gonna ask why you thought it was needed?
because those things tend to be hotpaths
im happily trading exe size over performance on hotpaths
just round all floats like .cache did?
most of my utils have this flag
maybe I don't understand something
he posted his own code for the RoundTo function
according to the docs "Unnecessary use of this attribute can reduce performance. The attribute might cause implementation limits to be encountered that will result in slower generated code."
yes.
yes, may, can
but it looks cool ?
but tests i did shown massive gains, generally
as I said. It's easier for me to imagine a grid as spacing. So if my grid spacing is 0.25, I want my objects to be placed every 0.25 units, not ever 4 units.
oh.. that's what you mean...
because the whole round(number / to) * to moves towards smaller rounding increments the larger to is.
but it's very strange ?
if you have 100x100 grid
you want to make small blocks .01x.01 ?
or by grid spacing you mean space between objects?
I guess I explained it badly, my apologies. yes.
not the size of objects?
I guess I am just too dumb to understand it
because here, as to gets larger, it rounds to smaller increments.
anyways @ashen yoke why not AggressiveOptimization then? or did you test it?
I see, it probably will be possible to do with spaces, but it's not needed, because I don't want any spacings
did you use it?
no. I just trust the compiler to be smart enough.
did you use AgressiveInlining?
no
so I will try to round my mouse position and add a little offset if needed tomorrow, thank you both for your help ;D appreciate that
its just that AggressiveOptimization is not available on 4.8
oh really?
well all it does is skip T0 compilation and does not do regular JIT on it.
ill check it out when we move to unity version supporting new features
I wonder how many references/calls a method needs before [MethodImpl(MethodImplOptions.AggressiveInlining)] improves performance. I have 5 references but one is in a loop. I tried it but it did not change anything.
how are you testing it?
I'm logging the time and subtracting the time for my existing code already. I just added that to two methods and it didn't change the time it took.
about the JIT and trusting it, you know of the intrinsics initiative? core clr and so on, when it went open source and the amount of optimizations skyrocketed?
no i don't know of that
well the jit is open source, people improve it all the time for years
problem for us is that this started after 4.8
when unity will finally introduce updated new .net i will have to relearn everything
i mean, is that in vs standalone project, which .net, if its unity, release mode or not
build or editor
i would think it would effect the timing even a little even not in release mode?
Why?
thats how .net apps work afaik, a flag is set for compiler optimizations to be enabled or not
in debug mode they are not enabled
does unity run it in debug mode? I don't have debug mode enabled.
yes its by default in debug build mode
editor itself
same as a new project in vs
defaults to debug build with pdb and disabled optimizations
what is the debug mode for unity then
its .net terminology, unity uses it
and by default it's off so the optimization should affect it, no?
open properties, see the build modes, see that release has optimizations enabled, debug doesnt
anyways, I tested it in a build. It's like .2 ms faster so i guess I'll keep it.
yes, editor by default runs with disabled optimizations, builds have them enabled
release mode will compile assemblies as if it was a build, with all optimizations enabled
its still not indicative of build performance, but its closer
I thought I've been in release mode cus it's the bug crossed out.
yes you were, didnt notice
I usually just stay in release mode unless I have errors leading me to the wrong lines, which can sometimes happen in release mode...
especially with the damn burst compiler lol
just thought more about it, im basing my intuition about inline on the struct based ecs i did shortly after unity announced its own, and there inline in some cases improved performance x10 and more, mostly with granular small methods on hotpaths
i observed actual massive gains, and since barely anything changed since then in unity's .net im still relying on those observations
oh and unity seems to agree
?
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public uint3x4(uint3 c0, uint3 c1, uint3 c2, uint3 c3)
{
this.c0 = c0;
this.c1 = c1;
this.c2 = c2;
this.c3 = c3;
}
ah lol
all of Unity.Mathematics is covered by it
yea, hotpaths make sense for aggressive inlining.
I also have a question about assemblies. Is it just an organizational choice to split your project up?
depends
if you have setup the asmb hierarchy properly you can save up on compile time, generally assemblies are treated as the main player in .net, everything is designed around it having a public and internal sides
does json files not work in android build ?
hows it speed it up?
unity takes away direct work with assemblies, linking them, chaining projects, with closest thing being asdefs
ah so the correct way to do it is to chain it one-way?
thats the only way to do it, afaik from out of unity experience
does it give you an error if you try to reference an essembly that is referenced by the assembly you're trying to reference?
yep
ah
also reminds me of a project I want to try. I want to make a c++ DLL with some stuff in it and call it in unity. Wonder if it'd make my pathfinding faster... I'd have to manage the threads myself tho...
I want to enable and disable those UI object(red line right side), on a certain animation keyframe. How do I do that?
this button I believe. It can let you trigger script execution on certain frames. So you can disable it without it being a child.
ahh I see
if you make a script disable it you can use this method
you can do it without event if you make a script that relays state on Enable/Disable
Got it it works now!
sounds dirty, but events are dirty to me themselves, how they are implemented
unity anim events in particular
lol
i mean..
lets find why animations broke, simple maintenance task - go through all animations and compare the strings in events to the method name
i use animancer and custom events
is that a custom animator?
never seen this before
mine just has a dropdown of methods to select once I add it to an object.
better than whatever that is
You guys ever feel guilty playing video games ever since u started making video games?
Now i get guilty knowing I oculd be making a game instead of playing it
ive seen that too sec
Ahh, so its when u click on an animation object vs when you dont
You get the dropdown version when you select the animation event while focused on an object in the scene (or prefab) that has your Animator attached
Else you get the generic "enter anything" version
if u click on the object(right) directly, u get that
this
that i never seen before, thanks
still, profoundly flawed approach in large projects
maintenance hell
idk, never had it break on me and I've been in a few large projects.
just don't ever rename the method haha
I posted this the other day in #🏃┃animation but I have a feeling this problem is going to require a more… custom solution
I'm trying to record a specific texture and audio while in the production game, not in the editor, but I can't find a great tool for the job. Unity Recorder only works in the editor and is a non-option, sadly.
Right now I'm using Spout2 with OBS for the texture along with a window recorder also in OBS for the audio, but it has quality and desync issues that I'm trying to avoid, plus it's just an overall complex way of doing things.
Does anyone have any recommendations or ideas on how I could record all of this?
quick question: I have a simple script that I attach to lamps from a prefab pack to change their material (from non-emissive to emissive). Is there a way to have defaults through the editor for every prefab that uses the script? (to avoid manually setting the on/off material on numerous lamp prefabs)
Yep select the script from the project window and set the script defaults
I tried that but I get this, and after assining the materials here the prefabs still don't have it by default 😦
You get what?
Yes
That's expected
Isn't that what you are doing
Adding this script to objects in edit mode?
hmm, is the expected behavior that prefabs that have this script will have those materials by default?
The expected behavior is that if you attach the script to an object in the editor after setting the defaults, the references will be set
If you attached it before setting the defaults, nothing will happen
No
would it be more performant to iterate through more small tilemaps, or less big tilemaps?
trying to decide how big each chunk of tiles should be for my sandbox game
It depends on the game.
Usually, you want to have as few as "unused" tile activated.
With the least amount of chunk
so as few active tilemaps as possible in the project?
So, if you have a game that use large amount of tile, larger chunks make more sense.
Both. Tile maps and tile
The ideal scenario, is 1 tilemap that contains all the used tile and no non used tiles.
is it mainly just as few active tiles as possible or do tilemaps themselves have a considerable computational cost by existing?
Without even knowing the cost of tilemaps, the only fact that you have more than necessary should be enough to you to know that you want to reduce them.
However, that being said, it is if you strives to have the best performance.
In most case, you can just profile and see for yourself.
Sometimes, inefficient method are not enough inefficient to matter.
I ask because the idea I had was for each chunk to be its own tilemap, then a 2D list/array storing the tiledata for that chunk
Yeah, and you want the least amount of tilemap with the least amount of useless tiles.
It is a multiconstraint problem that varies on the type of game you are doing and the actual cost of having useless tile vs having more tilemaps
what does iteration imply
accessing the type of each tile to see what, if anything, should be done with it
Dont you want to have the tile to actual make that decision instead of iterating on every tiles to ask them ?
tiles in a tilemap cant store unique data though
Perhaps have each chunk saved as a hashset?
What do you mean, you definitly can instantiate a gameobject or C# object that represent each tile.
arent tilemaps storing gameobjects more computationally expensive on account of the gameobjects running individual code?
Instead of operating on the tilemap, use it only as a renderer
Yes and no, if most of your tile does nothing, then you lose less time than iterating on all tiles and only updating a few.
Why do you need to loop them anyway? I read through everything, maybe i missed something
accessing the type of each tile to see what, if anything, should be done with it
for instance a sand tile shouldnt hover midair, it should start falling
so when checking a sand tile it should then check surrounding tiles to see if they are air, if so, spawn a fallingsand gameobject
Yeah, and it makes more sense for the sand tile to do that than somebody else.
I plan to have upwards of roughly 6400 tiles on screen
Personally, I think you are way better off using a C# representation of your game and only using the tilemap as renderer and initializer.
if you want to do that then maybe store it as a hashset and iterate through that as a 2D array and that would probably be quickest. You dont need to constantly loop, you can just signal whenever something happens to update that chunk.
the tilemap basically is doing that as it stands, like I said I plan to store the tiles data on the tilemap gameobject inside of a list/array
like each chunk would just simply store the min x/y and max x/y, and a hashset for the state of all the tiles. Then you would just update the tilemap visually
Yeah, then, do not iterate the tiles, but the array.
(And only those that needs to be updated)
so only reference the tile when it comes to creation or deletion
example usecase?
im sorry im half afk
reading
sand tile
@ashen yoke
that does not imply full iteration
to become mid air the tile state has to change
a change in state is an event
or it started midair for some reason
if you want it to constantly be updating your best bet imo is to multithread it, otherwise you should use events
if a sand tile has adjacent tiles it would just be skipped, same applies to the logic of any dynamic tile
Usually sandbox games to my knowledge use different threads in some capacity to update the world
It is Unity, you going to be highly limited.
Also, this can be done further down the line if needed.
I disagree
80*80?
Unity can multithread but when you do that the syntax of practically everything changes and you are forced to use the DOTS system to some level
You cannot do any call to any Unity API. (except a few)
Then don’t call unity API
Unfortunatly, when you are doing a Unity game, you kinda need to call Unity function.
it's side view, like Terraria
pixel art?
constantly check if the chunk needs to be updated. If it does, notify the main thread and it would update it. That way you offload the checking loop to a different thread and the main loop can focus on rendering and other game logic.
hard alpha?
yes
Doesn’t require and unity API calls to do this @steady moat
draw tiles on the shader
one atlas per layer
256 tiles per atlas
to control you update pixel in the control tex
Sure. I'm not saying it is impossible, I'm saying that you have a lot of restriction which means that your gain are limited.
this will provide the best control/performance
for changes in the chunk you dont need to iterate everything, you need to collect modified tiles, and the batch process them
one modified tile = 9 tiles added to processing queue
if tile was added, ignore it, very fast
Simply not true. Not constantly looping through active chunks would be a significant help. Additionally it could control what chunks are active based on the player position if the player constantly copies its position to a readonly public value.
whole thing screams Job system
I only dont use job system bc it wont let you use managed objects
and i like my queues and stacks
there is no NativeStack either.
Pretty sure Tertle's repo (bovine labs or whatever) has that, you can ask them in the dots channel if you want
the reason using the DOTS system is a problem for me is because last time I tried to use it I ran into the issue that it's an unfinished feature, and thus not fully functional
cant do everything gameobjects do
I could make my own implementation tbh i just dont think the job system would give me much more performance over my current system, which I use for pathfinding.
Don’t use DOTS (which is “released”), use jobs
That's by design
DOTS is a whole set of packages
Jobs, collections, and burst all function as they are designed, with limitations to get maximum speed
also dots is just… complicated (imo) for how you’re suppose to code things
using only the job system on the other hand, much more doable. And you can burst it too since it already wont let you use managed objects.
the job system is a part of DOTS. Do you mean Entities/ECS when you say complicated coding?
Either way, you can multithread however you want, most of Unity's API can't be used in it, Jobs+Native Collections+Burst is really really fast if you're up for getting your data prepared correctly
Yes, it's Jobs/Burst/Collections/Entities/Entities packages in one big pile
Yea
i mean burst can get a bit complicated to program for me since I’m not used to or experienced with pointers, but ecs is just weird to me bc it’s data oriented not object oriented, with a separation of systems components and entities. At least in. Jobs/burst i can still pretend there’s objects.
You don't generally need to do anything with Burst apart from putting the [BurstCompile] attribute on a job that doesn't use anything managed
Anything pointers is just additional and irrelevant to getting most things done
There’s some more stuff that’s needed, for example you must use native arrays or references to read stuff from a job, wont let you just read a float from the job.
Yes, and you don't have to deal with pointers directly, you just allocate a native collection type, pass it in, write to it in the job, read from it when it's done, and dispose of it.
How? It always wants you to use a native array/reference or a pointer to pass things around or for primitives pass by ref. I wouldnt say irrelevant
Ah yes, but it’s still a pointer under the hood and it helps to think of it as one, at least for me.
I don't; it's just a struct with a reference to the backing array in it. Sure it uses pointers but you don't have to even know that