#archived-code-general
1 messages · Page 445 of 1
like if there is some actual technical reason you need a public field over a public property
In 15 years of Unity development - I have never come across a need to have a public field
Not that there won't be a use , just, you can pretty much easily never use them
how have you never thought "dang i wish i could edit this serialized field outside this component!"
Good use case: Adding a temporary debug value you can watch in the inspector in such a way it'll stand out so you know to remove it later
how does it stand out? I use [ShowNativeProperty] from naughty attributes for this purpose.
because that's what properties are for? 😄
[SerializeField] private SomeType someField;
public float someFloat;
[SerializeField] private SomeType someField2;
Makes it stand out in code. though I'd never do that
Hey i like properties and use em a lot but some things can just be a field
If there's some additional code to changing the field (eg: checking for null, or clamping, etc), I want that done in one place and not everywhere I change the field. Regardless of whether or not it needs it now, it might change and require it in the future.. keeping away from public fields and using properties/ methods controls that and removes/ lessens the possibility of future tech debt
It's also how my first job taught me in their code standards
actually this is a good topic for me, what is the difference between property and field?
or maybe what are they exactly
It mainly depends on preferences. Someone can equally say "I like fields a lot but prefer to have all of my public members be properties".
field = your class variables
property = getter/setter
its trivial to update a field to a property in c# (if there is no risk of loosing a serialized value)
ahhh ok i see
a property makes a getter and setter function around a field for you
the shorthand to do a getter for something like private int level is public int _level => level right?
public int Level => _level;
Properties are simply getter/setter methods in c# that behave like fields (variables).
Properties should start with a capital
I like being verbose and showing the setter ;p
i see i see, alrighty thanks
public int MyCoolInt {get; private set;}
(also most of my code right now uses the same level notation for public and private fields lol..)
-# camelCase?
yep
theres the whole argument of doing it the proper way from the beginning, follow this architecture, never do X because of Y, decouple everything. In game dev specifically, a lot of these things really don't matter. Sometimes you can be pretty sure that you wont need to change to a property. Truthfully i hate seeing a bunch of properties in my code "just incase"
Usually it would be PascalCase for public things and camelCase for private/protected. Or you can do m_ if you are stuck in the 80s like unity 🤮
wasn't it _camelCase for privates?
I don't add a property unless it's needed, who'd add code like that just in case? 😄
You could look up naming conventions in c# and practice a standard. It'll help you to be able to identify code written by others better, implicitly.
Unless you maintain a public library there isnt an important reason to use properties to start
@safe flame the single most important thing in regards to styling is to stay consistent
The more practical reasons to prefer properties over fields are that:
- Properties can have different visibilities for getter and setter.
- Property getter and setter can have logic.
- Interfaces can have properties but not fields. If you ever need to make an interface to encapsulate something, you would never need to refactor anything if you default to properties.
do people really unscore their private variables outside of python languages
js, yeah
oh yeah i have two other teammates, and one teammate uses camelCase for functions, the other PascalCase
i try to follow what my IDE suggests, though i have ignored _camelCase for privates for the whole project
js is cus there is no access restructions
__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
ah no that's just facebook
the same reason you'd do it for a public library is why you (people in general) would for a private.. your audience is just future you
I meant it more like using a property rather than a public field just incase you have to change the logic. Or purely to adhere to "best practices". I still use properties for the most part anyways but I do find it annoying at times
I've noticed ides nowadays will actually try to hide those variables even if there isn't normally access prevention
Old school C devs but I don't believe they (those individuals) are common on this server.
you guys know the thing about 2 people arguing and then a third person coming in with a really different one that unites the first two people against the third
uhhh so what do y'all think about this
member style/groups are as follows:
- static fields
- serialized fields & props (
public)- own components (no access modifier, assigned on awake)
- convenience values (no access modifier, computed on awake/start, don't change)
- containers (no access modifier, initialized immediately, can be mutated)
- state variables (
private, often modified)- convenience properties (no access modifier)
- exposed properties (
public)- inner types
- unity messages (no access modifier)
- inputsystem messages (
protected)- intercomponent messages/methods (
public)- coroutines (
private)
member naming: fields and props arecamelCase, methods arePascalCase, no prefixes are used for fields/props
i mean.. i stay internally consistent lol
indeed and I know best for me 😄
Gotcha .. can't say I've ever had that feeling :p
anyway, snakecase is objectively the base (BEST, but also based) naming convention for variables because you can be verbose as much as possible and not feel bad
rust user alert
Wish I was way more consistent though.. got some code I'm re-using and for some reason I used _varName but everywhere else just varName ¯_(ツ)_/¯
hungarian notation
why, like, introduce punctuation in your words though
because-why-not?
Anarchy mode. Roll a d20 before writing any variable and consult a chart to see which standard to apply to this one
i have a dartboard for that
private bool __m_b_myBool; 🤡 🔫
d20 isn't enough, gotta do 2 and consult a 20x20 matrix
private bool bool_-m_MyBool.bool
this is unironically very close how most IDs are written in my job (not game dev)
pain
ancient rules from the 90s when ides were shit
Bee Movie notation.
public bool accordingtoallknownlawsofaviation;
public int thereisnowayabeeshouldbeabletofly;
Go try to use openssl or any old c lib and then you will understand how bad names can be https://docs.openssl.org/1.1.1/man3/PEM_read_bio_PrivateKey/
How should I save each object and their position? I'm using a save/load system with a json file and I want to save every object in the scene + their position
is there a specific part you're struggling with here? make a list, each element representing the objects ID and position. save that
Yea, each of them has their own script with its own values and I'm not sure what to do abt that
Store them too
Its gonna be hard but I will try
If its just an object without any extra data to restore, you just need some ID to find its prefab later
If it has extra data, same thing but save this extra data too (e.g. health)
Math question: I need to interpolate a height of a 2D spot between its four corners.
Like, I have the height at four points, call em 0,0, 0, 1, 1, 0, and 1, 1. I have a height at each of these four coordinates. Now, if I wanted the height at, say, 0.35, 0.7, how would I lerp that value on both axes? Basically, how can I find the height of an arbitrary point on a theoretical quad given the positions of its vertices?
My first thought is "Average the heights of the X lerp and Y lerp:
(Lerp(height[0,0], height[0,1], x) * Lerp(height[0,0], height[1,0])) / 2
But that feels... incorrect. Am I overthinking it?
I'm pretty sure that only works if X and Y are equal
Wait, no, it doesn't work for any distance, I'm picturing a quad in my head, a quad that's angled down from it's highest point at 0,0, looking for the height at 0.5, 0.5, those two lerps will both be higher than the point I want to actually check
So an average wouldn't do
Graphic because it's also helping me think this through. There's not actually a quad or I could just do some raycast shenanigans or something, I'm working off of pure math here
I think quad is tricky because it can be folded two different ways, (midpart) it's not truly averaged if two opposite vertices higher or lower. Probably point on the triangle should be calculated.
If it were a mesh made of triangles it'd be one thing, but what I'm actually dealing with is a 2D array of floats representing the heights of a surface in a grid pattern. I'm trying to get the height of an arbitrary point that is between those array indices
My first thought is this is just bilinear interpolation
This has a solution for an interpolation https://math.stackexchange.com/questions/3349939/calculate-the-height-z-coordinate-of-a-point-on-a-flat-quadrilateral-plane
But I think it could be split into triangles to simplify.
[Checking wikipedia]
Okay, that does seem like what I need.
Please tell me there's a Mathf function or something I can use for this 
Looks more complicated than it is when you write it all down like that. Bilinear interpolation is just three Mathf.Lerps. First, lerp between the top corners of the quad by the X. Then the bottom corners by the X. Then lerp between those two values using the Y.
For a grid of multiple quads, you find the 4 corners the point is within and calculate the normalized position within that quad and do the same.
Three lerps! That's the special sauce I was missing! I didn't think of three lerps
Yeah, I got all the math for that already, I have the corners and have InverseLerped between them to get the value between each, I just didn't know what to do from there
I had to double check, I don't often do bilinear interpolation manually. I just remembered having the same aha! moment. Bilinear interpolation is a combination of linear interpolations and trilinear interpolation is a combination of bilinear.
Hi, I'm trying to make a Joystick manually and I want to get a sprite to be rendered and updated real time as you move the stick so it looks like the base of a joystick Idk how to explain. I've tried creating a mesh but I just don't get how to update it in real time so it reshapes itself as I move the stick
Maybe a rookie doubt but I'm having a hard time with this thing. Does anyone have a good approach to constantly reshape polygons as the game runs?
What do you mean by reshape? If you're working with sprites then you'd probably want different frames for each direction
That would be a good approach but I currently have it set-up so you can move it to literally any direction so it's not just like 16 directions
Like a mobile game joystick
Well, your choice of 16 different sprite frames, or one mesh where you tilt towards the direction
bonus: make the mesh in blender then prebake it into 16 different sprite frames
is there a way to recalculate the mesh shape each frame? I was thinking on that more than switching between sprites depending on the position of the stick
A mesh/sprite that just looks right when rotated around the centre sounds ideal
oh god, that's true
just making like a cone sticking to a circle would do the trick
you dont need to reshape anything. Just rotate/tilt the mesh
Wrote the drawers script but still doesn't work and I'm not sure how to use it
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Can Someone Help me fix a bug in my game?
If you want fixing your bug I suggest you explain in detail what the issue is and possible share any errors you encounter. Above all, share the !code.
https://dontasktoask.com/
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
nullreferenceexception object reference not set to an instance of an object
so i was making a tower Defense game and everything works fine, but after i press the retry button that loads the same scene my enemy object stops moving and going to the waypoint location. the error is in my enemy movement code that takes an array of waypoints(positions) and then orders the enemy object to start moving towards it. but i don't know why the array is null after i reload the scene and i don't know how to fix it.
im new to unity.
is there a prettier way of doing this?
private void Start()
{
if (transform.childCount > 0)
{
Transform child = transform.GetChild(0);
string parentName = gameObject.name;
Match match = Regex.Match(parentName, @"\((\d+)\)");
if (match.Success)
{
string number = match.Groups[1].Value;
string newName = $"Arrow ({number})";
if (child.name != newName)
{
child.name = newName;
}
}
}
}```
For starters you can revert the if statements and make them into guard clauses
if (transform.childCount)
return;
Performance wise, put the Regex in a class-scoped variable and make sure to make it a compiled regex. There is an option for that if you make the regex
not to stackoverflow you but just curious, why are you doing this
For this we will definitely need your code so we can determine what the issue is. Also, please make a full screenshot of your console as it will contain a stacktrace where your code failed.
See the bot message for sharing code
The stacktrace should show the file paths of your code and what method/operation it did on what line. This is a very important detail
i have a ton of objects that i want to easily find by name from the hierarchy. renaming each of them manually would take so long
the snip is at runtime but if this is just like a editor tooling thing its super easy to have something like this in a menuitem where performance doesnt matter as much
yeah i thought that i might as well add an execute always attribute to make my life easier
Thank you. From the stacktrace you see it fails at EnemyMovement line 16
So this bit
yeah
see the bot message for sharing !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Now generally Update is called AFTER Start is called, but there are some exceptions
To begin, could you change your Start method to Awake?
One possible issue is Target might not be set when you use it
The second issue could be that Waypoints.points[0] results in a nullvalue
do you have a the Waypoint thing set up
transform is always set so this will not be null
Once this is done, and the exceptions till appears, the next thing to do would be debugging the incoming data
yeah it works the problem is after i reload the scene
are they in different scenes or something? what's your setup here exactly?
what exceptions?
just one scene and it works fine but after i press the retry button that loads the same scene it stops working
What happens if you log the result of Waypoints.points.Length inside your Start method?
And also, log the result of Waypoints.points[0]
https://unity.huh.how/debugging/logging/how-to
ok so the static field is referring to objects that have been deleted after reloading the scene
wait it should delete and reawaken Waypoints too
unless it's DDOL...?
what's the first error you see in console?
scroll all the way up
is it the same one, or does it perhaps point to somewhere else instead?
Execution order might vary if objects are disabled
Start won't be run after Update for a given component instance though?
i dont think so
ok sounds like your waypoints array was empty
which meant target wasn't getting set, since it errored before that
check your set up, do you actually have children in the object that has Waypoints?
If object X is disabled it will run its start method after object Y's update method
oh yeah but was this not in the context of the same object?
Alright so waypoints is empty
I suggest you do the logging I told you about
In this case I'd also log the child count specifically in your waypoints method
See if it has any. I assume it either doesn't log, or it logs zero
No, didn't say it was
why'd you bring that up then lol
i did
I assume this is the first log before you reloaded?
yeah
yes and after the reload is just errors
Do these waypoints even exist on a reload?
yes
So it doesn't log on the reload meaning it keeps the old objects int he static array
One thing you can do is get rid of the static context and make it a singleton, but ideally it just gets called again
What happends if you change the log to Debug.Log("message", this); and press it when it shows. Where is your waypoints object?
The object should have its Awake method called when it initializes, which is what it would do on a reload. In your case this does not appear to happen judging by the single log message
i try the Debug.Log("message", this); and it loged but its the same output
Just for clarification, this log message appeared once, and not twice in any way, right?
Oh, but here there are two now?
So it does run?
the second one is after the reload
@autumn flicker how exactly are you achieving the reload?
just SceneManager.Loading the same scene?
What is EnemyMovement.cs line 13? Did you change the code?
It does not point to anything from your previous screenshot
I assume it's the first index of your waypoints still?
i added a debug.log
Your second Debug.Log still points to the same location with the waypoints when you click it?
It seems like in the case of a reload it does not fill the array anymore because it has no children
And in turn Target remains null
But now the question is why it would no longer have them on a reload, suggesting the way points might be loaded at a later stage?
How are those waypoints added?
No I mean the actual game object instances in the hierarchy
You could also just suffer from some sort of race condition in that case
These are prefabs though. You have these added through the designer?
Then we can rule it out at least
the pink dots are the waypoints
if the waypoints are in the scene their awake will always fire before any enemymovement start fires?
The waypoints have no behaviour as far as I know
The parent game object collects them, then it will tell the enemy where to go
So far this all makes sense, I just don't see why it would break on a reload
same
Perhaps its time to use a debugger
what's in the DDOL
just to be clear, the first log is the only log during the first playthrough, and rest are after the scene reload?
yes
i don't know what a DDOL is im new to unity
the DontDestroyOnLoad part
you've marked some stuff as DontDestroyOnLoad, so just to make sure, you haven't put anything that relies on waypoints in there?
nothing its just the debug updater
I'd take Rob's advice and look into learning how to use the debugger
I think there's not much else to do here because it's likely there might be an issue that fixes itself before you even notice, but the code is invalid at that point
what scenario can actually trigger an outside index error on an array at index 0?
i thought it would be throwing a null ref on the array
wasnt aware an array could exist with no indicies?
The array has a size of 0, so index 0 is out of bounds
ah
And in turn, Target remains null and will always throw a null ref
So we initially started there, but the issue is the empty array
But hey, we learn debugging which is always good
well more specifically accessing at 0 throwing the error was what i was curious about but yeah
yeah i know but i don't know how to use a debugger because im new to this stuff so i preferred to ask people to help me out. Anyway, thank you guys.
so i logged each waypoint when its adding to the array and its adding them to the array after the reload so the array its not empty
try logging points.GetHashCode() in Waypoints.Awake and EnemyMovement.Start
see if they're consistent once you reload the scene
What you should do is use a debugger and put breakpoints where the exceptions are happening to investigate more. You can also put a breakpoint where the array is filled to make sure it is happens correctly on scene reload.
VS code has a debugger you can use with unity as long as you have the unity vs code extension + set vs code as the editor in unity.
the selected one is last hash code before the reload
put it outside the loop, have it run only once
then add the similar log (to Waypoints.points) in the other Start method, the one that's erroring
i did and the selected log is the last log before the reload and its from the start method log, but after the reload only the awake method logs and we don get the start method log.
why do you have so many logs
do you have multiple Waypoints components?
yes
24 waypoints
and the awake method logs them all
but the start method only logs one
you shouldn't
..you have Waypoints on each of your waypoints, don't you
Waypoints should only be on the container for the waypoints
otherwise you're just overwriting the static array when it loads for the children
each one has the waypoints script
yeah see above
it workeeeeeeeeeeeeed!
you were right
only the parent object that hold the waypoint should have the script
not every one of them
thank you alot
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
I am confused
How did this even work in the first place then
Also, how did they not all log a message if they have the script? You only had a single log and they didn't collapse
So many questions
Also because when I said to add this to the parameter and click it, it would've gone to the parent game object
Anyway, glad it's fixed
I even don’t know how it worked I followed a tutorial and it created it like this and it worked. The main question is why it worked at the start of the scene but not at the reload
Thank you man
I Appreciate that
Indeed, pretty funny it would work there
Exactly
Thats the thing that confused me
not sure the best place to put this but we are using I2 for localization and it works fine EXCEPT we have some key values such as 75% and on import it seems to be converting this to a value 0.75 etc can we stop this?
Hey is it possible to utilize system level actions in unity?
could you elaborate on what you're referring to
Basically making a project for school stuff atm, I need to essentially implement stuff like how inscryption is able to read through your hard drives. Or just ways generally to interact with the system like being able to create textfiles on your desktop or shutting down a PC through the game
oh, syscalls?
but uhh shutting down the entire pc i think could constitute as malware so maybe don't lol
yeah you generally dont want to mess with peoples systems like that, can you do it? yes
a little googling seems to indicate that you can use normal c# fs apis (System.IO) except on browser where there isn't an fs
Well good thing this isn't a general situation then
I dont intend on being malicious with system stuff its for school research for my bachleors
Not a project meant to be distributed through like steam or something like that though im still gonna look at the terms n agreement for unity tho
Thanks anyhow
yeah no worries but you can do it fine, you can access anything you need via win32 api and even some in build unity functionality
i don't think you'd need to go directly to win apis, just use the .net interfaces
Although if you do decide to go through win APIs, a cool one ive discovered is that you can set the name of the application when its in windowed mode, helpful in multiplayer
anyone please ? 🙂 ☝️
maybe try #↕️┃editor-extensions
alright
I am having a bit of confusion about mathf.smoothdamp, and why it is at all framerate dependant in my setup in-game (VRChat world, which uses unity).
- I have a test script to simply move a cube from y=0 to 1. Run in Update(). Using unity default (time.deltaTime).
- the parameters are all typical initially:
current value=0
target value=1
currentVelocity=0
smoothTime=0.1
maxSpeed=default (mathf.infinity)
deltaTime= default (time.deltatime) - My understanding is, mathametically, the overall duration to reach say 0.95 should be similar or equivalent for different framerates. Becuase the actual movement curve is the same, just the steps are different in different framerate.
- I asked GPT (I know, dont trust AI etc) to make a calculator to check the overall time to reach 0.95. It generated a code that runs the unity smoothdamp and measures the time it takes. I ran the code seperately and it seems to confirm, the times are about the same.
Time to reach 95% of the target at 15 FPS: 0.2667 seconds
Time to reach 95% of the target at 30 FPS: 0.2667 seconds
Time to reach 95% of the target at 60 FPS: 0.2500 seconds
Time to reach 95% of the target at 120 FPS: 0.2417 seconds
- However my in-game measurements (using similar method, by comparing the starting time, and the time it reached say 95%) are like this:
15 FPS, ~466 ms
30 FPS, ~666 ms
60 FPS, ~1100 ms
90 FPS, ~1567 ms
120 FPS, ~1.9 seconds
which is a whole lot of difference and cannot be explained simply by step size resolution.
Moreover, in VRChat you can press esc to open a menu which will lower your FPS for maybe a few frames. I can visibly "speed up" the cube movement by pressing esc therefore lowering the FPS for a few frames.
showing your actual code might help
oh this maybe difficult because it is done in VRChat's udon graph
how does udon graph handle ref parameters?
interestingly, it does not, i have to leave the nodes unplugged to get it to work, i assume this is handled in the background
you are talking currentVelocity correct?
yep
would the currentVelocity not being updated create such effect? i mean visually it seems to be damping just fine
absolutely yes
i mean i don't think it would be working at all though if it wasn't handling the velocity properly
How would I go about getting rid of seams between different meshes?
I think Im supposed to recalculate the normals by hand so they take in account the vertices of neighboring meshes but im not sure how to do this with a noisy sphere
You should share your mesh generation code
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Here's my attempt at implementing manual normals calculation(it didn't work)
https://scriptbin.xyz/wokozetoza.cs
So does the sphere consist of 6 parts?
I just calculated normals by normalizing the difference between the vertex and the center of the sphere
no I added the ability to subdivide the cube-sphere further.
so it depends
How did it look when you tried RecalculateNormals?
Are you even sure that it's a normals issue and not a vertex color issue?
Oh you aren't using vertex colors
In that case maybe a UV issue
If I use the built in function, the shadows are fine for the most part but there are visible seams between meshes. By using my handmade approach, the seams are gone but now the shadows are pretty messed up
the shadows are just lacking
What renderpipeline are you using
URP
Let me see
this is the lighting with "lighting with normal maps"
there's a visible seam, altho im not sure if thats what im supposed to do
meanwhile my implantation creates terrible shadows
Does your mesh have duplicate vertices at the seams?
I'd recommend to rework it so that the vertices are shared. Then RecalculateNormals should produce smooth normals at the seams
How would that work?
should there?
The normals are calculated per-vertex from the neighbors of the vertex. If your mesh has disconnected parts (like at the seams here), these seams will appear
You can try using something like a Dictionary<Vector3, int> to check for duplicates. The vector is the vertex position, the int is the index of the vertex at that position
It seems like the meshes are sharing vertices but lemme check
alright.
Hm I don't think there are duplicates.
Let me try to see if I can fix that.
You don't want duplicates. You want shared vertices at the seams
There are no memes here, thanks.
Any help please with propertydrawer 😬 👉 #↕️┃editor-extensions message ? I really don't understand these, they look complex
I just found out about the "GameplayMessageSystem" but I cannot see it in the plugins list, was this nuked/renamed etc?
what is that?
nothing shows up relevant to unity..
you lost from /unreal ?
haha yeah wrong channel 😄
Hi! How do I restart the game? Like completely in the exact state as if I launched build again or clicked play in editor. I tried simple scene one, but I saw massive amount of unassigned things out of nowhere and non reseted variables. Any workaround?
Ofc finding every single variable and setting it to what it should be is out of the question lol
if a scene is reloaded then it will load fresh (as in create new game objects with new components.
Existing class/struct instances and static vars wont be affected
we don't support modding here #📖┃code-of-conduct
oh okay my bad 😢
though it seems like you just might be getting different amounts of random values
also UnityEngine.Random is shared across everything, so maybe consider System.Random for a localized deterministic thing
but it all gets called in one function so nothing should be able to interfere?
welp i wont pry any further, my bad didnt know about the modding thing
the reason modding discussion isn't allowed here is partly for legal reasons and partly because modding covers some topics that aren't relevant to general unity development
but i skimmed your question and it doesn't seem particularly bound to modding, so maybe try booting up an empty "test" project (to eliminate the modding aspect, in the sense that it doesn't have an effect on the behaviour), and if you can replicate the behaviour there, you could ask about that
im not sure if that would count as rule evasion, so.. if a mod smites the convo don't be surprised i guess lol
sure i guess ill boot up unity
just gonna make a cool shuffle function rq ^-^
Yes, i get that, I just want to completely restart the game, and maybe run a function to skip the menu. Like if I closed the app and opened it
Then do that, unload or go back to some intro scene to unload everything so you can load it again
Im not following. Reloading scene 1 won't work, but loading scene 0 then scene 1 will?
just made it in a test and it works fine in there 😔
void Start()
{
Random.InitState(2);
List<int> list1 = new List<int>() { 1, 3, 12 };
List<int> list2 = new List<int>() { 1, 3, 12, 10, 100, 5 };
Shuffle<int>(list1);
Shuffle<int>(list2);
print("list 1:");
foreach (int i in list1)
{
print(i);
}
print("list 2:");
foreach (int i in list2)
{
print(i);
}
}
void Shuffle<T>(List<T> list)
{
for (int i = 0; i < list.Count; i++)
{
Swap<T>(list, i, Random.Range(0, list.Count));
}
}
void Swap<T>( IList<T> list, int i, int j)
{
T val = list[j];
T val2 = list[i];
T val3 = (list[i] = val);
val3 = (list[j] = val2);
}
this i think is about the same and it just works
now im super confused
what's with the val3 lol
If you use additive scene loading you can remove and re load the scene. Otherwise you need to load into some other scene to then load back to the first.
Remember that stuff in DontDestroyOnLoad is kept always
idk its in the swap method so i just included it
that's built-in?
its swap is a list extension that the game adds
yes
definitely not perfect
So it didn't work as I went from scene 1 to loading scene 1, but it should work when I would go from scene 1 to 2, and from 2 to 1
Tbh i dont know what unity will do if you single load into the same scene as you have loaded already
(fyi, swap only needs 1 extra variable
void Swap<T>(IList<T> list, int i, int j) {
T temp = list[i];
list[i] = list[j];
list[j] = temp;
}
```)
I had a lot of nulls and other problems, suddenly 50 critical warnings
well if you're seeing different behaviour in 2 scenarios, identify what's different lol
xor swap would like a word
that only works when you have access to the underlying bits; this is the general case
When I looked in inspector half of the things were unassigned
i am xD only thing i see is that repo takes one of the lists from a dictionary and the other thing is that repo has classes in the lists
but i dont see how itd make a difference
since im not looking at the list from dictionary
but a different one
xor swap still needs an extra variable
void Swap<T>(IList<T> list, int i, int j) {
list[i] ^= list[j];
sanity--;
list[j] ^= list[i];
sanity--;
list[i] ^= list[j];
sanity--;
}
Huh isnt there one where you can use 0 extra vars?
...are you cloning it? because if not, then it is the list from the dictionary
probably doesnt work in c# though
-# yes, xor swap. i made a joke
xor swap only works when you can actually xor the underlying data, which is accessible in c# fixed-width integral types
You can just do the tuple swap (a, b) = (b, a);.
Ha im slow
yea in c/cpp or using unsafe in other langs
it shuffles a list from the dictionary, then it shuffles the other list
if it shuffles the 2nd list before shuffling the list from dict it gives consistent shuffles (of the 2nd list)across multiple tries otherwise it doesnt
-# so apparently "cs type" gives results about caesarian section types
maybe like.. copy over the code you used that had the initial issue to begin with?
^^?
yeah but what you just showed doesn't seem very close to the structure you had originally
make dummy dicts and stuff
ill redo every class in there then ig
you don't have to replicate the entire project structure
just the parts relevant to this
at least keep the original flows you tested
i found it out but thanks for the help :) for some reason the count of the first list was going up by 3 after each reload of my save, which it shouldnt. every time i reset the game and loaded it the count stayed the same
Let's say I have a collection of Sprites that represent the elements in Unity. I want his collection to be used across many GameObjects. How should I set this up?
ScriptableObjects?
sounds about right
If I have a lot of collections of types of things (Textures, Materials, Sprites, Colors etc), should I also just SO them?
I tend to, depends on what kinda workflow you end up prefering
In a work project we basically just have this (an SO) and some functions on it to grab what we want from ids and such. It's nice and simple tbh.
what does it contain, just sprites?
what are the Ids? Ints or strings?
Contains whatever we want to access in various places. Prefabs, sprites, settings, etc. And we just have a static class with some constant ids for things like items, otherwise we can always just search with a string (such as a prefab name).
Why Unity's IPointerDownHandler interface event giving a 6 digit and different pointer id in eventdata.pointerID. it used to give touch Id like 0, 1 before Unity 6. It broke my game!
Could be a bug. Or maybe the event data is just not initialized or something
How to initialize it? It works when pointer is down on the UI raycast
I really hope it is bug
Well, where are you seeing it producing the weird numbers? Can you share the relevant code?
I just debug on event callback eventData.pointerID.
Whenever I click on the UI where the script is placed. It gives me different pointer id every time like
3562651
3562652
It used to give 0 when only 1 finger is there
And when 2 it give 1
And so on
It also seems that the implementation is dependent on the input system
There's no connection with this interface and input system
It works on my unity 2022 project
The same script produces different pointer id in unity 6
There is. It ultimately gets triggered by the input system/manager
And in unity 6 I think the input system is set to be active by default
Yes
Maybe try switching to input manager and see if that affects the pointer id
Why it's needed to me.
I made a touch area for mobile users where they can move cinemachine camera
The touch area is a ui
And I need finger ids to make sure the touch on UI will move the camera and not the touch outside ui
Sure
Then you'll probably need to figure out where these ids are coming from. Perhaps they're defined somewhere in the input system.
Yeah, I'll see
Thanks a lot for your time @cosmic rain
Excuse me I need help
I have a scene and there is an input field, a code must be written in order to play the game.
The thing is that the code is generated in a html website
how do I connect Unity to my website?
A web request
Sorry
is there a resource for best practices for pixel perfect 2d collisions? preferably with rule tiles? I'm apparently doing something weird.
with walls, yes
yo, for some reason when i bake, its not showing me what i baked? any ideas? i am using navmesh surface
and also i am tryna make a cube follow it, for some reason it isnt,'
This does not seem like a #archived-code-general question
beginner?, i mean i already sent
mb
Yea
since i didn't get an answer ill ask again, is there a resource for best practices on detecting overlap for collisions?
I'm not sure if there really are resources exactly
The documentation tells you pretty much what's there to know
Sanity check please. Anchor's parent is container, so essentially giving the view object the same parent, then assigning the same position and rotation.
Works fine the first time this is displayed, second time the view prints (0, 0) and the anchor prints (the real non zero X, 0)
Something does mess with the parent's scale but it should still work fine afaik
var view = ObjectPool.Instance.Take<BasicSpellView>();
view.RectTransform.SetParent(container);
view.transform.localScale = Vector3.one;
view.transform.SetPositionAndRotation(anchor.position, anchor.rotation);
print(view.RectTransform.anchoredPosition);
print(anchor.GetComponent<RectTransform>().anchoredPosition);
guys how do i make a mesh that looks something like this?
the big dot is a city, the small dots are vertices, the blue part is the mesh/triangles
most tutorials just tell you how to make a square with it
@olive ridge same as you'd make any mesh but there's a default import setting that trims loose verts, you have to turn it off if you want to keep them
Are you asking how to generate it with code?
pretty sure you cant generate it any other way right?
You can make meshes in a 3D modeling program. People come here with non-code questions all the time so that's why I'm asking
oh no i want to make it with code
What would the mesh be used for?
as i want it to be a map game so the territory around cities would be dynamic
just showing the territory around a city (big dot)
Delaunay triangulation might be useful if you want to turn a bunch of points into a triangulated mesh
And/or voronoi diagrams
that thing you can get on github?
Those are just algorithms, but yeah there are implementations on github
oh
I have used this https://github.com/nol1fe/delaunator-sharp
well how do i do it?
are there tutorials?
Yes
could u send?
also whats the setting?
I feel like that advice was more for premade meshes, not generated ones?
oh
(Which prompted me to clarify that you are generating it)
I want to get the number of frames or just the time left in an animation clip with the animator, is this possible?
except I've used overlap circle and its not working. clearly I'm too stupid for this
Post your detection code
public int FrameNumber;
public uint SeedState;
public ReplayFrameFighter[] Fighters;
public ReplayFrame(int _frameNumber, uint _seedState, int _fighter_count, BaseFighter[] _fighters) {
FrameNumber = _frameNumber;
SeedState = _seedState;
Fighters = new ReplayFrameFighter[_fighter_count];
var n = 0;
for (var i=0;i<_fighters.Length;i++) {
if (_fighters[i] == null) continue;
Fighters[n] = new ReplayFrameFighter(i, _fighters[i].input.inputs[0]);
n++;
if (n >= _fighter_count) break;
}
}
}```
hey im getting a gc.alloc in the `ReplayFrame` constructor. obviously to do with the array, but is there not anyway to just have a fixed array in a struct without generating garbage?
ReplayFrameFighter is a struct if that matters
well arrays are ref types if that's what you're asking?
You're creating a new array. That's the memory allocation. The contents of the array are irrelevant
also clearly it's not a fixed array because you're initializing it based on _fighter_count
new ReplayFrameFighter will also create garbage here if ReplayFrameFighter is a class
You can use Span<> + stackalloc to allocate an array on the stack to avoid heap gc in a function.
https://paste.mod.gg/dvgmgkkoeacz/0 last time i did the guy was just freaking out i had a RB in there and wasn't listening when i said 'ya i think its a problem with colCheck'
A tool for sharing your source code with the world!
I was interested what it took to get an array to be allocated inside a struct and from what I can tell, its unsafe only 😦
public unsafe struct MyStruct
{
fixed int span[5];
}
poo poo c#
sphereOverlap might me a way to check collisions
looks like you're likely to be creating a lot of arrays of the same size here so might see some benefit from pooling the arrays rather than allocating new ones per call, depending on how frequent this is
fyi, you don't need n here at all
you can just use i
also, do you really need this? could you perhaps add a properties to BaseFighter that give it similar capabilities to ReplayFrameFighter?
that way you could just use the same array in a different way, rather than making a new one
You could use ArrayPool instead. https://learn.microsoft.com/en-us/dotnet/api/system.buffers.arraypool-1?view=net-9.0
yo I'm figuring out non mouse UI navigation, how when a new peice of UI to move the selection to that
like for existing Ui at the start of a scene I can use the first selected think in the event system but i dont know how to make that work with seperate UIs, like say the options menu or pause menu
make your code select an element in the menu when the menu opens
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed;
public float rotationSpeed;
private Rigidbody rb;
private float moveInput;
private float rotationInput;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
// Inverted vertical input so W = forward
moveInput = -Input.GetAxis("Vertical");
// Left/right rotation input (A/D or Left/Right)
rotationInput = Input.GetAxis("Horizontal");
}
void FixedUpdate()
{
// Move forward/backward
Vector3 move = transform.forward * moveInput * moveSpeed * Time.fixedDeltaTime;
rb.MovePosition(rb.position + move);
// Rotate left/right
float rotation = rotationInput * rotationSpeed * Time.fixedDeltaTime;
Quaternion turn = Quaternion.Euler(0f, rotation, 0f);
rb.MoveRotation(rb.rotation * turn);
}
}
i hace a problem. When using the S and D forward, it acts ok, but when i face the error which the right is left and righht is lwft. How can i fix it? (it is for a tank)
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
its very easy, copy the code, paste it on the site hit save and send link..
a powerful website for storing and sharing text and code snippets. completely free and open source.
does it work?
yes
are you able to help me?
it is the sript of making a tank respond to w a s d commands
it partially does
but backwards takes a as d and d as a
are you talking about rotation ? why not just put -
now they are entirely switched, even when i drive forward
what could be the source of problem
idk check the gizmos of the object is correct
..lovely you cropped one of the important parts
entire
- its still in global mode.
- MovePosition is meant to be used with a kinematic rb
also this should belong in #💻┃code-beginner if even a code problem at all..
i am a code beginner but checking is kinematic fixed it. Thanks
well, not entirely
anyone know how to fix this it happens when i enter playmode and move my mouse i have a code that makes the camera and character follow the mouse but its not working -_- im trying to get my guy to turn left in right in a first person view but the camera and person is messing up
do you mean overlap CIRCLE? because yes i use that. i still pass though the walls only going up still
k is there an up to date top down dungeon tutorial for unity 6? i feel like i should go shoot myself since i cant seem to figure out this basic fucking problem
i see like coding wise how? do i get the event is there a "selected UI" variable or the like in the event viewer i just set or a function or?
In whatever function you use that opens the menu
Or in OnEnable in a script on the menu
i figrued it out was just looking for eventSystem.SetSelectedGameObject
so do you people not use rule tiles because they break collisions? or is there other reasons why you should never use rule tiles?
Hard to help without seeing your code
Using MoveRotation in Update is a no-no
also multiplying Time.deltaTime into mouse input - another no-no
And if you plan to move this into FixedUpdate - reading mouse input there would also be bad
you need to read and accumulate the mouse input in Update, then apply/consume it in FixedUpdate
ok thank you i will fix it
It's also not totally clear what this is actually for - first person controller?
yeah fps shooter
then don't use moveRotation
just do rb.rotation *= Quaternion.Euler(0, mouseX, 0);
and get rid of Time.deltaTime
and you'll be good
(no FixedUpdate)
ok will do this was really helpful thank you.
wait so would something like this work?
using UnityEngine;
public class MouseLook : MonoBehaviour
{
public float sensitivity = 2f;
public Transform cameraHolder;
public Rigidbody playerRigidbody;
float xRotation = 0f;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * sensitivity;
float mouseY = Input.GetAxis("Mouse Y") * sensitivity;
// Vertical camera movement
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
cameraHolder.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
// Horizontal body rotation
playerRigidbody.rotation *= Quaternion.Euler(0f, mouseX, 0f);
}
}
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
what?
read the bot message
ok
format the code correctly for others
Hey, I'm trying to animate a position from point A to point B using an AnimationCurve, how would that be possible?
yo, question, i use playmaker, how i can made a bubble for make some asset invisible when my character go on back of them ? thx ! 🙂
or when we don't see the player
make a curve that goes from 0 to 1 in whatever way you wish. Then use the Evaluate function output on the animation curve as the input to Lerp
e.g.
public AnimationCurve myCurve;
public Transform start;
public Transform end;
public float duration = 1f;
float timer;
void Update() {
timer += Time.deltaTime;
timer %= duration; // make it loop, just for demonstration purpsoses
float t = myCurve.Evaluate(timer / duration);
Vector3 position = Vector3.Lerp(start.position, end.position, t);
transform.position = position;
}```
Would obviously need to profile it to get contextual answer but just curious, There’s a notable amount of overhead in the act of instantiating something right? Like if I instantiated a prefab that had 8 other prefabs as children that’s gonna be lighter than if i instantiated the first prefab than instantiate each child prefab?
most likely that's the case
I think I read that in reverse, I meant my assumption would be its heavier doing more objects all at once than spanned over time @night harness
ofc also depends what's on those children / prefab in term of components
oh interesting, im guessing that might depend on the scale in question though right? I'm talking like pretty small overall (eg. imagine an enemy spawning with 3-4 prefabs under it). where i'd imagine maybe there would be more overhead in sending the instansiation requests 4 times rather than just once but i guess it's fairly hard to guess
imagine you have 8 Start methods running at once doing work , big hitch
probably, yes.
Nav has a point but it's more about spreading the work out over multiple frames vs there being less work overall
"notable" is going to be subjective though
fair. I guess in the context of what I was asking about doesn't help though (which i didn't provide so my bad on that, early in the morning aha). Doing fairly vague prototyping of how I want to handle code architecture for generic content in various prototypes and weighing up various solutions to problems i'm running into
In this case I'm thinking about how I kind of want the root of any content prefab to be kinda a BehaviourController/EntityManager with the different types of behaviours (eg. hurtable, interactable, valuable, movable etc.) as children of the parent whether that's literal or just logical rather than just having those behaviours be the main prefab script so i can mix inheritence and composition and all that
but there's a lot I gotta consider when implementing that kinda thing in how everything talks together, what the prefab setup would look like, what the scriptableobject would look like etc. etc.
so just messing around with stuff
how much work each component does plays a huge part in it as well
yeah forsure. im happy thinking about all this when it comes to items, player, enemies etc. but then my mind panics thinking about how much work i'd be adding to projectiles that die in half a second 😭
I know those should really have just a different solution altogether but i enjoy the idea of having everything managed the same way
anything you're going to reuse don't forget about Pooling , oh and polling can be other things besides gameobjects too
really does help recycling what you already allocated rather than cleanup , re allocate cleanup and repeat
if you have a serialized base/poco class stored on a prefab there's nothing in the scope of the class itself that is able to tell when it's been created right? since the constructor is run when the prefab asset was made?
What's your use case?
You might be able to use https://docs.unity3d.com/ScriptReference/ISerializationCallbackReceiver.html
the constructor will be called on your serialized POCO just... maybe not when you think it will be
I wanted the equivalent to an awake call in my poco class
I wanted certain logic classes in my monobehaviour that initialized by themselves to certain extents, more-so curious if it's possible than any ironed out vision
it's fine if the answer is just no
It just... depends on what kind of initialization we're talking about
that's why I'm probing
if you mean like "I want to do something right after the serialized fields are assigned by the serializer", then the link I posted above is for you.
nah i mean like runtime game logic typa stuff
this is for runtime
I just honestly did not consider those run at runtime
even though yeah that makes sense huh
hi! i just wanted a bit of advise, i have some bugs and i wanted some help, do i ask here or on the beginner one? (i know its dumb)
If you're a beginner, then #💻┃code-beginner
thx
Hello, I have a code that works for 3 of 4 of my players, but not my 4th player for some reason. Even with the code being the same it just won't assign anything keepint player4Choice void
void BypassSelection()
{
Debug.Log($"BypassSelection: Player 4 choice is {player4Choice}"); // Add this debug log to verify assignment
player1Choice = "1";
player1FeedbackText.text = "P1 selected: 1 (Testing Mode)";
HighlightSelectedButton(player1Buttons, "1");
DisableButtons(player1Buttons);
player2Choice = "2";
player2FeedbackText.text = "P2 selected: 2 (Testing Mode)";
HighlightSelectedButton(player2Buttons, "2");
DisableButtons(player2Buttons);
Debug.LogError("Testing mode: Player 3 choice is set to 5.");
player3Choice = "5";
player3FeedbackText.text = "P3 selected: 3 (Testing Mode)";
//HighlightSelectedButton(player3Buttons, "3");
//DisableButtons(player3Buttons);
player4Choice = "6";
player4FeedbackText.text = "P4 selected: 4 (Testing Mode)";
HighlightSelectedButton(player4Buttons, "4");
DisableButtons(player4Buttons);
whenever you have variables that have numbers like this, it's going to be better to use arrays or lists instead.
Likely you made some kind of copy/paste or typing error somewhere in your code
those errors can be eliminated when you just use arrays and loops instead of duplicating code N times.
anyway this code doesn't make much sense to me, so it's hard to say what's going wrong. It's not clear what this code is supposed to do.
Is serialization synchronous? as in if X object runs OnBeforeSerialize will it's OnAfterSerialize always run before any other objects OnBeforeSerialize will run?
It could be. It could be not. This is probably something you shouldn't rely on.
Work performed in these callbacks must be done with care, as the Unity serializer runs on a different thread from most of the Unity API. It's recommended to process only fields that are directly owned by the object, to keep the processing burden as low as possible.
https://docs.unity3d.com/6000.1/Documentation/ScriptReference/ISerializationCallbackReceiver.html
We can't say for sure if it's just one thread or a pool of threads and there's no guarantee it would stay the same in the future.
Yeah 🤔
Was playing with something like this to allow for a prefab to reference itself as an asset rather than it's own instance
public class PrefabBehaviour : MonoBehaviour, ISerializationCallbackReceiver
{
private static PrefabBehaviour _serializationTemp;
[field: SerializeField] public PrefabBehaviour Self { get; private set; }
void ISerializationCallbackReceiver.OnBeforeSerialize()
{
_serializationTemp = Self;
}
void ISerializationCallbackReceiver.OnAfterDeserialize()
{
if (Self != null && _serializationTemp != null)
{
Self = _serializationTemp;
_serializationTemp = null;
}
}
}
I noticed this in the serialization guide
Unity runs the same serialization code in a different variant to report which other UnityEngine.Objects it references. It checks all referenced UnityEngine.Objects to determine if they’re part of the data Unity instantiates. If the reference points to something external, such as a Texture, Unity keeps that reference as it is. If the reference points to something internal, such as a child GameObject, Unity patches the reference to the corresponding copy.
and realised in theory you could use these callbacks to quickly chuck the reference out of the patchers eyesight and slide it back in after the fact
Feels a bit unstable to me. What's the purpose of this?
Why not just hold references to the prefabs in, say, other prefab or an SO?
Def giving osha violation vibes, just testing the waters abit
Potentially has some nice benefits when dealing with networking for specific reasons that im forgetting but i remember I was looking for a way to do this
I think it was due to how it could help manage the order of execution of content spawning because without multiplayer i'd tend to just spawn a prefab via reference on a so then give the instance the so so it knows what data to care about, but in networking as a client I can't directly get a reference to the object i requested to spawn because that's an rpc that has to travel to everyone? something like that
would be cool to reliably do in general just for the sake of doing it though
Well, just don't instantiate objects via an rpc. Make a proxy method that handles the instantiation and initialization on the client.
There are probably many good ways to go about it without relying on the approach with serialization that you brought up(there are probably other issues with it).
Probably
To be honest I think there's an aspect to it where I just don't like that I can't do it 😛
That's something you just have to accept when working with third party close sourced engines.
You have to accept the rules of the game.
Or go and write your own engine/modify an open source one.
we'll see i guess 😄
In Unity Localization, how do you add a list as argument?
{0:list:{typeName}: {fromValue} -> {toValue}|\n}
Right now I am trying to make item description from these.
Example description:
Damage: 5 -> 7
Agility: 3 -> 5
Defense: 1 -> 2
I see you use transform to move your collider(https://paste.mod.gg/dvgmgkkoeacz/0) , you should probably use moveposition (https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Rigidbody.MovePosition.html) and definitely check what type of collision detection you are using (Discrete/continuous etc) , as teh default collision is good for basic stuff, not so much when things get a bit more complicated
A tool for sharing your source code with the world!
le issue: it seems that whenever i move circles it seems that theyre too stupid to realise that their target circle's position also changes relative to them and ends up causing what you see in the video, how do i fix it?
the relevant code for it is this
{
List<Vector3> points = new List<Vector3>();
float circumferenceProgressPerStep = (float)1/sides;
float TAU = 2*Mathf.PI;
float radianProgressPerStep = circumferenceProgressPerStep*TAU;
for (int currentStep = 0; currentStep < sides; currentStep++)
{
float currentRadian = radianProgressPerStep * currentStep;
GameObject dot = Instantiate(spawnDot, new Vector3(Mathf.Cos(currentRadian), Mathf.Sin(currentRadian), 0) * radius, Quaternion.identity);
Vector2 Dpos = dot.transform.position;
Vector2 Tpos = targetCity1.transform.position;
anotherfuckingscript targetScript = targetCity1.GetComponent<anotherfuckingscript>();
float distanceFromTarget = Vector2.Distance(Dpos,Tpos);
if(distanceFromTarget < targetScript.radius)
{
float angle = Mathf.Atan2(Tpos.y - Dpos.y, Tpos.x - Dpos.x) * Mathf.Rad2Deg;
dot.transform.rotation = Quaternion.Euler(0,0,angle);
float distanceFromRadiusEdge = Mathf.Abs(distanceFromTarget - targetScript.radius);
dot.transform.Translate(-distanceFromRadiusEdge/2f, 0f, 0f, Space.Self);
}
points.Add(dot.transform.position);
Destroy(dot);
}
return points;
} ```
what's the expected behaviour? that the unmoved circle stays the same?
no, that the moved circle properly recognises where target circle is and deforms properly
you're leaving out quite a bit of context here
what would "deforming properly" be? which is the target?
ok, so i decided to see where the said vertices spawn and it seems they dont move with the circle
you ever played agario? you seen how the circles deform whenever theyre close to one another? i want roughly that to happen
so the unmoved circle is deforming correctly, but the one you're moving should also deform in a similar way?
ok yeah you dont know what i want
yeah im not psychic lol
is getCircumferencePoints the function that generates the circle? check where it's being called from
Im trying to make procedural terrain and its working fine when i have no falloff but if i do then the X axis works fine and the chunks for it line up but the Y(Z) axis has massive gaps between the seams and i cant seem to figure out why that is. i can provide more code if needed but i think its an error in this code here somewhere.
float[,] heightFinalValues = new float[width, height];
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
float noiseSum = 0;
float maxPossibleVal = 0;
for (int k = 0; k < heightMapSettings.noiseLayers.Length; k++)
{
noiseSum += noiseLayers[k, x, y] * heightMapSettings.noiseLayers[k].strength;
maxPossibleVal += heightMapSettings.noiseLayers[k].strength;
}
int chunkSizeInVerts = meshSettings.numVertsPerLine;
// Adjust based on chunk's world position (coord)
int chunkOffsetX = (int)(coord.x * (chunkSizeInVerts - 1));
int chunkOffsetY = (int)(coord.y * (chunkSizeInVerts - 1));
// Falloff map's center
int halfFalloffMapSizeX = fullFalloffMap.GetLength(0) / 2;
int halfFalloffMapSizeY = fullFalloffMap.GetLength(1) / 2;
// Calculate global indices with offsets
int globalX = x + chunkOffsetX + halfFalloffMapSizeX;
int globalY = y + chunkOffsetY + halfFalloffMapSizeY;
// Clamp to avoid out-of-bounds access
globalX = Mathf.Clamp(globalX, 0, fullFalloffMap.GetLength(0) - 1);
globalY = Mathf.Clamp(globalY, 0, fullFalloffMap.GetLength(1) - 1);
float falloff = fullFalloffMap[globalX, globalY];
float baseHeight = heightCurve_threadsafe.Evaluate(noiseSum / maxPossibleVal) * heightMapSettings.heightMultiplier;
heightFinalValues[x, y] = baseHeight * falloff;
if (heightFinalValues[x, y] > maxValue)
{
maxValue = heightFinalValues[x, y];
}
if (heightFinalValues[x, y] < minValue)
{
minValue = heightFinalValues[x, y];
}
}
}
return new HeightMap(heightFinalValues, minValue, maxValue);
heres an image of the issue
What am I missing here?
I am trying to draw a line (using linerenderer) in the inverse direction of the touch position, which in and of itself works, but as the video shows for some reason I can only draw it from the world origin if I want the linerenderer to stay "flat"(so no banking) , or draw it from the right position but getting back that annoying rotation stuff.
The code is in the video and here as well:
https://pastebin.com/TpiUuVwF
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.
looks like you're accumulating a small offset in the Z axis while iterating
im using unity 2D and i dont get what i did wrong here, stafield not even showing up in the front no matter what i did
i've tried for almost 2d now and dont understand why it isnt showing up
not a code issue
hmmm, weird that its doing it for the Z and not the X, ive checked pretty much everywhere and it calculates it the same way
there is probably just a tiny mistake in that generator code
i would check all + operations
what is the proper channel for help for what i need
alr thanks
Hi! I have a silly question, I use the fbx exporter to export my various Unity assets to FBX. However, when I select my 400 assets and export them all at once, they will all be in a single .fbx file. My question is: can I export them all at once, but have them all be independent (one .fbx per asset, as if I were exporting them individually)?
I've coded a Python program to automate some mesh modifications on Blender and I need them to be individual .fbx. Thanks 😉
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
you can make yourself a script that exports them individually
The unity glfast package is better and will keep objects seperate by default when exporting game objects as GLB
https://docs.unity3d.com/Packages/com.unity.cloud.gltfast@6.12/manual/index.html
but you wont have an FBX 😕
if its just to edit in blender and then re export i dont see a problem
Mmmh, I'll have to see, because if the scale ratio isn't the same as for the FBX exporter, it'll bother me a bit, but I'll just have to adjust my .py script. I'll test it.
Thanks, I just wanted to know if it was already planned 😉
well do whats best for you, its another option
Hi I'm trying to create a wall jump mechanic but i think I'm going about it the wrong way? Here is my code:
@quartz sun Vector2.left is (-1, 0), Vector2.up is (0, 1)
By multiplying the vectors, ur scaling 1 vector's components by the other.
x => -1 * 0 = 0,
y => 0 * 1 = 0
result (0 ,0)
and then it doesn't matter what you scale the vector with
The player movement is better now but there is the issue now with the updated code I added which makes the jump very rigid
So when youre applying an impulse, you dont scale with the delta in time. It's not a continuously applied force, it's a response to an action that should be consistent across all occurrences of that action.
Here, even scaled by the dt(and it shouldn't be) the impulse is still very large. You need to reason about the final value of that impulse and how it'll affect your movement.
getting this error when dragging in gridview
I'm trying to make this building area but my current method of collision detection is pretty dumb. I'm just drawing a ray from the camera to the cursor and setting the position of whatever object I'm holding to the intersection between the ray and other objects
And that's leading to stuff like this where one object clips inside another. How would I go about fixing this?
I could do something along the lines of- inch the object I'm holding forward in the direction of the ray starting from the camera until it touches something, but that sounds inaccurate and pretty annoying. Is there a better way?
Turns out sphere/capsule casts are a thing. Thanks anyways
Depends what on what your goals are. One way is to place objects only on allowed surfaces that define a grid. Then check all grid positions nearby and pick the best one based on some metric you define
A grid could work but I'd rather use something continuous. I got it now though, thanks
A grid can be arbitrarily small and solve a lot of issues that continuous solutions have
That's fair.
Float solutions are just using a grid that scales based on number size and is unpredictable
That makes sense
Is there a cheat sheet for what type of level procgen algorithm to use depending on the use cases?
How is it possible that my coroutine gets called multiple times even when the first lines of the IEnumerator are flipping the higher and lower bools?:
if (lowCrawl && lower &&!higher &&!transitioning)
{
higher = true;
lower = false;
StartCoroutine(GetHigher());
}
A grid for things like capsules sounds like a nightmare though.
well, look at where you're resetting them, maybe that's getting called when it shouldn't.
if you can't figure it out just from looking at those, time to start debugging those values
What do you mean? I'm setting them right here in the code snipper.
The other bools are irrelevant as the coroutine is getting called multiple times, meaning they are the right value anyway
The question is why should the coroutine be called again when higher is true and lower is false?
where are you resetting them back to higher = false or lower = true
well if it's called from here, then higher is true and lower is false is wrong
like i said, try debugging the values over time in Update or something
also maybe you have multiple of this component, whether that's on purpose or not
I'm sorry I don't understand. Conditions are met, then I flip them so the coroutine doesn't get called again...I did that flip in the coroutine and moved here just in case, but that didn't fix it
nope, one script and one object
and you never flip them back?
where else are lower/higher getting set?
oh my god I'm a moron
nvm fixed
it wasn't that, it was something stupider than that
obviously thats not how you'd implement it, a grid doesn't actually exist in a scene, its just a discretization of a continuous space which you perform during your calculations.
I want to check whether the tunnel in front of my is getting narrower. So far I'm sending two rays, one higher than the other, towards move direction
If the higher ray hits and lower doesn't, that's a positive result for me...but that's very unreliable. How can I improve this?
For example, I could extend the distance of the rays and compares the distances between the two hits AND check surface normal angle for better certainty.
Is this better? Anything else?
i didn't realize 'four directional grid movement' qualified as 'a bit more complicated', my bad i guess. i don't even think transform vs moveposition even mattered here, turning off my composite collider on the walls fixed my issue, now the box collider seems to move one square south too far and one square north not enough. (had the south issue before the composite turn off)
Use a CapsuleCast or SphereCast
how would i add sound effects to UI, navigation? like more specifically i guess how do i detect the event system switching selected UI elements, i can figure out the playing sounds part
UI OnSelect event / ISelectHandler
also another issue is i notice that what ever UI is selected, gets deselected when clicking, how do i disable this or reselect when a controller input is detected or something?
It's a setting on your input module
There’s no official implementation of that but you could recreate it in a couple different ways
How so? Currently the closest I've had is putting my 'dontdestroyonload' singletons in basically every scene I plan to run regularly
Is it something intended for editor or the final game?
Besides the ones on the starting scene the rest are for the editor ofc, a autoloads system like godots would eliminate the need for that
There's initialize on load attribute that can be used to initialize stuff outside of scenes. As well as some editor callbacks.
If it's an editor tool, you should make an editor script or something. Other than that, placing a singleton in the scene is the right way.
i got a error message saying i need a animator conponment, what does that mean
Show the actual error message
I want to create a separate object that I can use in multiple classes derived by mono behavior. I have been looking for references relevant to that. It's poco, something we use in normal c# programming.
I have an idea how to code it but Monobehavior restricts a lot of it.
This sounds like something related specifically to VR chat, so you should ask in their community. !vrc
!vrchat
Join the growing VRChat community as you explore, play, and create the future of social VR! https://discord.com/invite/vrchat
You can use any and all C# features in Unity. There are no restrictions on using POCOs.
That's what I have been trying to figure out.
Do you have a specific question?
It is in my previous message?
I answered it
There is nothing preventing you from doing anything you do in "normal C# programming" in Unity
perhaps if I share my code you'll understand what specifically I am trying to achieve?
that would be great
I don't understand what you're asking
what do you mean by "my code breaks"?
Also are these snippets from two different classes?
You didn't share what any of this is: RockPool.rockPoolInstance.GetPooledGameObject();
so it's hard to tell what that;s calling
this is the same class
or what's going wrong
so what do you mean by "my code breaks"?
What are you expecting to happen and what actually happens?
It might be helpful if you made a thread
okay
I think I figured it out, thank you. This was a confusing question to ask even for me. This was do-able but we don't normally think about scalability unless it is a big project, so maybe that might have confused everyone when I asked if they know any references for SOLID.
thanks again.
if you initialize it in the same FixedUpdate, it will keep refreshing the index
I'm gonna be honest, I still have no idea what you were asking here.
but you at least made effort to understand and try to help me out, even if you were clueless, so I thanked you for that. I left a code up there, it might help, because it is working now. The problem was setting the values once every time the timer is 0. When I tried it it started refreshing index but it wouldn't give me the error or anything.
if you still like me to move this to thread, I'll do that.
is there still an issue here? because I also have no clue what you're asking here, even from reading the initial message.
that is some extremely questionable code too
how is it questionable?
I am not going to keep on repeating myself if you guys don't understand you guys don't understand. Lets just leave it at that.
line 41 is ShootSytem.play(); and gunscriptable object is the glock model it says i have an error while shooting my gun and i dont see any errors
this is a null reference
you need to initialize your gun
or the game object that you're trying to use here.
Well for one, the hardcoded GameObject.Find calls in a row. But since you've deleted it I cant answer more...
As for ur 2nd message, people are trying to help, the way you've worded questions are extremely vague and just generally dont make sense. Repeating it or saying you wrote it above doesnt help yourself get help.
Dont crosspost #📖┃code-of-conduct
ok my bad
Oh that, it is wiser to get the objects from your game scene or from the resources. Thankfully I didn't post my object pool code where I am getting prefabs from the resource folders. The second message was I was looking for a way to initialize an object once and reinitialize an object when the timer runs out without using any coroutines because coroutines is an expensive call, or so I've heared.
so I asked here if anyone have any reference or a site or even a section of this community that has any remote reference of pocos being used to code in unity.
When I said 2nd message I was specifically referring to the 2nd message in your response to me #archived-code-general message
You also dont need to get prefabs via resources. You can literally just drag and drop them as a reference
What if you have many prefabs and you want to cycle through them with random index?
In regards to your coroutine part: Using a timer vs a coroutine is fine here. I doubt you'll ever run into issues with coroutines here. Youd really have to be starting a lot of them to see a performance difference. The profiler would give you more insight to these things too
You can make a list and it will show in inspector. Drag and drop them into the inspector either way
Cycle through them with a random index isnt related to the whole Resources vs drag and drop
So you'd rather suggest dragging and dropping 100s of objects into inspector than selecting them by labels, names, and tags?
interesting
in that case maybe I am asking questions that no one here ever heard of, makes my questions sound vague.
sounds like a pretty standard question
No, one isn't related to the other, but you still have to select them some how.
If you're using resources or GameObject.Find on 100s of objects in the first place you're gonna have problems. It's not like you're dealing with 100s of objects in random folders, or different sets of 100 objects every day. You can select them all > drag and drop.
The code you deleted above literally had line by line GameObject.Find to populate a list so I dont see how you're thinking dragging is worse here
Or depending on the context /type of content break that big list down into a list of lists
I will post it again if you like, I was selecting them for testing by using GameObject.Find later on it would've been resources.loadAll("folderpath");
Yeah in most cases a ScriptableObject holding a list is preferable than resources
I got scared because bawsi said "your code is questionable" so I deleted it
ya, I think I am just reading into code.
Thank you guys for this discussion.
void Start()
{
rockSpawners.Add(GameObject.Find("rockSpawn1L"));
rockSpawners.Add(GameObject.Find("rockSpawn2L"));
rockSpawners.Add(GameObject.Find("rockSpawn3L"));
rockSpawners.Add(GameObject.Find("rockSpawn1R"));
rockSpawners.Add(GameObject.Find("rockSpawn2R"));
rockSpawners.Add(GameObject.Find("rockSpawn3R"));
rockSpawners.Add(GameObject.Find("rockSpawn1T"));
rockSpawners.Add(GameObject.Find("rockSpawn2T"));
rockSpawners.Add(GameObject.Find("rockSpawn3T"));
rockSpawners.Add(GameObject.Find("rockSpawn1B"));
rockSpawners.Add(GameObject.Find("rockSpawn2B"));
rockSpawners.Add(GameObject.Find("rockSpawn3B"));
time = 500f;
index = Random.Range(0, rockSpawners.Count);
}
void FixedUpdate()
{
time--;
if(time == 0)
{
Debug.Log("TIME IS: " + time);
index = Random.Range(0, rockSpawners.Count);
spawnerTransform = rockSpawners[index].transform;
rock = RockPool.rockPoolInstance.GetPooledGameObject();
ReInitObject(index, spawnerTransform, rock);
time = 500f;
}
}
void ReInitObject(int index, Transform spawner, GameObject rock)
{
PooledObject currentPooledObject = new PooledObject();
currentPooledObject.currentIndex = index;
currentPooledObject.currentRockSpanwer = spawner;
currentPooledObject.currentRock = rock;
if(rock != null)
{
currentPooledObject.currentRock.transform.position = currentPooledObject.currentRockSpanwer.transform.position;
currentPooledObject.currentRock.transform.rotation = currentPooledObject.currentRockSpanwer.transform.rotation;
currentPooledObject.currentRock.SetActive(true);
}
}
Here is the code bawsi, have at it.
Either one should pretty much be avoided here. The list should just be exposed to inspector by [SerializeField] and drop the items in. You could use a scriptable object if you see a purpose there, you'll be putting the items into the SO then referencing the SO in your monobehaviour.
!!Interesting, I'll keep that in mind
is GameObject.Find("object") is an expensive call too?
it has to scan all objects , also string are very error prone
You probably wont notice any lag from this but it's definitely relatively expensive. Since this would be searching the entire scene compared to already having the reference.
Its better to avoid it because its fragile. If the name of the object ever changes 3 months later, suddenly this code stops working and you'll be wondering why
That's actually a good point.
never actually thought of it this way, I only thought "what if you were to select 100-1000 objects"
Thank you guys
Also if multiple objects have that name
Anyone familiar with using list for localization?
I need to pass down list to an argument, I assume its done this way?
{0:list:{typeName}: {fromValue} -> {toValue}|\n}
Right now I am trying to make item description from these.
Example description:
Damage: 5 -> 7
Agility: 3 -> 5
Defense: 1 -> 2
I have a struct with Enum StatsType, float fromValue, and float toValue.
So I have a List<StatOptionDescription> that I can pass down to.
But I am not sure how to properly pass them down so that it can work with LocalizedString.
Hello, does Unity's playable API support target matching?
Anyone know how I can enable nullable for just my scripts? I'd like to get warnings in both Unity and Visual Studio
void Start(){
playerInput.UI.Click.Disable();
playerInput.Player.Disable();
playerInput.UI.Disable();
}
does anyone know how to disable mouse clicks? i have this main menu and everytime i start the game and click with the mouse it deselects the button selected
How is a single LogStringToConsole call taking 60 milliseconds?
presumably to do stack trace extraction
So this goes away in a release build?
Not if you've got stack traces enabled
#if !UNITY_EDITOR && !DEVELOPMENT_BUILD
// Remove stack traces for Debug.Log and Debug.LogWarning.
// If something is important enough for traces it should be an error or exception.
Application.SetStackTraceLogType(LogType.Log, StackTraceLogType.None);
Application.SetStackTraceLogType(LogType.Warning, StackTraceLogType.None);
#endif
Thanks, that makes sense
Yeah, that too
Although what I added seems to be working fine for now
But I should maybe replace rays with capsules
could someone have a look at this and tell me why do I accelerate when I slide upwards? is there some error in my math?
https://paste.mod.gg/pwxbljplxhyv/0
A tool for sharing your source code with the world!
Try adding a breakpoint and inspecting the relevant variables when the issue happens
gimme a sec lemme check some numbers
my computer is so potato
ffs give me a bit more time
can someone make this make sense to me?
Code snippet:
Debug.Log($"Keys in playerGameObjects: {string.Join(", ", playerGameObjects.Value.Value.Keys)}");
Debug.Log($"ContainsKey({LocalClientId}): {playerGameObjects.Value.Value.ContainsKey(LocalClientId)}");
Debug.Log($"playerGameObjects.Value is null: {playerGameObjects.Value == null}");
Debug.Log($"playerGameObjects.Value.Value is null: {playerGameObjects.Value.Value == null}");
if (playerGameObjects.Value.Value.TryGetValue(LocalClientId, out var player))
{
Debug.Log("Entry found");
localPlayer = player.MapToANetworkObject().gameObject;
}
else
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.AppendLine("Player Remapping Failed");
stringBuilder.AppendLine("Context dump: ");
stringBuilder.AppendLine($"Local id {LocalClientId}");
foreach (var item in playerGameObjects.Value.Value)
{
stringBuilder.AppendLine(item.ToString());
}
Debug.LogError(stringBuilder.ToString());
}
Logs:
Keys in playerGameObjects: 0
ContainsKey(0): False
playerGameObjects.Value is null: False
playerGameObjects.Value.Value is null: False
Player Remapping Failed
Context dump:
Local id 0
[0, NetworkEntityRef]
Might want to explain what the issue is. The logs make total sense to me.
i am trying to access a dictionary by TryGetValue with the key LocalClientId, but the TryGet fails and logs the remapping failed, but the logs do indicate that the LocalClientId (0) is present
I'd try stepping through that code with a debugger.
What type is the ID?
Well that seems likely to be the issue
whats wrong?
Have you implemented GetHashCode and Equals appropriately with your struct?
no
Is your struct simply a wrapper on your ulong?
If you're using it as a key to a set you should override both of those methods for performance reasons anyway
ye it wraps a ulong i use to track objects (with some utility functions)
I'm not sure why you think a ulong would be equal to a struct then.
But anyways, I'd start with debugging the code with a debugger.
i didn't expect them to be equated directly
implemented those functions and now stuff works
Thanks for the help
looks like friction is applied incorrectly because of the increasing acceleration
but the maths work out logically
another point might be my code blocking people from riding slopes
and the maths there didn't work out
{
// check to see if player is in same direction as the resultant velocity
if (Vector3.Dot(movementForce, currentVelocity + movementForce) > 0f)
{
// get the normal of the obstruction
var obstructionNormal = Vector3.Cross
(
motor.CharacterUp,
Vector3.Cross
(
motor.CharacterUp,
motor.GroundingStatus.GroundNormal
)
).normalized;
// prevent movement force that would boost the player
movementForce = Vector3.ProjectOnPlane(movementForce, obstructionNormal);
}
}```
so presumably i either flipped a vector here or the ProjectOnPlane actually accelerated the player
when i was sliding upwards
my deduction is since the code only have problem when I slide upward, the vector here is wrong
Well, debug it. Either add debug rays to see the relevant vectors in the game or step through the code and see their values.
Project on plane can't produce a vector with bigger magnitude than the input vector.
I used some debug rays and did find out that the magnitude was much larger than expected, which confused me when I reviewed the code
can't seem to pinpoint where it got wrong even with breakpoints
To me the obstructionNormal calculation is weird. I'm not sure what you're trying to achieve with it and why.
I'm trying to get the normal of the obstruction so the player wouldn't slide upwards by spamming the slide button
I don't see anything related to obstructions in it though. Only ground normal and character up.
whenever when the player isn't grounded (is not stable on ground) but still find ground (obstruction)
You should probably visualize the related vectors in the game to see if they match your expectations
Or as I said earlier, step through the code and see if the values match your expectations
I'll try again and see if the grounding normal has any problems
So, I'm working with a modified Kinematic Character Controller, and I used it's "Charging" tutorial to make a Rolling ability.
https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131?srsltid=AfmBOop1MQShdPTUeQwhp7wgt997XCZpNYBhj53IB21WHlD1f6iriIT-
(This is the thing.)
However, the whole ability is quite bork'd. And it has strange interactions with Water.
Here is how water should behave, roughly.
And here's what happens when I try rolling into it.
But curiously, it ONLY happens the first time I enter water, and ONLY when rolling into it.
And here's the error that comes up.
show code
Should I just post the C# files wholesale?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
wait, it doesn't even seem to be your code, the error points to example code from the asset
https://paste.mod.gg/glndxvydymrt/0
Okay, this is the Character Controller Script.
(And I edited the Example Code, just to clear that up.)
A tool for sharing your source code with the world!
If I need to post the motor script as well, let me know.
_waterZone is null there. i'm not going to comb through code that isn't even yours to find out why it might be null though.
Okay, I have turned "private Collider _waterZone;" into public.
The water zone appears to be whatever water volume the player is currently swimming in. And somehow, Rolling causes the player to enter the swimming state without getting an assigned water zone.
the slightly blue cells should be way more blue basically, if they weren't affected
Doesn't seem code related
partly, but you're right it's mostly visual I'll move this, thank you
Okay, I fixed my problem. I just had to update the water detection function to be extended to all states that weren't swimming.
Not just grounding but all the intermediate vectors as well
hey yall, losing my mind over what i "think" is code logic again:
The idea behind what i'm trying to do is to make the camera fade to black during the monster's kill animation, however the fade never happens for some reason and you can see the void as the player is being teleported back to the beginning
I've verified that the camera DOES fade if i change the priority within inspector, and the player.FadeToBlack() function is also called during runtime
The flow of the script goes:
Player is killed, monster's kill animation starts
-> during the monster's kill animation, it calls ResetMonster(), which just makes it so that it's not triggering the player kill multiple times, but also invokes the GameOver() event for the game manager
-> Gamemanager tells player to fade to black (change priority of the fadetoblack camera on the player), then triggers an event to reset the game
-> Roommanager.RestartRoomManager() is called, which teleports the player and monster back to their beginning positions
-> player.RespawnPlayer() is called, sets fadetoblack back to 0 so the camera should be in its normal state
the issue is likely that you're changing the priority to 2 and then back to 0 all within the same frame within the same method chain so nothing else is happening during that time that the priority is 2
you don't want to set it back to 0 until after the transition
Ok ok, I'll take a look at what i can do
Though how could i achieve this? Because in Type.ResetLevel I'm teleporting the player & monster, and then right after that's done, the priority is set to 0
and that all happens within the same frame.
Imagine this scenario:
I have a $5 bill, you want this $5 bill to buy a drink from a vending machine. I then stop time, place the money in your hand, then immediately take it back and resume time. Were you able to spend that $5 at the vending machine?
This is essentially what you are doing with the priority for the camera, there is no time that passes between when you set it to 2 and when you set it back to 0
Oh yeah I understand that, I mean how do I make the time flow "as intended", I thought maybe coroutines would've helped but no dice
wdym "no dice"? that definitely would work provided you actually wait in the coroutine
otherwise, you might need to unspaghettify your code and use some more events (like an event that triggers when the transition is complete)
Alright, I might've screwed up with the coroutine placement when I tried, I'll take a look again
I also did spend quite a bit of time unspaghettifying the code (it was way way worse than this lol), but I'm not against doing more of that
Though i might ask assistance regarding that when the time comes, the current state of the codebase is as much as I could do
I think this happened in an episode of JoJo's once
Dio did kind of fuck with Polnareff like that
tried to go up some stairs and Dio kept placing him back down
being on topic, not sure what i did before with my coroutine, but i got some form of progress now
Well did you search it? What did you find? Here's what I found:
I did, but it doesn’t seem to be working for me so figured I’d ask here to see what others have tried
The csc.rsp part will get Unity to compile with NRT.
For VS/VS Code, I use a Directory.Build.props file:
<Project>
<PropertyGroup>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
I don't know if Rider respects it or not.
(Instead of Directory.Build.props you can also use an editor script to modify the generated .csproj files, but that's a lot more work for the same result)
I have a List<TrackInfo> here. TrackInfo contains a number of [SerializeReference]-attributed fields. All of them have field initializers, but when I add an item to the list, everything starts out null anyway.
I added that "huh" field to check that default values work at all. It's a regular int field, and that works fine.
I also checked that field initializers work for [SerializeReference] fields that aren't part of an object stored in a list, and that works fine too.
I guess I'm going to need to add a button to the inspector that adds an item to the list and populates its fields
I think unity particle is broken because I forced every Z axis of my particles and they ALWAYS drift away from camera in Z axis!!!
Only solution I found was fixing their Z axis inside shader in vert function... But this is not an actual fix.
https://pastebin.com/cKZ1cmTY
what is going on here??? Why are they always drifting away in Z axis? This is stupid...
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.
Tried what you suggested, but VS is still giving me warnings 😦
Where are you putting the file?
@chilly surge At the root of my assembly
I have an asmdef at the root of my assembly in a folder. I put the csc.rsp and the Directory.Build.props next to the asmdef
Hmm I'm not sure that work, I think the file has to be on the same level (or above) the .csproj file.
In case anyone else has had similar problems I finally managed to fix it:
https://pastebin.com/aQXt2dNQ
Still want to clamp the length of the arrow , but am happy that it finally works
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.
when I am in a scene and I look at the Scene view, the text looks perfect, not blurry at all, but when I go into game it has like weird rectangles around the letters. I tried increasing padding to 10-15-20pixels but it fixed the rectangles but it made the letters feel weird like choppy, in the scene it looks decent but at the game the letters are like low quality, anyone knows a fix?
If I have an event that is supposed to trigger at frame 10 of a video playing, but the video happens to skip frame 10, is there a way to try and make sure that event is hit anyways?
has anyone else had problem with particles velocity? Im creating a 2D game using meshes and creating particles with meshes. I completely locked their Z position everywhere even added a Z clamp in update for every particles. I also tested disabling any velocity completely. Particles always drift away from camera in Z axis no matter what!! im getting frustrated , I have been trying to solve this the entire day.
screenshot?
gravity being applied to particles?
try frame == 11 ? or check previous frame and current frame then check if frame 10 has been skipped.
also no I even tested no gravity with my particles.
I'm trying to cover if arbitrary frames are skipped, not specifically frame 10.
so you need to detect for any frame skip happening?
yep
then do something like this:
float expectedFrameTime = 1f / 60f;
float skipThreshold = 0.005f;
void Update()
{
float delta = Time.unscaledDeltaTime;
if (delta > expectedFrameTime + skipThreshold)
{
Debug.Log($"Frame skipped. Delta time: {delta:F4}");
}
}
what does your emission collider look like
im not to sure on where to go to ask for help for this im starting to get into some sort of developing and trying to run this starter project file i have to test out movemtn/animations etc but i cant get it working due to error codes i dont know how to fix if anyone could help it would be great
its these 4 errors here
My particles doesnt show any collider
I'm unsure, using the InputSystem, how to read if any mapped action is in use or not. I tried "IsPressed()" but it returned true all the time. So tried something else instead which always returns false.
private static bool GetAnyActionHeld()
{
foreach (InputAction action in InputSystem.actions)
{
bool? state = (action.ReadValueAsObject() as bool?);
if (state.HasValue && state.Value) return true;
}
return false;
}
Is there a better way? I can't imagine that Unity made this system without a way to check if any input is in use (Like for "Press Any Key").
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.14/api/UnityEngine.InputSystem.InputActionMap.html#UnityEngine_InputSystem_InputActionMap_actionTriggered
or maybe
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.14/api/UnityEngine.InputSystem.Keyboard.html#UnityEngine_InputSystem_Keyboard_anyKey
depending on what you're actually looking for?
or just bind an action to anyKey
So I have a Credits scene where when you have held any action mapped button for x amount of time, then the credits will prematurely end.
So it needs to be that I can read any of the input actions I have in my maps and check if any of them are in use. If they are, I can assume a button is being held down.
I'm open to suggestions on doing this differently, if there is a better way to approach that problem
Well I think you could use <*>/* as the control path in your binding and it will capture literally everything
Or perhaps "<*>/*[Button]" for any button control
No you can just set this up as a binding in the asset, no need for calloing GetAction or FindAction at all
InputAction action = InputSystem.actions.FindAction(@"<*>/*[Button]");
So instead of this, how would I then prompt the InputSystem to figure out if a button indeed was pressed?
Or is being held, I guess
Make an action in your asset of type Button
Make a binding for it, and use <*>/*[Button] as the binding path
then treat in in your code like any other button action
so like InputSystem.actions["MyAction"].IsPressed()
or give it a Hold interaction
and listen for WasPerformedThisFrame()
So instead of "InputHelper.GetButtonDown("Exit Credits")" I would do "InputHelper.GetButtonDown("<*>/*[Button]")
no
I don't know what InputHelper is
that's a custom thing you made, so it's hard for me to say how to use it
Ah yeah, sorry that's a utility class. Forgot about that.
So this is what the code currently does to see if a specific action is being called
public static InputAction GetAction(string action)
{
InputAction inputAction = InputSystem.actions.FindAction(action);
if (inputAction == null)
Debug.LogError($"The InputAction \"{action}\" doesn't exist. Check if the spelling is correct or if the action exists in Project Settings -> Input System Package.");
return inputAction;
}
So for example "Settings Menu" might be an action that is then passed on to this method via the InputHelper class.
It then returns the InputAction object, if any, so that you can perform things on the action like reading from it.
In my scenario, I need to be able to read if any mapped button is being held currently, so that I can advance a timer while the buttong is being held.
It would be this way then InputHelper.GetButtonDown("Exit Credits")
But in the input asset, you would bind the Exit Credits action to <*>/*[Button]
Aah, okay. I getcha.
Sorry for the confusion there. I think I got it now.
It is odd to me that Unity does not have an easier way of doing that, but there is likely an implementation detail as to the why.
I feel like InputSystem.IsAnyButtonHeld() would be the easiest
Rather than having to assign an "Any key" like this
The point of inputsystem is to move away from doing keyboard only stuff
Sure, although I don't see what that has to do with what I am envisioning
Controllers also have buttons
but then how does that work for local multiplayer? How do you exclude certain buttons or devices?
It makes it super simple for your one, hyper-specific use case at the expense of flexibility and extensibility. Which is basically reverting back to the old input system
There is a "any action triggered" event for PlayerInputs and the arg given can be used to read the state and duration: https://docs.unity3d.com/Packages/com.unity.inputsystem@1.14/api/UnityEngine.InputSystem.PlayerInput.html#UnityEngine_InputSystem_PlayerInput_onActionTriggered
Making a convenience method is not really taking away from what everyone else is doing and I can assure that "any key" detection is far from uncommon for use cases like this.
blah blah unity not wanting to presume or overstep with such a function blah blah
I doubt it's that. They had in the old input system if I'm not mistaken.
I think it was simply overlooked in the new design when it was made.
Just odd after this amount of time 🤷♀️
I presume it was keyboard + mouse only but this new system is trying to make make us avoid being keyboard centric. Anyway you have to do whatever works yea its nice to wish for a nice solution to already exist
And I want to point out again that, what I asked for is not keyboard centric
It is input method agnostic. Every input has buttons of some kind.
Yeah, the new input system is...missing quite a few things that seem like common sense
I suppose that in the code for your event handling, you could just route the InputAction.CallbackContext into a custom input handler and have that increment a value if context.performed/decrement that value if context.canceled, then check if any button is held by querying that value. It's a bit like a counting semaphore lmao
is it legwork? yeah, you have to make sure you slap that method call into every event handler. could be worse though
Yeah that sounds... way more complicated than simply making a binding for all buttons.
Can you make a binding that just accepts "any button"?
ah i see that
er, 30-40 minutes
my bad, I missed that lmao
no two people have the same idea what common sense is
On an abstract level perhaps, but there are people who agree on what "common sense" is.
However to believe that common sense is...common is the illogical thing to do, as paradoxical as it sounds.
this is not the first time i've seen a relatively common use case be missing from the inputsystem
the other time was actually brought up in a thread some years back and one of the Unity devs said "yeah we're looking into this next" but it was never implemented lmao
Just because something is a relatively common use case doesn't mean it necessarily needs its own special API.
This is an input system.
Sort of like how Unity is a game engine, yet doesn't have a "First Person Shooter" module.
It's a general purpose system, and the API needs to be powerful and flexible, and yes, easy to work with, but if you over-opinionate your API you end up with a more complicated API with tons of caveats and multiple ways of doing the same thing.
right but
this isn't a "special API", this is just "is any button held"
that's a special API call
i think we have different ideas of what consitutes a "special API" then
¯_(ツ)_/¯ seems that way yes
Would anyone happen to know how I can find how far a ray intersected a Gameobject?
The RaycastHit from your Raycast has a distance property
subtract the hit point from the ray distance
sweet
What you are saying, and what I requested (the anyButtonPressed) are not incompatible. They are in fact not related.
You could argue that any convenience call, of which the InputSystem has many, would be a "special API call" by your own definition, which to me would be an absurd notion.
Here's a point against a universal anyButtonPressed: Motion controls. If I have a game that reads input from, say, a Joy-Con controller, moving the controller is an input. Do I want to include waggle in "Any button" or not? It's not really a button, but it is an input in my input actions map
Somewhere between "all the possible convenience methods" and "no convenience methods" is the right number of convenience methods.
If I'm making a "Press any button to continue" menu, do I want it to continue if the user moves their hand at all?
Probably not.
It is an input, but it is not a button, unless you present it that way. I see no counterpoint here.
Button presses are discrete values. Movement, such as kinetic input or positioning devices, is continuous.
thanks guys