#archived-code-general
1 messages ยท Page 437 of 1
oh wait i think i misunderstood
do you mean "parameter" in the general/mathematical sense, rather than relating to functions?
getting build errors (again) but not sure what exactly is the cause... it just disappears and wont let me click on it
i think your just taking this a little too literally rather than conversationally
i mean either way, this level of being pedantic doesnt really do anything. its understood what i meant regardless in that a value goes from A to B. im aware of these things, thats just not how people talk in reality
I am currently attempting to solve errors porting from referencing SO to referencing a base C# class.
Lots of null reference exceptions
compile errors should be visible in your IDE or even console before building
i disagree tbh; in my experience arguments and parameters have basically always been called how they are, not interchangable
well I managed to see an error I guess... but yeah it doesn't appear on my Visual Studio 2022 or Unity Errors... lets me play in test mode just fine but denies me to build
you'd have to show what specifically you have problems with. i also have to head off soon so i really recommend posting this as its own question. null ref errors are really the same in most cases. something is null, you tried to access it. you gotta find out why its null. (unless its a unity editor error)
I have almost always seen parameter be used in this context
i havent used parrel sync in awhile. I dont think its available in a build though as that doesnt really make sense. maybe ask in #archived-networking or specifically the multiplayer unity server
the docs for it do say "ParrelSync is a Unity editor extension" so that implies to me it cant exist in a build
When I was referencing the SO's directly, I was doing things like ```cs
if (currentItem != null) do this;
I think its because the references to the class instances are never null
yeah you have to mark serialized base classes as [SerializeReference] iirc
I guess deleting that line of code seemed to work... but that seems a little annoying to deal with testing and well making builds ๐
otherwise the serialization of the base class ensures it's always an instance
It says that is only for fields
do you mean [Serializable]
it would only ever be forced to be not null in the context of serialized fields afaik?
well yea your SO wont be null since its a physical asset. You have to new your c# object. really its best if u make this as a new question possibly in #๐ปโcode-beginner since its a null ref error and show people the full context
in the stuff i mentioned above, you should be creating a new instance of it so you can actually pass a unique ItemData to your inventory
even if its serialized, you dont want to pass that same instance to everyh item
truthfully ive never used parrel sync in my own code. i used it purely for creating the 2nd folder and running 2 editor instances is all. you could surround it with a conditional compilation #if unity editor
I just got told by another server to do
if (!ApplicationContext.isClone)
instead... I guess this is their solution. I think this is a Purrnet (the networking service I am using for my multiplayer game) thing though
what you have seems better than what i was doing, a checkbox in editor to declare which was the server
havent seen that either but if it works then thats good. the #if unity editor would be your other solution
yeah like 99% of this code is from a tutorial from Bobsi lmao
I haven't even made my own "Main Menu" for my game yet... just relying on their sample scenes and then following their tutorial to make it work with the SteamTransport
atm just been focusing on getting gameplay features done
maybe we've just been in different environments 
well hopefully you get further than i do in it. i guess purrnet is also new since i havent heard of it before. there was ngo, mirror and fishnet when i was messing around. but yea i think these types of questions will mostly be better in their server usually. a lot of the times it may seem like a simple unity question but then its specific to one random framework component
It's a new thing yeah. It's aiming to make it easy for developers. At least that's their goal.
Hello! I made an item database editor window so I can make items without scripting in my videogame. It wasn't super difficult. But I'm struggling pretty badly with making an inventory. I managed to make an inventory grid and make the icons / items draggable and swappable, but when stacking and such came into it I became stuck.
Can anybody recommend something? A tutorial, maybe a forum? I'm trying to make an inventory with 25 slots and an equipment window next to it where my 3D character displays and I can drag equipment on it.
What got you stuck about stacking? Inventory and equipment windows are often common in RPG tutorials, so you could try looking up tutorials related to that or you could try searching both of those specific keywords
Stacking gave some weird behaviours. Like, I could stack the item, but the quantitytext wouldn't show while all of that had been properly assigned. Then as I tried to fix it, I could endlessly duplicate items. Or at one point I could place the items anywhere on my screen outside inventory grid. Before this, the inventory worked fine. But at this stage I'm so far along in my code that I cannot revert the changes either so it's pretty much ruined. xD
I searched at inventory system unity but it gave me 2D mostly. I'll try looking up RPG tutorials instead.
Even tried debugging with AI through Co-pilot and Codeium, because I'm only a beginner at this. But no luck. Felt like they only drove it into the ground further.
Inventory system would be mostly the same both in 2d and 3d
Ah I see, AI can be tricky to work with code, though if you are thinking of rebuilding your system, maybe you could break down those parts from the perspective of how it should function, the actions you do to cause things to happen, then code each of those actions - you should be able to take 2D tutorials and apply it to your context though, as dlich mentioned, inventories are mostly UI for data so that should apply in both 2D and 3D fine
You're probably right! I found a good 2D tutorial, I think I'll give it a shot. Nothing to lose. My own system is pretty much ruined anyway. I just hope I can integrate the editor window I made with it so I can simply create items without having to script them one by one.
I'd say that inventory system != UI.
It's just the logic of handling inventories/items. The UI can be implemented separately in many different ways.
The moment you merge these concept into one thing, you hit yourself in the foot
Good point, I see a inventory as a list of data, the UI is visualizing that data, so if your UI displays a "item" data class, and your editor window creates "item" instances, I dont see why that setup wouldnt work - but I agree, keeping your systems and data separate when possible is always a good idea
Hi. I can ask about the code here, right?
Yes this is coding general
can you [HideInInspector] but with code like var a = [HideInInspector]
I've got a huge variable script that a lot of other scripts derive from, but these other scripts dont use all of them only some, and i was hoping i could hide them to make it easier to see the variables that do matter
what
ideally you would just not have all those variables in the script they derive from
perhaps adding using different components alltogether or fitting in layers of inheritence in between that base script and the scripts deriving from it
a double inheritance? hmm
Custom inspector editor so you can draw what you want is the solution @placid edge
you cant remove an attribute for an inherited field/property
double isn't anything atypical
a lot of situations involve many layers
thing is there's like, a lot of different permutations to inherit
is that like an extension or can i do it in unity?
there's not a single answer to that kinda question but c#'s "solution" is interfaces and unity's "solution" would be different components alltogether
you can override and do your own inspector for a monobehaviour so you can customise what it draws and does
a mix of all three options is done based on preference and context
quick sidebar, can a private var still be inherited?
kk
however using SerializedReference is different but i forget
is anyone here good with collisions
im having a pretty complicated problem with my game object destroyer and my collider script
There are 120.000 people here, just ask your question, if someone can help they will.
Optimization is one of those "cross that bridge if and when we get there", if your not experiencing any noticeable problems then its fine, you could always use the profiler to check performance and test on lower end machines that you may be targeting/supporting as well - there is also Physics Scenes in Unity to simulate stuff like trajectories: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/PhysicsScene.html - lots of good tutorials on how to use Physics Scenes on YouTube as well if you choose to try that approach
I pull my move action like this:
var moveAction = _inputMap.FindAction("Move");
when inspecting it with the debugger, there is a list of bindings, but no clear way how to pull the bindings bundled under secondary or primary.
What I'm trying to do is pull a specific binding, e.g Secondary/Left and then rebind it to another key. However I do not understand how to access it.
Is there a way to create a 2D expanding ring visual effect? As in, expanding radius, but constant thickness of the line.
perhaps ask in #๐ฑ๏ธโinput-system?
๐ค im not sure this really fits here, perhaps one of the art channels would be a better fit?
Is there any major reason not to handle some logic in private variables, inside a scriptable object? (ie: keeping track of a "current element position" pointer in a list)
did anyone actually make that statement ? wdym
TextMeshPro Question:
so i want to create a players options to control the font size of the game.
my attempt is to increase the faceInfo.scale of the font asset.
this works perfectly in the inspector, because its a scriptable object.
but when I change the scale in code, it indeed updates the scriptable object... but the font ingame is not updated....
why?
whats wrong with txt.fontSize = somevalue; ?
i want to update all text in game not just one...
I think the font scale is only applied when you bake the texture again
so may depend then also on the texture mode being dynamic or not
you probably want to change the font material asset?
yeah i was looking for something like an update or redraw call...
i dont want to create a system that grabs all textfields in all scenes to change them.
this is why i am trying to change the font asset
I never said that
i could restart the game to make it take place... but that feels... a little too much lol
yea if dynamic you will need to change it before anything is added to the texture...
so just dont and have some font offset to apply to tmp instances then
I have two transforms: A & B, and B can move freely around inside a radius around A.
However, when the move direction goes outside of the radius I want to get the intersecting point C.
How would I go about finding C?
Vector3 C = A + Vector3.ClampMagnitude(B - A, radius);```
Perhaps just that
So we get the direction from A to B and limit it with the radius
And if you need to detect when it's outside the circle, you'd check if the magnitude of B - A is more than the radius
(A, B, C are position vectors, not transforms in my example)
if you need the actual point C, then its a bit more complex I think. there are solutions to circle intersection online
Yeah just realized they might need something more complex if the blue arrow's direction matters here
Yeah, I've tried wrapping my head around this for a little while now... I'm not really sure what to look for online.
Circle-line intersection
Looks like a potential parametric equation + some dot product could work too 
(My solution would only find the yellow point)
Yeah, my very temporary solution looks like this:
What's wrong with it?
It works great in that example, but isn't very accurate in other situations...
"circle intersection algorithm" should lead you to actual math solutions for this. from what i remember, it would be uni level math, maybe 2nd-3rd year even
Thank you, will look into it.
If it ends up being too complicated I might just have to settle for my temporary solution..
couldn't you do this algebraically?
Length of yellow is just distance from center of circle to the blue line, length of orange is just circle's radius, then you can extend from intersection of blue and yellow.
That too, you have the equations of both the line and the circle and you can solve for the two intersection points, then you select the one that fits.
Will give an attempt at this, not sure if I'm competent enough for this right now, but we'll see...
i find it a bit confusing what you're doing here. how would you get the distance from the center and the blue line?
From what i understand, the blue line is a vector, not a line equation
You wouldnt be able to represent something like (0,1) in the equation
The blue arrow has to have a starting point as well as a direction, that's enough to derive an equation for the blue line.
what equation do you derive if the direction is pointing straight up?
x - c = 0
I kinda wanted to solve this by going over the math, but I asked Phind to do this, and it did manage to solve it.
Not sure what code it gave you, but do check for edge cases by looking at divisions and see if it's possible to end up with divide by 0.
Yes, looking through the sources provided, I see people check those kinds of cases.
I can share the Phind thread if that is allowed
i slept very little, but i assume you'd have to treat this as its own edge case right? the formulas for distance from a point to a line would result in division by 0 here
I mean the distance would be C if the center was 0, 0 but just confirming
Yeah, things will work out in math, but not in programming.
The typical approach is to just solve it while ignoring edge cases, turn it into code, then check for division by 0 afterwards.
I don't see if links are allowed or not, but ill post the Phind thread with the code and sources it provided:
https://www.phind.com/search/cm91kggre00003j6s8l23c5ot
Idk about the math but I would definitely not allocate an array just for that result ๐ฌ
Although I guess it's cleaner to look at and easier to iterate over
i kinda skimmed through it but code math is never that fun to read. One thing I didnt consider initially which is pretty obvious, and that this AI code doesnt consider is that if you treat blue's line as infinite in either direction, there will always be intersections. there can't be 0
which also simplifies the problem
Does anyone know how can I make an outline shader. Where I want to outline the object based on drawing a cube around the object instead of outlining all of the smoothed edges and others
So if like the object is a sphere I still want the outline shader to draw a cube around the object
That doesn't sound like outlines at all really, wouldn't you just draw a quad that has some borders?
You can calculate a screen space rectangle from the renderer's bounds if you need it to fit inside
I will see if I can manage to simplify it this way, since the only time I check for this intersection is when I know it should intersect. I also don't look forward to going through the math
I quickly skimmed through it and that code takes the same almost the same approach as the image I've shown.
hello everyone, sorry to bother you guys . I'm new with decals and I'm trying to use it to paint a grid floor on a curvy terrain. I have two questions regarding the pics attached. First one is where do I change the alpha of a decal texture ? I don't see the option.
nevermind it's actually set in the decal projector itself
hello everyone, i dont know this is the right channel to ask this. But it is posible to make a game like for example tetris in versus mode so Player 1 vs Player 2 each of them with their own gameplay on a same PC in different monitors? And for example when the time finishes the player with most points win and the winner is display in both monitors
anything is possible
Unity Camera can target specific monitor . https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Camera-targetDisplay.html
there would be performance implications of using 2 cameras on the same scene, essentially rendering twice
how do I do that though?
@vestal archthank you, I will try the input system channel.
Im making a UI game and I'm using a system where if you hover over a button, some text will be attached to your cursor (which you can't see here, but you can see the text.) Is there a way to draw a box around that hover area and make it the same size as (or slightly bigger than) the text?
If you know an element has the pointer over it you can have some tooltip element be positioned and sized correctly to match. What ui system is this?
With the old and new input system you can easily get the mouse position to move some element to the mouse
Im using UI, the text is textmeshpro. Unless you mean something else with ui system
yea i meant ugui or ui toolkit.
All you need then is some Image with your tmp text inside it. Position the rect transform to be where you wish and you can set the rect transform size to match the hovered element (RectTransform.rect to get the size)
I could do that but is there no way to automatically get the size of the box?
You can also just set up these things to have the tooltip element already created but hidden and you can reveal it when the hover happens
its not magic you have to do something to make things work??
But a lot of games have an automatic box size system and its a lot more modular. I could manually make a box but its not an ideal solution
Use the event system events: https://docs.unity3d.com/2019.1/Documentation/ScriptReference/EventSystems.IPointerEnterHandler.html
you are too vague, there are "automatic layout" components to do layout for you and the anchors to also perform automatic resizing
Thats something I want then, how do I do it?
tbh i am confused what you really want now
I have the hover and cursor system set up its just the box I need
you can get the size of any rect transform so therefore you can make any other rect transform match the size of another
I need to create a "box" that wraps around my hovered text to the perfect size
yeah but the ratios wont always be the same will they? Unity uses different measuring units for the width of text and the widh of an image
All UGUI elements use rect transform
If you use layout groups you can have the rect transform of tmp text auto size to fit the text it contains (this uses the 'preferred size' of the tmp text)
Then you can use the rect transform rect to size match a lot better
Hell you can even just grab the bounds of the mesh and use this but thats extra work
Whenever you use TextMesh Pro component, it feeds the Preferred Width and Height (which can be use automatically with some layout such as Vertical and Horizontal). I also, I believe there is a function to get the preferred with and height directly if you prefer.
does it account for everything including font size and whatnot? If so then can you find it for me?
Yes, it does.
And no, I wont give it directly to you.
Alright
newer docs dont show inherited functions so here:
https://docs.unity3d.com/Packages/com.unity.textmeshpro@1.0/api/TMPro.TMP_Text.html#TMPro_TMP_Text_GetPreferredWidth
you can use these functions to get this data or use layout groups to auto layout the tmp text (which can also set the rect transform size then automatically)
i need help pls anyone know how to delete all changesets after a certain one in plastic scm?
After changeset 129 my workspace is so fucked
so because i feel like i mathed wrong im going to ask here.
so i'm trying to do what is the equivalent of RaycastHit2D.fraction, (which returns a number from 0 and 1) onto a regular RaycastHit.
problem is RaycastHit does not contain a fraction method like the 2d one does.
what would be the proper way to do this?
normally i'd check if the fraction is 0f to continue my method
most of my raycast isn't different at all except im just using 3d raycasts now. so i feel like i should for most reasons should get the same numerical result?
anyway my attempt to make an equivalent was to do
if (RaycastHit.distance / (Vector3.Distance(Start, End)) == 0)
but i feel like this might be wrong?
nvm
oh... actually it sorta sounded like that might worked lol but i think im going for a percentage value?
ya I messed up the t part
isnt (RaycastHit.distance / rayMaxlength) enough?
ah im not sure. i never had a raymax length set so i was trying to make one with the vector3 distance lol
physics.Raycast parameter is called maxDistance iirc
it's in raycast and not raycasthit?
yeah you provide to the raycast method
alrighty then. guess i gotta create that.
jsut thought i could get the max distance if i get my start and ending point from the raycast
You could do it how you had it here too #archived-code-general message
just don't compare floats with ==
but only if End is the max
yeah, the end should be the max, where the point should be where the hit happened in between start and end
wait so raycasthit.distance gives a numerical value that doesn't stay between 0 and 1 correct?
it's the distance, so no of course it's not between 0 and 1
alrighty cool. i'm going to do some debug logs, i really need to see what's going on with these numbers to see if my raycasts are hitting or not
ok so... after some debug logs. it seems it is doing the proper distance so that's not my problem
what result are you expecting / whats happening instead?
i'll need some time to properly explain my situation...
well for the most bit i was having 2 issues, one some collisions didn't seem to happen at the correct time, also some angles weren't working correctly when i was converting from 2d to 3d.
but i believe most of my issues revolve around how i was trying to get angles calculated.
originally i'd do Mathf.atan2 on the raycasthit2d normal to get an angle which would give me numbers like this in the image (of course there was a bit more math, using pi mostly and mathf.rad2deg)
eventually when switching things over to 3d, mathf.atan couldn't count for the z position to get the angles on the 3d scene so i used Vector3.angle get my angle. which gave me numbers similar to the 2nd image.
although i believe i fixed what was going on with the 2nd image by stopped using mathf.rad2deg
aaaand i believe i sorted out my issue which was probably all rooted in how my angle values were given to me. so im just trying to debug and fix this.
main thing im going to try to do is get my vector3.angle to behave the same way as the image on the left. so imma pick apart some stuff for a while
Use Vector3.SignedAngle.
Also if you don't want to count the z axis just don't. Remove it from the vectors.
oh i actually do want the z axis
๐ 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.
Hello, In my state machine the transition between the idle to jump states, when I jump the state is abruptly ended then immediately changed to Idle.
Idk why that happens, the transition between move and jump works.
public class IdleState : PlayerStates
{
public IdleState(PlayerSoccerController player) : base(player) { }
public override void EnterState()
{
player.SetAnimation("Speed", 0);
}
public override void UpdateState()
{
if (player.GetPlayerButtons().Horizontal() != 0)
{
player.ChangeState(new MoveState(player));
}
if (player.GetPlayerButtons().Kick())
{
player.ChangeState(new KickState(player));
}
if (player.GetPlayerButtons().Jump())
{
player.ChangeState(new JumpStandingState(player));
}
}
}
public class JumpStandingState : PlayerStates
{
public JumpStandingState(PlayerSoccerController player) : base(player) {}
public override void EnterState()
{
player.SetAnimation("StandJump", true);
player.Jump();
}
public override void UpdateState()
{
player.NormalMovement();
if (player.GetPlayerRb().linearVelocity.y <= 0)
{
player.SetAnimation("StandJump", false);
player.ChangeState(new FallState(player));
}
}
}
public class FallState : PlayerStates
{
public FallState(PlayerSoccerController player) : base(player) { }
public override void EnterState()
{
player.SetAnimation("Fall", true);
}
public override void UpdateState()
{
player.NormalMovement();
if (player.IsGrounded())
{
player.SetAnimation("Fall", false);
player.ChangeState(new IdleState(player));
}
}
}
What's the practical difference between using Resources.Load and using SerialiseField on my classes, in particular for stuff like an extra Sprite or an AudioClip? And is there one that's generally preferred/recommended?
serialize field serializes and exposes the reference
resources.load keeps it in memory throughout the entire game
two very different things
someone can correct me but i haven't seen a good reason to ever use resources.load unless your reliant on plugins that should ideally also not be using it
that's backwards, you can use Resources.Load to load and unload things as needed
You can load instances from the resources folder and unload them but there's a copy of everything in Resources that's always persistant afaik?
It avoids any sort of reference based required loading and unloading things like scenes, bundles, addressables etc. offers
There isn't. You're probably confusing with loading prefabs and instantiating them.
there's a copy of everything on disk, which is where you can load from
Persistent on the hard drive, not in memory
Nah a peer has been lying to me in that case ๐
But yeah, resources is not recommend
Unless you don't care.
If you need to load/unload assets, use addressables
(im googling now and apologies for being incorrect, although there's multiple comments from unity staff that imply or outright stated my incorrect understanding)
to go back to the original question, whether you use Resources.Load or Addressables, the main reason to do that is usually when you want to control the lifetime of the asset rather than having it loaded eagerly as soon as it's referenced which is how serialized fields work. like imagine a UI that can display some big images one at a time, you can load and unload them so you don't have to keep them all in memory at once
The thing is that you need to unload the asset manually. It wouldn't be unloaded when it's not referenced.
This is what mentioned usually.
Everything in Resources gets loaded into memory at startup. It doesn't wait for you to call Load before it reads it from disk.
as mentioned above this is not correct
and was also my impression
it's just the indexing / infomation of the contents in resources
nah this one for example is kinda wilding
technically correct because they are refering to the indexing but i think a lot of people are absolutely going to get the wrong impression
I was following this tutorial https://youtu.be/iNLQCwCHEBM?si=_kKEsoOwt70aigsA. why does this happen?
Unity Ragdoll Tutorial - Animation With Physics - Gang Beasts Style - Part 4
Hey Buds,
If you are having issues with copying the animation, please look at the reply to the pinned comment.
Welcome to Part 4 of the Unity Ragdoll Tutorial Series.
In this one I show you how to animate your ragdoll while allowing the limbs to be affected by physics...
Am I just going crazy expecting my game to not fall under 120 FPS when writing to JSON? I have a few methods that, changing the player's stats in any way cause it to happen. And it's going to like 90 FPS for maybe 4-10 frames. I've tried async but it still lags. Is there a resource or best practice someone can point me to for super lazy saving?
You need to use the profiler and check precisely what's causing the issue
Are you writing to disk on the main thread?
Anything you do besides pulling out the profiler right now is just complete guesswork
I've done Task.Run(() and it didn't seem to have that much of an effect
I read your comment, I'm just responding to you asking about writing on the main thread..
if you're using Task.Run it shouldn't be affecting the main thread frame times much, can you share your code?
can someone take a look?
because you have non-uniform scaling in your hierarchy
For example
The best rule of thumb here is: if an obejct has a child, it cannot have non-uniform scaling.
If you need to scale parts of the body, you should put those parts on separate child objects that don't have any chilren
sec
so instead of :
LeftUpper```
do this:
```Torso (unscaled)
Torso Visuals (scaled)
LeftUpper``` @stark sun
okay thx I'll try
private async Task SaveDataAsync(bool statsChanged, bool recalculateStats)
{
string json = JsonUtility.ToJson(PlayerDataSnapshot, false);
await Task.Run(async () =>
{
await fileWriteLock.WaitAsync();
try
{
File.WriteAllText(jsonPath, json);
}
finally
{
fileWriteLock.Release();
}
});
if (statsChanged) OnPlayerStatsChanged?.Invoke();
if (recalculateStats) _playerData = PlayerManager.Instance.RecalculateStats(PlayerDataSnapshot);
}
fileWriteLock is a SemaphoreSlim
the JSON serialization is still on the main thread then, so the profiler should be able to tell you if that's the slow part, maybe put a profiler BeginSample/EndSample around that specific line
if that's not it, maybe something else on the main thread is blocking waiting for that lock?
adding on to what was already said: I wouldn't be suprised if unity dont allow JsonUtility to be used on other threads (may throw an exception, use a debugger to confirm it works).
Best to not use Task but UniTask (third party) or Awaitable.
the profiler is kinda confusing ngl. I did:
UnityEngine.Profiling.Profiler.BeginSample("Serialize PlayerData");
string json = JsonUtility.ToJson(PlayerDataSnapshot, false);
UnityEngine.Profiling.Profiler.EndSample();
but I can't even find it. I suppose this means the OnGUI is the problem and not the JSON? I'll look into UniTask & Awaitable, thanks
Use hierarchy mode
And search
and deep profiing
Custom markers should appear without deep profiling imho
but yeah it's very likely your actual json serialization is not even noticeable
which would be a very helpful result here
They will yes
340ms gc collect holy moly
The performance drop cause is clearly GC
yea looks like the Serialize says time ms 5.89 lol
Could be that this serialize or something else shortly before allocated a lot and then this gc is happening due to it
i would have thought the incremental gc would not do such a big collect though
yep the profiler will tell you also how much garbage each things creates
I bet they allocate a lot every frame
List<string> foo = new(int.MaxValue);
this is fine in update right? /s
To be serious, using Span + stackalloc should be considered if you want to avoid heap allocation for some temp array.
!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.
https://paste.mod.gg/vccjcttynlzv/0 this is my InitializeSystemLog code which is showing up in that profiling shot
A tool for sharing your source code with the world!
how many logs did it show? could be a lot of labels and strings
testing on a fresh loadin so 0, and I do /clear before
this code is doing a bunch of avoidable allocations and the OnGUI callback can run multiple times per frame, so that could be part of your GC performance problem, although you might want to look at where else memory is being allocated throuhgout each frame in the profiler
it's more likely to be lots of smaller things adding up
honestly I think I just have a lot of overlapping performance issues and I need to go through and whack em 1 by 1. I mean I thought it was lagging when I picked up exp orbs but I just got it to not lag by disabling some other thing in my game. I have a 1300 line OnGUI inventory and it usually doesn't lag.. unless I have a full inventory since I'm serializing every texture2D as a byte array, then doing copies on my entire player object. It's atrocious. Thanks for the resources and help guys I'll need to get more familiar with the profiler and do a couple refactors, I'll be back if I narrow things down more
You should be using ui toolkit or ugui for your game UI
yeah I wish I found that out before I made the inventory for sure
ongui has been "old" for like 10+ years
well I made my cards interface with UI toolkit, sort of. I ended up using the VisualComponents as positioning and transitioned to code, just seems easier to me
im confused then. draw the ui document and all is good?
I took some code & prefabs from balatro-feel github, so I use UI document to position the cards & containers then use their positions to instantiate the prefabs
it would be easier if there werent 3 of them and information about it wasn't confusing as all hell
its easy. UGUI uses canvas + rect transform and other components like image and button.
UI toolkit is xml and can be built with the visual editor. It has styles like css and does not use gameobjects for its elements.
ongui is an old immediate mode gui system where you have to re define and create the ui on each draw
right, I mean I'm aware of it now. But when I got started with Unity I just missed that OnGUI is 'old'. It's not deprecated but you shouldn't use it.. information that just slipped my field of awareness
I'll probably have to replace the OnGUIs I made in the future but for now they 'work'
OnGUI/IMGUI is great for quick and dirty debug UI
Hmm well that sucks but some simple research should show what unity list as the current major ui systems and what you should use
its good for non prod ui yes
alright I'll go back in time 4 months and tell myself to research it xD
I'm more of a 'code now, ask questions later' kinda guy
sometimes the answer to those later questions is "you shouldn't have done that" ๐
Ive done things in a weird way, not wanted to refactor it... then realise more it really needs a refactor and do it anyway ๐
Sucks to loose work but more reliable and maintainable code is better.
you're not wrong. my current philosophy is to maximize velocity since there's just so many things that need to be done. I know I'm going to have to refactor in the future but I'd rather have something workable to re-do rather than nothing on paper. I'm doing the thing everyone says not to do and just going for a 3D RPG as a solo dev rather than limiting scope in anyway so this type of stuff is inevitable
I extracted your cat's footprint from this
omg
@bleak garden Don't post memes here
!warn 186870134672064512 Don't post memes, don't spam the channel.
exiym has been warned.
@bleak garden Keep clowning
No, was just curious.
I did manage to catch the serialization taking 400 ms
alrighty so perhaps i'm not using Vector3.SingedAngle properly.. so im going to backtrack back to the root of the number value i wanted.
the main goal was to convert my 2d raycasts to 3d. for the most bit (except for 2 things) it's coming along fine.
collisions are handled all within raycasts, the colliders are only for the raycasts hits.
in the 2d setup to get my normal angle information from a raycast, i'd get the raycasthit's .normal and use Mathf.Atan2 on it and put a modulus from using the acquired angle as the dividend and using 2x of pi as a divisor.
after that i get the surface angle by getting the modulus using the normal angle subtracted by half of pi as the dividend and using 2x of pi as a divisor again.
so now i want to do that but for 3d normals while pretty much getting the same kind of results, just taking the z axis to count for the extra information needed to handle orientation.
so i guess in a simple way of saying. im looking for a way to get these 2d angles rotated but get the same normal and surface angle results.
i believe what i need to do is find a way to get mathf.atan2 to be able to get me a tangent taking the orientation to it...
its usually not advised to have mutable data in your SO at all, because the asset just represents one instance. everything referring to that instance will read the same data. if you have a valid use case for what u said at the time, its not like its illegal to do so
Expand it more. This is like GC as I've said earlier.
If it is, it would obviously happen in different places at different times
this is incredibly hard to follow. instead of describing this whole 2d thing, what are you actually trying to do in a 3d context? the normal already exists and there are built in methods to calculate angles
you very rarely actually need trig math in these things with all the built in methods
it just says GC Alloc
it's probably this for storing my item pictures
public void OnBeforeSerialize()
{
if(_ItemPortrait != null)
{
byte[] textureBytes = _ItemPortrait.texture.EncodeToPNG();
_ItemTextureDataBase64 = Convert.ToBase64String(textureBytes);
}
else
{
_ItemTextureDataBase64 = string.Empty;
}
}
Yes, that's what it would say usually. Alloc or free.
You should avoid allocating a local byte array.
how often is it running? it looks like it's in Update, nearly 500kb is a big allocation to be doing frequently
it should only run once per item to serialize. So if I have like 8 items in my inventory 8 times
Why do you need to serialize a texture anyway? Is it generates at runtime?
right, but how often does the serialization happen
it's somewhere in the Update loop based on this?
only when a value is changed, I'm testing it with exp orbs so my player is getting hit with 3 serialization calls within a 0.1s time frame. I have this in my exp track function and the _saveManager.AddExperience line is what's calling it
you either need to call it way less often (make an autosave timer or something?) or do a lot of work to reduce the amount of allocations that happen there ๐
Can you explain why you're serializing a texture?
my inventory is an OnGUI function and I use it there
That doesn't explain anything
the first step would be, don't do that
Are these textures generated at runtime? Are they not existing assets?
they are existing assets
Then why duplicate them?
Why are you saving it during runtime?
Save when the game ends or on some loading screen
what if the game crashes?
is this also running on the actual experience orbs? this is really bad..
Then fix the crash
You shouldn't be saving things on runtime or on update
every orb does not need to run that logic, and they shouldnt have access to saving
Can you answer a simple question: why are you saving the texture data?
I don't know what you want me to say. I deserialize it so my ItemData class can have the Sprite and I can just use it.
Is it just for saving the game state?
put them in a dictionary or list somewhere and serialize an ID or index instead, you don't need to save the whole sprite
ok, I'll do this. thanks
If it is, then this is not how you save game. You'd save a texture/sprite I'd and assign it at runtime. It's ridiculous to be saving a whole asset.
well this is interesting to read
never seen someone save an asset as a string before
well here's my JSON, yea it's storing the pictures for all the items in the inventory
plz be joking
maybe it will work with UniTask or newtonsoft
Isn't it clear already that you shouldn't be doing this at all?
of course
to be clear this is shit and will always perform badly
switching out the async or json code will be a difference of a few bytes here and there, the 500kb allocation is coming from this giant file haha
If you want runtime change-able icons or something you should load them separately and ref them smartly throughout this inv json.
some things are still lagging even with 0 items in the inventory but yes I'll have to get the sprites a different way
use Resources, Addressables or just some serialized list and reference them with their name/address
A simple fix:
[SerializeField] private Sprite _sprite;
I thought you couldn't serialize a sprite
well I don't think you even can
its a unity serialized reference TO THE ASSET
can be anything (almost), audio clip, texture2d, material, shader...
ive usually seen beginners ask about saving gameobjects or similar to file, but this is the first time ive actually seen someone follow through too
the advice you see anywhere is to map it to an ID
genius though right?
not in the slightest
I paid for the CPU I'm gonna use the CPU
And that's how no one will pay for the game
Bad thinking
this is fairly common among advanced "beginners" that don't participate in this discord. happens mostly with meshes though.
that won't work with JsonUtility will it?
i mean you probably can (but shouldn't), but that's not what's happening here
it's the field (and its reference) that's being serialized, it just happens to be of type Sprite
well I'm joking lol
Load json -> get id of item -> find item def -> get sprite from item def -> ??? -> profit.
[CreateAssetMenu(fileName = "New Item", menuName = "Scriptables/Item")]
public class Item : ScriptableObject
{
public string GUID; // <-- That's what you'll save in the json and use to load items
public Sprite Icon; // <-- That's where you would insert a sprite that exists on your Assets folder
public string Name;
public string Description;
public Item()
{
GUID = Guid.NewGuid().ToString();
}
}
the ??? is making the rest of the game
constructor works there? this seems really off..
Yup
It's called when the scriptable is created
So it attributes a new guid
yea, then we profit and make big bucks ๐ต
it's not doing anything unity-related so it's fine
thats interesting. ive seen a lot of questions in here about generating an ID in scriptable objects but this is the first time ive seen someone use the ctor
good to know
it's basically the same as writing it as public string GUID = Guid.NewGuid().ToString(); which i think is pretty common, i think most people do that with primitive types all the time
hm, you can't just initialize GUID from the field declaration?
ah
I remember a bug by doing that where the GUID will randomly change some times
Due to recompilation or something else, cant remember right now
๐คท well, field initializers are essentially part of the constructor, so there should be no difference
what does Guid.NewGuid() do
So the whole parroting of "never use constructors with unity objects" is just nonsense apparently
it creates a new guid....?
so I map GUIDs to each item?
I think it's a misconception of the real issue which is using new
You can also just put an id yourself that you understand like "pistol" or "shovel"
Hi, im trying to code my wheels to rotate with the speed if my car, i managed to do this but when i code the front wheel turning it somehow resets the frontwheel rotation every frame since im using update method so does anyone know how to implement both wheel roll with car speed and steering at the same time, this is my code
using UnityEngine.InputSystem;
public class CarController : MonoBehaviour
{
[Header("Car Settings")]
[SerializeField] private float acceleration = 100f;
[SerializeField] private float maxSpeed = 20f;
[SerializeField] private float turnSpeed = 10f;
[SerializeField] private float gripStrength = 5f;
[Header("Wheel Settings")]
[SerializeField] private Transform[] frontWheels;
[SerializeField] private Transform[] allWheels;
[SerializeField] private Transform[] backWheels;
[SerializeField] private float maxSteerAngle = 30f;
private PlayerInput playerInput;
private InputAction throttleAction;
private InputAction turnAction;
private Rigidbody rb;
private void Awake()
{
rb = GetComponent<Rigidbody>();
playerInput = GetComponent<PlayerInput>(); // Ensure a PlayerInput component is attached
throttleAction = playerInput.actions["Throttle"];
turnAction = playerInput.actions["Turn"];
}
void Update()
{
HandleMovement();
ApplyTireGrip();
UpdateWheels();
}
private void HandleMovement()
{
float forwardInput = throttleAction.ReadValue<float>(); // Supports both keys & gamepad
float turnInput = turnAction.ReadValue<float>();
if (forwardInput != 0)
{
Vector3 moveDirection = rb.transform.forward;
Vector3 force = moveDirection * forwardInput * acceleration;
if (rb.linearVelocity.magnitude < maxSpeed)
{
rb.AddForce(force, ForceMode.Acceleration);
}
}
rb.AddTorque(Vector3.up * turnInput * turnSpeed);
}
private void ApplyTireGrip()
{
Vector3 lateralVelocity = Vector3.Project(rb.linearVelocity, transform.right);
rb.AddForce(-lateralVelocity * gripStrength, ForceMode.Acceleration);
}
private void UpdateWheels()
{
float speed = Vector3.Dot(rb.linearVelocity, transform.forward); // signed forward speed
float rotationAmount = speed * Time.deltaTime * 360f;
float steerInput = turnAction.ReadValue<float>();
float steerAngle = steerInput * maxSteerAngle;
foreach (Transform wheel in backWheels)
{
// Just roll the back wheels
wheel.Rotate(Vector3.right, rotationAmount, Space.Self);
}
foreach (Transform wheel in frontWheels)
{
wheel.Rotate(Vector3.right, rotationAmount, Space.Self);
}
}
}
it's still good advice for new users, until you understand exactly when they run and why you can't do unity stuff there
Yeah. It's good for beginners, but detrimental for more advanced users. "never use constructors unless you know what you're doing" would be more appropriate :p
I personally didn't know that this is valid
unity can be picky what you use or access from some constructors so its kinda shit
But there is, field initializers run during asset creation and loading, when Unity loads a scriptableobject it deserializes it from the .asset file, normally it should skip fields initializers if the value is already serialized, but there are lots of edge cases like script reload, partial serialization and so on where this line may run again, resetting the GUID and silently overwriting it and breaking references... Meanwhile the constructor runs and assign the GUID only once, making it stable and persistent (exactly what you want for json-based save files, runtime lookups and so on)
(I don't know on newer versions, when i tried making it your way it was 2021 or 2022, may or may not have been fixed)
You have a misunderstanding there. Constructor will run every time the object is created, generating a new guid. It's "stable" in the sense that afterwards, data will be deserialized onto the object and overwrite the new guid with the "old" one. Constructors don't necessarily execute on the main thread in Unity so it's a lot easier to just tell people not to use them than to explain why it's okay sometimes and not other times
How can I prevent the thing happening on lower legs?
Them bending sideways? Your joint's axis is probably facing the wrong direction
Or should the lower legs not rotate at all?
Show the relevant code, settings and other context.
animations were inverted so I just changed the scale of legs to -
that may be the problem
Okay I reverted it
Yeah you generally don't want to scale any physics objects weirdly (negative or non-uniform)
Invert the axis of the upper leg joint
I inverted it and it looks like this
Physics.RaycastNonalloc doesn't add things to array in order do it?
No, you'd need to sort it yourself if you need that
I don't need help but does anyone else here really wish there was more consistency between 2D and 3D
It's like 2D is missing some features and yet gets like so many different new ones
Especially physics related ones
Oh wait I wonder if it's because of Box2D
ah, for me i sorta almost feel like the opposite lol but that might be because i used 2d so much more than 3d (which is why im having the certain issues im having lol)
oki dokie cool. i think i'll try sorting them out
anyone done a bunch of work with Graph editor foundations (experimental i think)? i need to ask some questions before diving into it
can anyone come to vc and help me with smth please? u dont need to talk, bc i wont too, im writing whats wrong etc, would be nice :D, if interested, dm me, bc this server doesnt have vc :O
That's not how this server works. You can !ask your question correctly and people can help if they wish.
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #๐โfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
alr, i have a car and a player, u should spawn with a player, but u spawn in the car, thats not right, when i make the car invisible, then ill spawn with the character, and my question is, how can i fix that
Video: http://egesworld.com/need-help/ (bc i cant upload a huge file)
Problem: the player starts in the car, but it should spawn/start as the player (capsule object), idk why it doesnt work, but in the video u can see that when i remove the CarController script, that it does work, but when i enable it, it doesnt work, so if u can help me, please help me :D
I mean it's pretty clear - the CarController script is doing it
so isn't the solution to just disable it before the player enters a car?
oh, thx for the help, ill try that
is it possible to restrict only a certain subset of custom nodes to certain visual scripting graphs?
I have been having an issue with the NavMeshAgent 's remainingDistance, it is sometimes returning infinity even if the npc is literally a few steps in front of the objective, literally nothing blocking its path. I read that it returns infinity when there are still some corners to turn before getting to the objective, but this is simply not the case. Anyone has an idea on how to deal with this or a more reliable way to know the npc got to the target position?
By the way, I did Debug.Log the amount of corners and it got to like 8 even though it is literally in front of the objective. ._.
how can i fix that? .-.
when i click e, this pops up
The only reason you would see that is if you're rendering your game through a RenderTexture for some reason
oh, yk how to fix that?, bc im looking toturials, and trying to find the fix myself
but i cant find it
I mean the way to fix that is to have a real camera in the scene
not sure what else to say
I think you're kind of in tutorial-land and you're not really focusing on actually learning how to use the basics of Unity
no, i am, but i already have an camera, and an camera is getting created when u r in the car
sounds like a really weird setup
.-.
ok so im trying to use Vector3.SignedAngle, which works sorta but, im trying to get anles from the opposite side to give me a number value that isn't a mirror to the other side.
like, if i rotate a plane a bit, i'd get an angle of 12 degrees. but when i rotate it the opposite direction, i get about the same thing, even though i was expecting it to circle back to either 350 or -170.
i figured if i could get it to go into a negative number from the opposite direction, i could at least check for that and just add 360 to it to give me the number value i wanted
yes you can check for it and add 360
e.g.
if (angle < 0) angle += 360;```
if you want the angles to always be positive
It might help if you explain what you're trying to do and what the actual issue is
making the numbers always positive isn't always a good thing
oh good idea, imma try that, thx
cough use Cinemachine cough
nah, i want to use and edit my own camera :P
what am i doing wrong
doesnt work
same error
im feeling dumb rn ๐ญ only bc of a car ๐
ik ๐ญ its everything of the car :P
lol
ok so, long story short, i'm changing my 2d game to account for 2.5d on-rail gameplay.
i want to keep my 2d behaviors just allow it to account for rotation of it being brought along by a spine.
at the moment, im just trying to make sure my raycasts that aim down are getting the angles of slopes correctly.
originally my angles worked as, 360 and 0 being the character being on a flat surface and 180 simply meant that they were contacting an upside-down surface.
so since i can't use mathf.atan2 and just get some radians off a 3d normal, i'm going to try to skip past getting radians and use vector3.angle to get me the angled degrees i want.
anyway im starting to think that im aiming signed angle incorrectly.
Vector3.Angle doesn't tell you which direction the rotation is in though
it tells you the minimum angle between the two vectors
always <= 180 degrees
That's what SignedAngle is for
And yes it's quite possible you're using SignedAngle incorrectly
without seeing your code I can't tell you
ah ok sec
should i combine the first scritp with sec one? or should it be like this, its there (first script), so the player can enter the car
Vector3 dir = new Vector3(0, 1, 0).normalized;
NormalAngle = Vector3.SignedAngle(hit.normal, Vector3.up, dir);
at the moment i was just trying to get the angles from a 2d perspective but not 2d if im making sense (i feel like i said this wrong)
well in this example both your to direciton and your axis are the same exact vector
I find it very hard to believe that Vector3.up aka (0, 1, 0) is the correct axis
Think of it this way
Vector3.SignedAngle is like taking a piece of paper and drawing two lines on it
the first two directions are the lines
the third direction is the way your pencil would be pointing if you placed it standing up on its eraser on the desk
like up and out of the sheet of paper
for a normal 2D perspective that would be Vector3.back
aaaaaah
so:
NormalAngle = Vector3.SignedAngle(hit.normal, Vector3.up, Vector3.back);```
the axis is the normal of the surface the paper is resting on
i think i understand now, thank you very much for the explanation and the pencil and line relation lol
yeah that actually fixed it, thank you again! โค๏ธ
so all i gotta do is change vector3.back to something to account for the character or camera's perspective and it should be good
Does anyone know how to implement frontwheel turning and rolling to my car, im trying to create rocket league like car movement, and im usin Rigidbody to exert forces and rotations to my car
My issue is that im having a hard time achieving both front wheel steering and rolling rotations, if i use both the other one does not work
{
float speed = Vector3.Dot(rb.linearVelocity, transform.forward); // signed forward speed
float rotationAmount = speed * Time.deltaTime * 360f;
float steerInput = turnAction.ReadValue<float>();
float steerAngle = steerInput * maxSteerAngle;
foreach (Transform wheel in backWheels)
{
// Just roll the back wheels
wheel.Rotate(Vector3.right, rotationAmount, Space.Self);
}
foreach (Transform wheel in frontWheels)
{
wheel.Rotate(Vector3.right, rotationAmount, Space.Self);
}
}
}
Im calling UpdateWheels every frame to set rolling rotation and steering rotation but somehow it is not working
Backwheels roll and work fine but the front wheels wont roll with this code, only steer
wheel.Rotate(Vector3.right, rotationAmount, Space.Self);
Here vector3,right should roll the wheels and rotation amount should rotate y axis for steering
I dont see where you would be steering the front wheels in this code. do some debugging to print out values to see that wheel.Rotate would be rotating the object, assuming rotationAmount isnt 0. Maybe you have other code that is directly setting the rotation
I havent used them myself, but I think wheel colliders already have this functionality built in
i am getting a error Platform name 'VisionOS' not supported. when installing https://github.com/apple/unityplugins but i am not building the apple.core for visonOS only for iOS put still the final package has VisionOS i am using unity 2021.3
always found it strange how these are distributed...
also upgrade version as 2021 is not supported updated anymore (unless you have enterprise)
Iโm just familiarizing my self with the profiler. For some reasons the render pipeline manager is taking a lot of frame time, what can I do to improve itโs performance. The scene only contains a default terrain with a grass texture, no trees, no grass and no deformations to the terrain.
Curious does anyone have any examples of using Unity to build real time applications other than games?
For example a level editor, studio of some kind, DAW, etc?
Share a screenshot in jpg or PNG format.
check the #๐โunity-industry channel. there are examples of peoples' work there
Cool
You'll need to expand the hierarchy more. This only tells us that the issue is related to rendering.
So you can see that the main camera takes around 5ms to render. The total time of the rendering is around 16 Ms, so there must be something else taking the rest of the time. Probably several more cameras rendering the same amount of objects. We don't see it in this screenshot, it's below.
5ms for preparing rendering is more or less okay. You'll need to investigate what the other cameras are and why they take that much time.
Or it could be something else, like a canvas.
Something that the engine renders.
there is a second camera rendering only the gun which is quite normal for an fps game. The third camera is rendering to a render texture for the map and it has separate rendering layer that currently only has two things the player ui representation and also enemies ui representation nothing else. I disabled the map camera to see if it was the one giving the delay but it wasn't the one
Well, you'll need to look at the profiler data, but the rest of the cameras seem to take 11ms in total, which is a lot for non main camera.
It might be something else, we need to see the profiler data.
These things would increase GPU time, not CPU. CPU time would mostly be affected by draw calls count.
Ah I presumed it was also waiting for the GPU but this shows it's not doing much
Not many draw calls either. Need to see the profiler hierarchy for the full picture.
Let me disable other cameras and see if it's improves
Yeah, there are special functions that would appear if it was waiting. Like wait for present and such.
Can you. Just share proper profiler screenshot.
I was lazy and did not open the screenshot fully (on mobile)
The one you provided earlier expands too much. Just keep it expanded to the camera level.
15ms physics ๐ฎ
unity recommended frametime is 16ms or ??
16ms is 60 fps
1/60 = 0.016
depends on your target framerate
1 / target framerate gets your frame budget
if you target 144hz you need 1/144
ok
Yeah, so you can see that weapon and map cameras take almost as much time as your main camera. That's a lot. And then there's the scriptable render context too, which I'm not entirely sure what it is without seeing it's details.
I assume it's submitting the command lists to the GPU, but that shouldn't be that long imho ๐ค
@strange rapids When profiling you have to think what kind of performance/framerate you want to see for your hardware. If you have a high end pc and cant even hit 60fps then you have problems.
if your pc is poo poo but you can get stable 30 then its probably okay-ish.
Also, shouldn't that be on the render thread?๐ค
I think i discovered something, i was testing the game using the unity simulator(since im developing for mobile). I ran the game on my phone and it performed very smoothly. Then i changed to the normal game view and it performed well
Seems like the simulator was the one causing issues
Thanks y'all
6ms for rendering is still arguably high. But I guess it depends on your game and frame time budget
device simulator? maybe the resolution was too high for your pc to handle well
so it could be better?
probably. I don't have powerful hardware so it's most likely
Yea you need to think about all these things when profiling. Editor perf is always a bit lower anyway vs a real build.
and ofc if you are doing a mobile game then you need to profile on a real device (via a dev build) to know for sure
There are probably ways to optimize it. It's hard to tell without investigating your project closely.
can someone help im trying to develop a planet game and the horizontal mouse movement makes my player fly away from the planet and I dont know how to solve it
scene is quite empty
I'd start from profiling the game on your actual target device as rob5300 suggested.
Then look at the profiler data again. Perhaps you can disable shadows and lights for the weapon and map cameras or tone them down to reduce the overhead.
Alright will do. Thanks everyone.
You were told how to post code in the other channel, also don't cross post
I dont know how to do it it doesnt have a share button on the website it told me to go
paste.mod.gg has a Save button in the top left, paste your code in and click that. Then copy the link from your address bar and post it here
Should probably also show your other movement code and related inspector setup
https://paste.mod.gg/bzxdblybtrul/0 there are 3 scripts here that I use related to this
A tool for sharing your source code with the world!
what do you think? about it what could be the issue
I only see one script and it looks AI generated
which one do you see
movementScript1
A tool for sharing your source code with the world!
A tool for sharing your source code with the world!
so what do you think could be the issue @hexed pecan
I'm looking to setup a GameManager and TimeScaleManager for pausing. It raised a question about events. If I want the GameManager to have a UnityEvent like Paused, and the TimeScaleManager should have a listener for that event, where should I be putting the AddListener line? Is it better to have that line in the class that will be reacting to the event (TimeScaleManager) or the class that is triggering the event (GameManager)?
It depends but usually the class instance itself will subscribe to an event. Also you can use normal c# events if you dont need to do it via the inspector
public event Action<bool> myEvent;
e.g. manager.OnThing += MyCallback; to sub a member function to an event
Putting it in the class that triggers the event defeats the purpose of an event. In that case you might as well have that class simply call the function directly.
The point of an event is to reverse the dependency.
c# events are better as only the owning class can invoke them. a UnityEvent can be invoked by anyone.
Hmm you do raise a good point there.
Thank you both for the input!
I already asked you to show the inspectors of the related objects. But I don't really want to help with AI generated code anyways.
@lone bone btw if you use a c# event it will be null if it has 0 subscribers. You can invoke it safely always by doing myEvent?.Invoke();
Good to know. At the moment, I don't need it in the inspector. So I'll probably use that for now.
a unity event is just a class instance so this does not apply there
This is so weird, could any of you tell me why it's happening?
this is my script, i'm still learning to code:
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
//first i need to get the input of the user through vector 2
//after getting the input of the user in vector 2 i need to translate it to vector 3
//so like that after getting it i need to add a variable that is responsible for the player's speed
//this variable should be visible in the inspector so i change it
[SerializeField] float controlSpeed = 10f;
Vector2 movement;
float xOffset;
float yOffset;
// Update is called once per frame
void Update()
{
xOffset = movement.x * controlSpeed * Time.deltaTime;
yOffset = movement.y * controlSpeed * Time.deltaTime;
transform.localPosition += new Vector3(transform.localPosition.x + xOffset, transform.localPosition.y + yOffset, 0); // this is what moves the object in first place
}
public void OnMove(InputValue value)
{
movement = value.Get<Vector2>();
}
}```
I have no idea what your video has to do with your code tbh
you just adding the position and not the rotation
I want to remove unused unity features from my build.
I am testing how small and optimized i can make the URP sample scene.
Is there a way to inspect builds for what unity deps are actually built and linked?
Ohhh my bad I uploaded the wrong video
Just a sec I'll upload the correct one
well..
The docs website is currently having issues but here https://docs.unity3d.com/6000.0/Documentation/Manual/ReducingFilesize.html
Ok so got a question, is it possible to save a generic type array in Json and then parse it out as arguments for a method, trying to make a json system that saves a String ID of a method and an object[] arguments of that method.
guys here's the correct video
i uploaded the correct one
not the rotation exactly, i uploaded the correct video, unity just crashes
try commenting out parts of the code and see what part exactly is responsible
here's my code anything to change in it?
this is my script, i'm still learning to code:
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
//first i need to get the input of the user through vector 2
//after getting the input of the user in vector 2 i need to translate it to vector 3
//so like that after getting it i need to add a variable that is responsible for the player's speed
//this variable should be visible in the inspector so i change it
[SerializeField] float controlSpeed = 10f;
Vector2 movement;
float xOffset;
float yOffset;
// Update is called once per frame
void Update()
{
xOffset = movement.x * controlSpeed * Time.deltaTime;
yOffset = movement.y * controlSpeed * Time.deltaTime;
transform.localPosition += new Vector3(transform.localPosition.x + xOffset, transform.localPosition.y + yOffset, 0); // this is what moves the object in first place
}
public void OnMove(InputValue value)
{
movement = value.Get<Vector2>();
}
}```
I seen it but looks fine at a glance , thats why i said comment out a line or two
nothing in here is going to crash unity
the crashing has nothing to do with this script
most likely its the inspector / GUI crashing (could be a bug)
the floatpoint warning seems weird
your player is being sent EXTREMELY far away which is causing a memory overflow
does your editor also crash when you add the script outside of play mode?
could be transform.localPosition += new Vector3(transform.localPosition.x + adding onto itself soo much that it goes "out of the map"
ik it's why i said it's so weird that it's crashing like this
it's this is the exact script i'm using for the game though
nope only in player mode
kk i'll try to modify this line
what happen if you write this
transform.localPosition += new Vector3(xOffset, yOffset, 0);
so its definitely something wrong with your code
i'll try this
yeah ik but can't tell what exactly it's just crashing
sure but it's not the prob,em
why are you adding the script in play mode though
I think it's just a weird bug with doing that
i'm adding it in player mode for the video i'm recording, so the one that is watching knows there's something wrong with the script
that doesn't tell us something is wrong with the script
that tells us something is wrong with adding the script in playmode
@urban summit did you actually start with script already attached?
i think it's just an editor bug or a bug involving some weird interaction with some other code and adding the script at runtime
no i attached it later in player mode, for the video
attach it in edit mode
so you never tried it with script already on it?
then show a video
i already did that and it kept crashing, it's just i had to attach it during player mode for the video i was recording so whomever watches it knows something wrong with the script
i'll try this way to fix it though
tell me if it works
What version of uNity are you on
Trust me changing any code inside that script iisn't going to fix it
This is an error maybe with the input system or something like that
the code in the script is fine
YOOOOOOOOOO thx man it worked!!!!!
would say it's because he's adding the current position again to the movement vector. This causes the position to grow much faster than it should essentially compounding every frame.
true
but that shouldn't crash the engine
that's the weird part
idk why but using this line transform.localPosition += new Vector3(xOffset, yOffset, 0); instead of this one transform.localPosition += new Vector3(transform.localPosition.x + xOffset, transform.localPosition.y + yOffset, 0); worked
called it :p #archived-code-general message
i mean think about it
unity 6 34.1f
I see why that code is clearly wrong - it just doesn't make sense it would crash Unity ๐ค
truly weird ngl

my guess is just some weird interaction with a huge position value and some other component
i might be missing what youre saying, but isnt any object going that far supposed to crash the editor?
no
why would it
it would just make the object far away
big number is not a danger to anything
unless you for example try to use the big number to allocate that much memory
So - some weird interaction where that is somehow happening methinks
ya normally you just get this but doesnt crash the editor
i did expect it to cause something like this but i guess im wrong. thanks for the clarification
maybe there's some component that is allocating some kind of data structure based on the positions of objects. Like a minecraft-style chunking code that allocates chunks based on the bounds area covered by objects
That might cause such an issue
I would def report this to unity if you can reproduce this @urban summit
so perhaps it might because of the code but also a bug in unity editor as well?
how do i do that?
might be a bug in unity but might also just be a poor interaction between this code and some component you have.
God knows what's in these folders
kk i'll do this right away!
make sure you send them all the assets in your folder too, so they can replicate it with yours as wel
i'm taking gamedev unity course those are just other projects (they don't interact with my current one in anyway)
well but is it not if the the values are growing too large then this error appears (Overflow in memory allocato) ?
a large number takes up the same amount of memory as a small number
i'm just keeping them all in a single folder though
value types have fixed sizes
oh yea right
Guys @sullen urchin @rigid island @leaden ice i just did more invesitgation using AI, it also agrees that my original code would bug the game, so perhaps it was just a bug in my code after all
I'd still report it to unity though
thx for the help everyone
don't listen to that spam generator, it just tells you a bunch of nonsense meant to sound legitimate lol accessing individual components is fine.. The issue was you were adding such a high number but the bug itself is editor not handling that gracefully for some reason.
nothing to do with accessing individual component
Yeah, I agree with that.
I wouldn't disagree with what you're saying, your far more experienced with unity than I, weird that unity editor has behaved that way after all
sure issues but it shouldn't crash
are the docs down for anyone else?
nvm im not getting a server error anymore but the styling is all messed up
The AI's reasoning in that screenshot is very much off
It's nothing to do with using individual XYZ components, it's just that it keeps adding the value to itself
Which grows exponentially
๐
when you do += its actually going to do a = a + b
and as people told you, AI chats will just lie and make shit up
If something actually caused a native crash then you should report it as a bug
if it instead just did something you didnt expect then thats just user error
wdym unsafe? what's telling you it's unsafe?
because it's force ๐
I am struggling with a issue in my scripts, it is relatively complex the topic
Would anyone be willing to help me out on this.
just ask and we will see who can help
How do I paste my code in here, is there some form of comment I need to do add in discord?
<@&502884371011731486> I have a user in my dms asking for volunteer work.
The issue stems from the SetVoxelData, previously I used to not reuse old data in my voxel engine constantly re making the data to re use it. I am beginning to think that this new approach is just a issue.
Okay
If anyone want to take a crack at this one
This is getting into very complex c# like the garbarge collection and job system with burst
If you want us to send them a warning, you need to provide their user ID.
well whats ur problem there?
The problem is in the area called SetVoxelData, inside it I went from the old system of not resuing data to a new dirty update chunk system. For some reason it now only renders a tiny portion of each chunk.
I know for a fact this one spot is the issue, because removing this part and re adding my old code solves it. I am doing this for the performance I was told it can give by instead of deleting the data in the GC it re uses it for the code to run faster
I cannot seem to figure out why it only renders a tiny portion of odd faces of a voxel chunk
!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.
see above
Thank you but I shared using the website called pastecode, if that is okay.
yeah, those are allowed
i personally dislike external sites for relatively small code blocks, which i see quite frequently, especially paste.mod which doesnt seem to work for me on mobile
aiding visibility in code issues, can make it easier for passers by to potentially spot an issue, if its behind a link, maybe less people will take a look
This is actually my first time ever trying to reach out to a community sharing my code related issues like this. I always kept it vague or didn't share the whole code
I mostly use AI to help me find issues
welcome! ive been around community like these for about 15 years now! a lot has changed ๐
ok so i believe i narrowed down all of my problems when converting over to 3d and i believe the singular issue im having now is how
Physics.RaycastNonAlloc doesn't sort the raycastshits the same way that Physics2d.LinecastNonAlloc does.
so i guess my next thing to figure out is how would i be able to sort the physicsraycastnonalloc by distance? was wondering if anyone happened to know a preferred method?
you have an array of them, just sort it yourself. there is no specific order to the elements returned from these functions
if your question is actually how to sort, this should be in #๐ปโcode-beginner
https://learn.microsoft.com/en-us/dotnet/api/system.array.sort?view=net-9.0
you can use the RaycastHit.distance
cool, i'll try that out
my GUI.DrawTexture doesnt do multiple draws
only one at a time
after i updated my unity editor
i need it for my enemy hp bars
I'm getting an error on the marked line because the GameObject that was referenced is destroyed. I was under the assumption that checking if it's null, as I did in the condition above, would return true if it's destroyed but maybe I'm doing it wrong?
void SetLookingAt(IInteractable newInteractable)
{
// Inform what was previously selected that it's no longer being looked at
if (lookingAt != null && lookingAt != newInteractable)
{
lookingAt.ToggleTooltip(false); // Error here
if (lookingAt is OreDeposit)
{
mining.CancelMine();
}
}
// Assign new value
lookingAt = newInteractable;
}```
https://docs.unity3d.com/ScriptReference/Object-operator_Object.html
you're using an interface presumably for lookingAt? i dont think this would be using unitys null check then
a component isnt a GameObject, i assume casting to UnityObject should be fine, if you dont wanna use Monobehaviour or Component
Oh yeah, true
I overlooked that
This still isn't working because I think the cast to a Component counts as accessing the deleted object?
if (lookingAt != null && (lookingAt as Component).gameObject != null && lookingAt != newInteractable)```
is there a way to NOT have my ide default to NUnit.Framework when List is mentioned
no, accessing certain members of a deleted object (like gameObject, transform etc anything that results in a native-layer call) will throw if the native side is destroyed. Drop the .gameObject part
do you have using System.Collections.Generic;
I mean I have to manually put it up every time every since Unity 6
what IDE are you using
Visual Studio
ive always had to include the using tag. what version of VS are you on
VS 2022
So i made a rope generator and sometimes it breaks while regenerating the rope, it does so to adjust the ropes length when the player pulls it apart. And that works but sometimes i get these weird results where the left half of the rope gets turned into a stiff straight line, how could I detect this or even better prevent it from happening in the first place. heres my regeneration function which i think is probaply causing the issue:
private void RegenerateRope()
{
float ropeLength = GetRopeLength();
int newRequiredSegments = Mathf.RoundToInt(ropeLength * ropeResolution);
segmentLength = ropeLength / (float)newRequiredSegments;
List<RopeSegment> newSegments = new List<RopeSegment>();
for (int i = 0; i < newRequiredSegments; i++)
{
float factor = (float)i / (float)newRequiredSegments;
Vector3 position = Vector3.zero;
Vector3 oldPosition = Vector3.zero;
GetPositionAlongRope(factor, out position, out oldPosition);
newSegments.Add(new RopeSegment(oldPosition, position));
}
requiredSegments = newRequiredSegments;
segments.Clear();
segments.AddRange(newSegments);
}
and the get posititon along existing rope function:
private void GetPositionAlongRope(float percent, out Vector3 centerPoint, out Vector3 oldCenterPoint)
{
float ropeIndex = requiredSegments * percent;
int leftPoint = Mathf.FloorToInt(ropeIndex);
int rightPoint = Mathf.CeilToInt(ropeIndex);
// I hade to cut out a small bit to stay within the charachter limit
else
{
centerPoint = Vector3.zero;
centerPoint += segments[leftPoint].currentPosition;
centerPoint += segments[rightPoint].currentPosition;
centerPoint /= 2f;
oldCenterPoint = Vector3.zero;
oldCenterPoint += segments[leftPoint].oldPosition;
oldCenterPoint += segments[rightPoint].oldPosition;
oldCenterPoint /= 2f;
}
}
my GUI.DrawTexture doesnt do multiple draws
only one at a time
after i updated my unity editor
i need it for my enemy hp bars
Dunno what you mean, it's not supposed to draw multiple textures.
For game UI it is recommended to use UGUI (unity UI components) or UI toolkit these days, not the ancient OnGUI/IMGUI system
but i have a custom mouse- a image that follows the mouse and the moue is hidden
so the buttons dont work because the image block the mouse from clicking that
what can ido?
on the image, untick the box that says "raycast target"
you should be doing that on everything you dont intend to be clickable
For a large grid world what is more performant. Having all the visuals in a tilemap or a large texture that im setting pixels of. I will need to be changing colors on them every few frames so pretty consistant updates needed.
I'm new to Unity but have a large background in C#. I'm struggling to find a general architecture or development framework that is all-around "good" to start with - I see folks arguing that too much logic in behaviors is brittle, and I can buy that - what's a good alternative? I watched a video by git-amend on SOAP where components can take dependencies on reactive variables, and that seemed nice, but I'm not paying $70 (the video was an ad for a SOAP framework) for baby's first game
If anyone's familiar with regular C# dev - these days folks build apps on dotnet's hosting framework which provides a good way of building generic console apps, services, web apps, etc... and it beats the crap out of trying to do it yourself.
I'm looking for some kind of equivalent. I'm positive I can build something basic without any tools or patterns, but what is the next level that most folks default to?
https://unity.com/blog/games/level-up-your-code-with-game-programming-patterns
Most of the regular c# patterns apply here, not much changes..
also from other .net framework, main difference Unity doesn't really have its own Dependency Injection system and other systems, there are assets but for the most part you probably wont be using it much
It's not the C#/general patterns that get me, it's the newer things that are specific to game dev.
Take for instance - the tutorial 2D platformer uses a custom "simulation" script, which I believe is a rough kind of ECS system that allows any component to submit events to a queue, iterate over them, and execute them
which tutorial 2D platformer? on Unity website?
It feels odd to me that something as crucial the collection to which you submit all game events and is executed in your loop, is also hand-written.
I guess what I'm after is the established patterns like this, learning what problems they solve, and then choosing one to start with
This one - it was presented to me when I first loaded the editor
I'll see if I can find a link to it
Ah yes that one, imo very over engineered for what it is.. Very bad example from Unity to showcase this..
I think that comes with your own experimentations, there is no hard rule. You eventually do a system that mainly works for you, (or a team if you are doing that)
all keeping in mind the general c#/programming patterns
It's just me, I'm looking to recreate an old flash game and bring it back to life.
I guess I just want to start off on the right foot with a generally accepted framework
I think in the beginning you might be overthinking it
For sure. I know how large the world that I live in is, with line of business app and API development.
And I'm imagining a similar world for games, and I'm like... how can I shortcut this and learn the big points..
I would mainly start with smaller bite siszed projects before diving into your dream project and kinda get a feel of the waters
May not be possible and I just need to dive in lmao
I would recommend just trying things out first and observing the downsides
there's isn't really a standard framework that everyone uses
Got it. I came into the field expecting ECS to be the hotness, and then all I'm reading is that it's... not very necessary and kind of "enterprisey"
I'm guessing I'll end up just making the game I want in a naive way, and then refactoring if I choose.
It's not very complex, a top-down 2D physics game, so it can go through some iterations
I would recommend taking a look at some packages at some point though: UniTask, VContainer (or Zenject), R3 (or UniRx)
unless you have very specific performance needs, avoid ECS
yeah ECS might be adding overcomplication you might not need rn
I think what I'm suffering through is that I'm very educated in one area, and I'm expecting to get the similar level of education in another area without actually experimenting first.

It sucks.
I don't want to be new again.
Thanks for the advice.
also by the way thing are looking from one of the ECS talks, I think unity is working so gameobjects will basically be going to ECS. So you get the ease of gameobjects with benefits of ecs
Yeah I remember reading somewhere on Reddit that there is some hybrid work there
and it's not full DOTS
ya, DOTS is basically the whole system which includes things that can be used with gameobjects too like Jobs / Multithreading .
UniRx is archived, ahhh Aaand found R3.
I think R3 is the new one
speaking of UniTask, unity finally added their own Awaitable class. Something to look into now
at least we get proper Async now..
The SOAP video by git-amend I watched appealed to me because I'm familiar with reactive variables from frontend development, and it seems nice to be able to pass a reference to a reactive number to a score component - rather than publish and listen to events
UniTask adds quite a bit more than just async support, some pretty cool stuff there
hmm need to look into more myself, I just get iffy when having so many dependencies from third party libraries..
well, at least those libraries are actively maintained and open source, so you can always fix your own stuff
I think most people are also using Odin nowadays or something similar
just give it a shot
with time you'll learn what works and what doesnt
theres always a better way of doing things
doesnt mean you always should
otherwise you'll be developing a flash game until youre dead
C# events are pretty good to update variables, like a score component. makes your code more independent
(but harder to debug in the long run)
and they're super cheap to run
even with dozens of events triggering your performance doesnt really suffer
im using unitys hdrp water to create water in my game and a buoyancy script i made but the problem is large objects on the water react too violently to small changes in the waters surface, does anyone have an idea on how i could fix this without just upping the angular drag a ton
Sometimes, the method I use to keep my player on the ground causes this "teleport" effect, where the player unnaturally sticks to the ground.
{
checkPos.transform.rotation = Quaternion.Lerp(checkPos.transform.rotation, Quaternion.Euler(0, 0, -angle), rotationValue);
Vector2 below=castRayLevel(rb.position, -checkPos.transform.up, slopeCheckDownLength, Color.red).point;
if(grounded) rb.position = (slopeHitPoint-below==Vector2.zero || walledSlope ? below:slopeHitPoint) + (Vector2)checkPos.transform.up * cc.radius;
}```
hey, im making a 2d Vampire Survivors like game, firsst time making a game with enemies and i would like to do more types of enemies, how should i do it? i have a Damageable script which does health and dying logic and i want to use it for everything that has health, IDamageable interface with takeDamage and OnDeath functions so i can call it with the interface and not care which enemy type script it is,, as i said, i want to make more types of enemies, so i want to make for example a Scout script that has its own movement logic, this far i get it, but i want for some enemies to have their own dying logic, but because its in the damageable script it has to be same for all, how should i do it? its probably something stupid, but im totally burnedout today and my mind is clouded and tired. I NEED HELP
should i just throw away the damageable script and make the enemytype scripts with all health logic in them?
!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.
sorry, my bad
but im totally burnedout today and my mind is clouded and tired.
you need rest, not help
go get some rest first
it'll help a lot
im trying to do it a whole day and its something new i've never done, dont think a rest will give me any new knowledge xd
it won't give you new knowledge, but resting is important because it freshens your mind so that you can use your already obtained knowledge to fix issues you couldn't figure out with a tired mind
and it'll make it much easier to absorb new knowledge and relate that to your current knowledge
Is there any way to get a reference to a script assigned to a scriptable object from UnityEngine.ScriptableObject?
what do you mean a reference to a script? you dont attach components the same way you do to game objects
are you talking about the scriptasset?
i think?
I am using this asset that allows you to make weighted randomized lists, and it has a feature to allow you to make a list of scriptable objects, and i am trying to get a reference to the the scriptable object itself, but i am getting errors like: Assets\Scripts\Card_Manager.cs(28,21): error CS0266: Cannot implicitly convert type 'UnityEngine.ScriptableObject' to 'Card_Template'. An explicit conversion exists (are you missing a cast?)
its your scriptable object, you should know what reference you're talking about. maybe just show the !code and tell us what problem you're trying to solve here
๐ 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.
ya show code cause that error doesn't tell us much
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GG.Infrastructure.Utils;
using EasyButtons;
public class Card_Manager : MonoBehaviour
{
[SerializeField] public Card_Template[] All_Cards;
[SerializeField] public Card_Template[] All_Cards_Random;
[SerializeField] public Weapon_Card_Template[] All_Weapon_Cards;
[SerializeField] public WeightedListOfScriptableObjects All_Cards_Weight;
private Card_Template Test_Card;
// Start is called before the first frame update
void Start()
{
}
[Button]
public void Weight_Test()
{
Test_Card = All_Cards_Weight.GetRandomByWeight();
//Debug.Log(Test_Card.Card_Name);
}
// Update is called once per frame
void Update()
{
}
}
this is the script
so GetRandomByWeight() returns an SO ?
and what type is Card_Template (class, struct etc..)
the error is also really just a basic c# error
Card_Template is the scriptable object i made, so it is a script
i can send that here as well
whats the return type of GetRandomByWeight();
I think it is what ever the list type is i think?I can go look into the code of the asset i am using to find it, give me a sec
ohh ok. cause whatever it is, it isn't a Card_Template which is what the error is complaining about
i think it is just "ScriptableObject"
not all ScriptableObject fit with each other, each class is its own TYPE of SO
ScriptableObject are nothing different than POCOs except a few unity quirks
you couldn't mix
Cat and Dog class just because theyre both Monobehaviour per se
i get that, but all of the Scriptable Objects in the list are Card_Template
i could try to modify the script to have a class for Card_Template?
am i allowed to??? it is an asset i got off the asset store? idk if i am allowed to show it's code?
I guess? just show the function, its not the whole asset..
if its a custom asset how does it actually return a class you made
you would just have to cast it to the SO type which is exactly what the error tells u
Okay, here is the fuction:
public T GetRandomByWeight()
{
float totalWeight = 0;
for (int i = 0; i < _weights.Count; ++i)
{
totalWeight += _weights[i];
}
float randomWeight = UnityEngine.Random.Range(0, totalWeight);
float currentWeight = 0;
T result = default(T);
bool success = false;
for (int i = 0; i < _weights.Count; ++i)
{
currentWeight += _weights[i];
if (currentWeight > randomWeight)
{
success = true;
result = _objects[i];
break;
}
}
if (!success)
{
Debug.LogError("Can not find proper item, return null or default");
}
return result;
}
how do i do that?
oh its a generic
like this: Test_Card = All_Cards_Weight.GetRandomByWeight() as Card_Template; ?
It worked!

thank you :D
if its generic that means you should probably be providing T at some point but not really sure how you've set that up
its an asset normally you have that in the arguements no?
public T GetRandomByWeight<T>(T myData)
well seems like it's the class that's generic, no?
maybe? i only see the return value is generic
the method isn't generic, as in, the type parameter isn't declared on the method
so it must be from the class
so it's presumably specified somewhere prior to the method call
yea, if a method is defined as Name<T>() then the method is generic, if it's definied as Name() yet still uses T inside it then the class is generic.
Does CanvasRenderer work with custom vertex buffer? The following code works:
var vertexes = new Vector3[] { new(-50, -50), new(-100, 40), new(80, 50), new(100, -40) };
var indexes = new int[] { 0, 1, 2, 2, 3, 0 };
var mesh = new Mesh();
mesh.vertices = vertexes;
mesh.triangles = indexes;
_canvasRenderer.materialCount = 1;
_canvasRenderer.SetMaterial(_material, 0);
_canvasRenderer.SetMesh(mesh);
However the equivalent code with custom vertex buffer, doesn't render anything:
var vertexes = new Vector3[] { new(-50, -50), new(-100, 40), new(80, 50), new(100, -40) };
var indexes = new uint[] { 0, 1, 2, 2, 3, 0 };
var mesh = new Mesh() { subMeshCount = 1 };
mesh.SetVertexBufferParams(
4,
new VertexAttributeDescriptor[] { new(VertexAttribute.Position) }
);
mesh.SetVertexBufferData(vertexes, 0, 0, 4);
mesh.SetIndexBufferParams(6, IndexFormat.UInt32);
mesh.SetIndexBufferData(indexes, 0, 0, 6);
mesh.SetSubMesh(0, new(0, 6));
_canvasRenderer.materialCount = 1;
_canvasRenderer.SetMaterial(_material, 0);
_canvasRenderer.SetMesh(mesh);
I think I fucked it up 
I don't think I was supposed to put a while statement there 
congrats you found an inifinite loop
no gifs ig ๐
try changing any line and saving, if that doesn't work restart the editor
okay ๐
alt + f4
I just made animator spaghetti I am NOT doing all this again ๐
can someone check for capitalization errors im bout to blow
- https://screenshot.help
- get your !IDE configured
- that's not how you share code either
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข
Visual Studio (Installed via Unity Hub)
โข
Visual Studio (Installed manually)
โข
VS Code
โข
JetBrains Rider
โข :question: Other/None
sorry dont have discord on my laptop :( i shall get it
you can also use the browser version
just you know, as long as you don't take photos of a screen. thats painnn
alrighty took a lot of fighting and i can finally confirm the issue was going from Physics2D.LinecastNonAlloc to Physics.RaycastNonAlloc
2d linecastnonalloc would detect multiple collisions and add it to an array while sorting that array with the first thing being the closest thing to the start of the cast. this is what helped me get what i wanted first.
raycastnonalloc would detect multiple collissions and add it to an array, but i dont think it sorted objects the same way that the 2d variant did so i would get inconsistent results.
this really had me confused as i thought my height and range checks were wrong and everything.
so i decided to do a single linecast to see if all my other code was fine... and it was
lol i really spent 5 hours today watching math youtube videos to see if anythig i was doing wrong.
anycase this means the way to get my 3d raycasts work the same way as 2d linecastnonalloc, i need to sort the array by the closes hit from the source.
is there a question here?
not now but thank you for asking
This isnt a channel for your own developer updates, there is #1180170818983051344
oh i'm very sorry.
well i guess to add a question. previously i tried to sort the array from the source but i didn't realize i didn't use it correctly back then. so... now the question is...
how do you actually use Array.orderby? in a case of getting the closest point to the start position of the raycast first and the furthest last?
sorry again about the lack of question prior
have you looked online, there are tons of posts from quick google searches about "how to sort an array based on distance unity"
im not sure what issue you had with Sort, which is what I linked you last time, but you could also just show what you tried there
Test your C# code online with .NET Fiddle code editor.
documentation also has examples for using Comparer https://learn.microsoft.com/en-us/dotnet/api/system.array.sort?view=net-9.0
definitely googled around for a way to do it. i'll admit i did also look at google's generative ai on it too. i tried to follow the sample and it didn't seem to have made any difference at the time so i just deleted it and put it back to what i had before. i was really unsure if what i did was right or wrong i kinda don't really remember how i wrote it at the time ( was definitely trying to remember exactly what i wrote that was wrong)
ok im going to try to do it like this, thank you
if code isn't working or giving correct result should post here before deleting it completely
keep in mind this is basic numbers, you would need to access their property distance in raycasthit
something like this i think.. Array.Sort(hits, (a, b) => a.distance.CompareTo(b.distance));
ah, i never seen .CompareTo before so i definitely was going to mess up here. ๐
thank you very much!
its a method from IComparable shown in Array.Sort docs.
https://learn.microsoft.com/en-us/dotnet/api/system.icomparable.compareto?view=net-9.0#remarks
and => is just replacing a delegate/method
long version
Array.Sort(hits, delegate (RaycastHit a, RaycastHit b)
{
return a.distance.CompareTo(b.distance);
});```
thanks, im gonna spend some time reading this.
also the example you showed seems to not be returning errors so far. im still writing it together.
also "=>" is something i never could understand how/why it worked, so i always avoided using it ๐
and.... this just mostly explained mostly what i was confused about....
so it just handles "vague" variables??
sorta.. it can infer from it, just shorthand of writing the method (a,b) are the same parameters
"type inference" i think is technical term
they're not vague
honestly i looked at that page several times previously and it never clicked, but the code example you showed with the sort actually explained a lot more for me.
oh good ๐ glad it helped
Ah so it writes the type without having to specify the type
it knows the type without declaring it again
coming from the array here , array is Raycasthit (a,b) have to be Raycasthit
ah yeah, ok i understand now ^^ thank you very much. i actually was trying to figure out how to even use => for like 2 or so years and i've just been avoiding using it since then cause it wasnt making sense to me lol
yeah its a bit confusing at first also because it has multiple uses
one more question, if you use Array.sort do you have to make a new array for it or does it just remake the array?
nope it does all the heavy lifting for you
its sorting the same array
using some algorithms, forgot which ones it explains it in the docs
I think this is why choosing OrderBy has its flaw, I think LINQ does in fact create a new array for it
so i'd imagine doing that like every frame or something, eek
oh ok awesome.. i tried to use OrderBy previously because i couldnt get array.sort to work, but i was worried i'd have to make a new array for the sort then just copy the array to where i wanted it to be. but i/m glad i don/t have to do that.
anyways this is what im about to try now. thank you in advance for all of your help and explanations
var _dir = (end - start).normalized; //Destination - origin
var amount = Physics.RaycastNonAlloc(start, _dir, LinecastResults3d, Vector3.Distance(start, end), LayerMask);
Array.Sort(LinecastResults3d, (a, b) => a.distance.CompareTo(b.distance));
ok yeah that worked, thank you very much!
you probably will get issues sorting the re used array here because the old/unused elements are still there...
e.g. array is 6 big but you usually only get 2-4 results.
where would i store api connection data that my clients need to connect to to retrieve server lists for example? i don't want people to be ddosing my endpoints which would take them down for all players haha?
Quick question about csharp events, can you assume they are immediatly executed before the next line (after event.Inkoke());
Nothing is asynchronous unless you very specifically designate it as so
Code runs one line at a time, top to bottom
Ahh gotcha, events were/ is a bit confusing about timing for me. but if everything is run on main thread unless you make it asycthat makes it easier, i thought they may run using a Interrupt pattern
Yes, when you call the event all the subscribers are called one after another.
Even coroutines are single-threaded
that would make sense, if you need each part of a coroutine to run 1 after the other.
designing for asych programming requires a shift in logic, to prevent stuff like race conditions
but thank you so much for answering.
am i right in thinking that the way coroutines work is that it doesnt have to wait for them to finish doing their thing, before it can progress to the next frame?
i could write a method that takes 10 seconds to complete, calling that in update will cause unity to freeze for 10 seconds
it executes the code till it hits some yield statement
then it "pauses" and will execute more next frame/when the time to wait has passed (unity will check that delay each frame)
not quite. it will execute all of its code normally until a yield statement, then the yield will be evaluated at different parts of the frame to see when it continues the next chunk of code, and that process repeats until the coroutine is stopped (which only stops it during a yield) or there is no more code to execute
Once you call StartCoroutine, it runs until it hits a yield. Then, every frame, before Updates are called, it checks the conditions of all outstanding yield statements, and if the condition is done, it runs that coroutine until it hits another yield or exits, then moves on to the usual update loop
There is a great blog post by microsoft that explains how async really works. This is similar in a way to how coroutines work too.
https://devblogs.microsoft.com/dotnet/how-async-await-really-works/
i'll admit i did get some hiccups. the sorting worked most of the time but some times it would just not work. thanks for pointing out that may be the cause, im going to poke around with it a bit
np. Using no alloc is better to avoid allocating arrays all the time but then that means you cannot sort that array with common functions.
If for example only want the closest object you can just loop over the relevant hits and find the closest.
that's a pretty decent idea. im going to give that a try and see how feels ๐ฎ
its always a bad idea to sort a collection just to get the max or min item as its faster to loop once and find it that way.

I am losing my mind trying to fix this, already did a full uninstall / reinstall of vscode.
I should be able to click on these autocompletes with my mouse right? Swear it did before...
I swear that was working before. Keyboard / Tab insertion does work still...
Yeah yeah I should just use keyboard but... it should work right....
Tried things like regen csproj files already... and it does work in VS Studio (but not gonna switch..)
Might have to bug a vs code specific discord but wanted to see if anyone here had an idea.
what if you press enter
It does select the one thats currently highlighted
Nope
Really okay so I am going nuts then lol, installing another extension in vs code for untity snippets DOES work to click them to insert, and its the same looking suggestion window
it works for other things but not methods ๐คทโโ๏ธ Could be something to report on the github
just updating you. this actually fixed it. thanks! โค๏ธ
Oh! i think i know this problem. i think i had this before, give me a moment to find where/how i fixed this.
if i remember correctly there was something that needed to be changed within the options of visual studio. (Sorry i don't remember at the top of my head so i'm looking for it lol)
Ah realized you were using nonalloc instead of raycastall , yeah dunno how I missed that..glad its sorted again tho lol
@stone kraken
well you can enable/disable the list members within the "All languages" or in unity's general case, the "C#" textEditor settings in the options
as far why it didn't fill when you clicked it, it might have something to do with the IntelliSence settings? (not entirely sure) i would suggest re-toggling the show/hide members and see if it would let you fill it
if anything i hope it helps a bit.
Thank you will give a try! ๐
keep in mind this is for Visual Studio, not VSCode
Does anyone know if there's a way (even if it's a hacky one) to make unity's floating windows behave like normal windows? It's so annoying that the floating windows render on top of my other stuff when focusing unity
(repeat from #๐ปโunity-talk mb)
not a code question, and dont crosspost
Sorry, I've never used that channel and it's less active, so I thought I'd give it a try but ur right.
how is โ unity-talk less active? its literally the most active channel..
It's fairly inactive at the moment, but everywhere is inactive at the moment. It's monday morning most people are far too wiped to be asking or answering anything
weird how it worked for 1 method but not the others ๐คทโโ๏ธ
I reported it back in this thread where it was added snippets
https://github.com/microsoft/vscode-dotnettools/issues/1020
Interesting observation, haha if I use my keyboard to go down to the one I want THEN click it works ๐
VS default layout is awful and cluttered, and minimap support is bad.
Like I cant see my region or mark tags by default in vs minimap why not? so weird they both have such different features
to be fair they just added Unity snippets not long ago ๐
we are getting better than where we were 2 years ago
Like some of the good things of both would have thought they would share but I understand vs studio and code were designed for different things
Ahh
Yeah its really a minor thing but... just thought it should work / thought it was before ๐
hey send that to the thread if you can, the microsoft dude who worked on this will see it too
Done!
I'm sure its some type of bug with unity snippets cause it works fine for other things and most people wont notice
I barley use my mouse so I never noticed
If a suggestion is more than a couple down I like clicking ๐คทโโ๏ธ ๐ haven't made it to the keyboard-only elite yet ๐
hehe grateful for keyboard arrows ๐ช
hey there
is there anyway i can make a fixed timestep system that is completely decoupled from the update loop and framerate
i need it for sending inputs over the network where the server expects the time between inputs arriving being roughly the same
Coroutine is coupled with Update/FixedUpdate though
the existing networking frameworks should just do this by default, this is more of a #archived-networking question and you should really just an existing framework
oh ok then
ima ask there but i dont really want to use a framework, ive already spent a lof of time doing netcode
sry did not read the part with the user input, thought he was just looking for some kind of bg task with fixed wait time
most people no matter where you ask is just going to suggest using an existing tool anyways. if you wanna make it yourself, you should likely already know how to make it.
also you could look deeper into them and see what they specifically do
i was asking it here cause its not really a networking specific thing its an engine specific thing
Not sure if it's helpful with networking, but the PlayerLoop API exist, might wanna take a look
I dont know if that actually gets you away from update, but not sure if you'd really be able to at all. There is multithreading but you cant use unity stuff on other threads from what I know
heh, I just found out you can vector.x = Mathf.Lerp(b: 1f, a: 0f, t: 0.5f); write the arguments out of order as long as you name the arguments
ive never written them out of order before
pretty handy when a function has many arguments and you want to be more explicit
also not having to always scan/look at the function to see the order of the params
It can be used also to specify some optional args too if the order is not ideal