#archived-code-general

1 messages ยท Page 437 of 1

vestal arch
#

yes so that's an argument

#

oh wait i think i misunderstood

#

do you mean "parameter" in the general/mathematical sense, rather than relating to functions?

noble herald
#

getting build errors (again) but not sure what exactly is the cause... it just disappears and wont let me click on it

night harness
#

i think your just taking this a little too literally rather than conversationally

lean sail
# vestal arch yes so that's an argument

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

dense estuary
#

I am currently attempting to solve errors porting from referencing SO to referencing a base C# class.

#

Lots of null reference exceptions

lean sail
vestal arch
noble herald
lean sail
night harness
lean sail
#

the docs for it do say "ParrelSync is a Unity editor extension" so that implies to me it cant exist in a build

dense estuary
#

I think its because the references to the class instances are never null

night harness
#

yeah you have to mark serialized base classes as [SerializeReference] iirc

noble herald
night harness
#

otherwise the serialization of the base class ensures it's always an instance

dense estuary
#

do you mean [Serializable]

night harness
#

it would only ever be forced to be not null in the context of serialized fields afaik?

lean sail
#

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

lean sail
noble herald
lean sail
#

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

noble herald
#

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

vestal arch
lean sail
# noble herald I just got told by another server to do ``` if (!ApplicationContext.isCl...

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

noble herald
sturdy hatch
#

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.

soft shard
sturdy hatch
# soft shard What got you stuck about stacking? Inventory and equipment windows are often com...

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.

cosmic rain
soft shard
# sturdy hatch Stacking gave some weird behaviours. Like, I could stack the item, but the quant...

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

sturdy hatch
#

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.

cosmic rain
#

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

soft shard
#

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

forest helm
#

Hi. I can ask about the code here, right?

languid hound
#

Yes this is coding general

placid edge
#

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

night harness
#

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

placid edge
#

a double inheritance? hmm

steady bobcat
#

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

night harness
#

a lot of situations involve many layers

placid edge
#

thing is there's like, a lot of different permutations to inherit

placid edge
night harness
#

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

steady bobcat
night harness
#

a mix of all three options is done based on preference and context

placid edge
#

quick sidebar, can a private var still be inherited?

steady bobcat
#

private fields cannot be accessed by a sub type, change it to protected

placid edge
#

kk

steady bobcat
#

however using SerializedReference is different but i forget

hybrid flower
#

is anyone here good with collisions

#

im having a pretty complicated problem with my game object destroyer and my collider script

main shuttle
#

There are 120.000 people here, just ask your question, if someone can help they will.

soft shard
#

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

lost dove
#

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.

woeful hamlet
#

Is there a way to create a 2D expanding ring visual effect? As in, expanding radius, but constant thickness of the line.

vestal arch
elfin tree
#

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)

rigid island
subtle path
#

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?

rigid island
subtle path
#

i want to update all text in game not just one...

steady bobcat
#

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

rigid island
#

you probably want to change the font material asset?

subtle path
#

yeah i was looking for something like an update or redraw call...

subtle path
#

this is why i am trying to change the font asset

subtle path
steady bobcat
#

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

charred swift
#

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?

hexed pecan
#

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)

lean sail
#

if you need the actual point C, then its a bit more complex I think. there are solutions to circle intersection online

hexed pecan
#

Yeah just realized they might need something more complex if the blue arrow's direction matters here

charred swift
#

Yeah, I've tried wrapping my head around this for a little while now... I'm not really sure what to look for online.

hexed pecan
#

Circle-line intersection

subtle herald
#

Looks like a potential parametric equation + some dot product could work too aPES_Think

hexed pecan
#

(My solution would only find the yellow point)

charred swift
#

Yeah, my very temporary solution looks like this:

hexed pecan
#

What's wrong with it?

charred swift
#

It works great in that example, but isn't very accurate in other situations...

lean sail
charred swift
#

Thank you, will look into it.
If it ends up being too complicated I might just have to settle for my temporary solution..

chilly surge
vestal arch
#

couldn't you do this algebraically?

chilly surge
#

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.

charred swift
#

Will give an attempt at this, not sure if I'm competent enough for this right now, but we'll see...

lean sail
#

You wouldnt be able to represent something like (0,1) in the equation

chilly surge
#

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.

lean sail
#

what equation do you derive if the direction is pointing straight up?

chilly surge
#

x - c = 0

charred swift
#

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.

chilly surge
#

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.

charred swift
#

Yes, looking through the sources provided, I see people check those kinds of cases.

#

I can share the Phind thread if that is allowed

lean sail
# chilly surge `x - c = 0`

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

chilly surge
#

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.

charred swift
hexed pecan
#

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

lean sail
#

which also simplifies the problem

zenith acorn
#

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

hexed pecan
#

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

charred swift
chilly surge
#

I quickly skimmed through it and that code takes the same almost the same approach as the image I've shown.

junior flicker
#

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.

junior flicker
#

nevermind it's actually set in the decal projector itself

barren sentinel
#

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

rigid island
#

there would be performance implications of using 2 cameras on the same scene, essentially rendering twice

lost dove
#

@vestal archthank you, I will try the input system channel.

forest vigil
#

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?

steady bobcat
#

With the old and new input system you can easily get the mouse position to move some element to the mouse

forest vigil
#

Im using UI, the text is textmeshpro. Unless you mean something else with ui system

steady bobcat
#

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)

forest vigil
#

I could do that but is there no way to automatically get the size of the box?

steady bobcat
#

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??

forest vigil
#

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

steady bobcat
#

you are too vague, there are "automatic layout" components to do layout for you and the anchors to also perform automatic resizing

forest vigil
#

Thats something I want then, how do I do it?

steady bobcat
#

tbh i am confused what you really want now

forest vigil
#

I have the hover and cursor system set up its just the box I need

steady bobcat
#

you can get the size of any rect transform so therefore you can make any other rect transform match the size of another

forest vigil
forest vigil
steady bobcat
#

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

steady moat
forest vigil
steady moat
#

And no, I wont give it directly to you.

forest vigil
#

Alright

steady bobcat
safe lintel
#

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

edgy ether
#

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?

rigid island
#

nvm

edgy ether
#

oh... actually it sorta sounded like that might worked lol but i think im going for a percentage value?

rigid island
#

ya I messed up the t part

rigid island
edgy ether
#

ah im not sure. i never had a raymax length set so i was trying to make one with the vector3 distance lol

rigid island
#

physics.Raycast parameter is called maxDistance iirc

edgy ether
#

it's in raycast and not raycasthit?

rigid island
#

yeah you provide to the raycast method

edgy ether
#

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

rigid island
#

but only if End is the max

edgy ether
#

yeah, the end should be the max, where the point should be where the hit happened in between start and end

edgy ether
#

wait so raycasthit.distance gives a numerical value that doesn't stay between 0 and 1 correct?

quartz folio
#

it's the distance, so no of course it's not between 0 and 1

edgy ether
#

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

rigid island
edgy ether
#

i'll need some time to properly explain my situation...

edgy ether
#

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

leaden ice
edgy ether
#

oh i actually do want the z axis

tawny elkBOT
robust berry
#

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));
        }
    }
}

woeful hamlet
#

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?

night harness
#

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

thick terrace
night harness
#

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

cosmic rain
thick terrace
#

there's a copy of everything on disk, which is where you can load from

mellow sigil
#

Persistent on the hard drive, not in memory

night harness
cosmic rain
#

But yeah, resources is not recommend

#

Unless you don't care.

#

If you need to load/unload assets, use addressables

night harness
#

(im googling now and apologies for being incorrect, although there's multiple comments from unity staff that imply or outright stated my incorrect understanding)

thick terrace
# woeful hamlet What's the practical difference between using Resources.Load and using Serialise...

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

cosmic rain
late lion
#

Everything in Resources gets loaded into memory at startup. It doesn't wait for you to call Load before it reads it from disk.

night harness
#

and was also my impression

#

it's just the indexing / infomation of the contents in resources

night harness
#

technically correct because they are refering to the indexing but i think a lot of people are absolutely going to get the wrong impression

stark sun
#

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...

โ–ถ Play video
bleak garden
#

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?

leaden ice
#

Are you writing to disk on the main thread?

#

Anything you do besides pulling out the profiler right now is just complete guesswork

bleak garden
#

I've done Task.Run(() and it didn't seem to have that much of an effect

leaden ice
#

Again

#

guesswork

#

you need to profile first

bleak garden
#

I read your comment, I'm just responding to you asking about writing on the main thread..

thick terrace
leaden ice
#

For example

leaden ice
# stark sun can someone take a look?

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

leaden ice
#

so instead of :

  LeftUpper```

do this:

```Torso (unscaled)
  Torso Visuals (scaled)
  LeftUpper``` @stark sun
bleak garden
# thick terrace if you're using Task.Run it shouldn't be affecting the main thread frame times m...
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

thick terrace
#

if that's not it, maybe something else on the main thread is blocking waiting for that lock?

steady bobcat
bleak garden
#

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

cosmic rain
#

And search

leaden ice
#

and deep profiing

cosmic rain
#

Custom markers should appear without deep profiling imho

leaden ice
#

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

steady bobcat
#

340ms gc collect holy moly

cosmic rain
bleak garden
#

yea looks like the Serialize says time ms 5.89 lol

steady bobcat
#

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

leaden ice
#

yep the profiler will tell you also how much garbage each things creates

cosmic rain
#

I bet they allocate a lot every frame

steady bobcat
#

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.

bleak garden
#

!code

tawny elkBOT
bleak garden
steady bobcat
#

how many logs did it show? could be a lot of labels and strings

bleak garden
#

testing on a fresh loadin so 0, and I do /clear before

thick terrace
#

it's more likely to be lots of smaller things adding up

bleak garden
#

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

steady bobcat
bleak garden
steady bobcat
#

ongui has been "old" for like 10+ years

bleak garden
#

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

steady bobcat
#

im confused then. draw the ui document and all is good?

bleak garden
#

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

steady bobcat
#

๐Ÿ˜ but why

#

use a single UI system and use it properly

bleak garden
#

it would be easier if there werent 3 of them and information about it wasn't confusing as all hell

steady bobcat
#

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.

bleak garden
#

well I use UGUI a lot

#

plus code to make it work

steady bobcat
#

ongui is an old immediate mode gui system where you have to re define and create the ui on each draw

bleak garden
#

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'

hexed pecan
#

OnGUI/IMGUI is great for quick and dirty debug UI

steady bobcat
#

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

bleak garden
#

alright I'll go back in time 4 months and tell myself to research it xD

steady bobcat
bleak garden
#

I'm more of a 'code now, ask questions later' kinda guy

thick terrace
#

sometimes the answer to those later questions is "you shouldn't have done that" ๐Ÿ˜›

steady bobcat
#

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.

bleak garden
#

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

hexed pecan
#

I extracted your cat's footprint from this

robust berry
#

omg

sleek bough
#

@bleak garden Don't post memes here

#

!warn 186870134672064512 Don't post memes, don't spam the channel.

tawny elkBOT
#

dynoSuccess exiym has been warned.

sleek bough
#

@bleak garden Keep clowning

elfin tree
bleak garden
#

I did manage to catch the serialization taking 400 ms

edgy ether
#

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...

lean sail
# elfin tree No, was just curious.

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

cosmic rain
#

If it is, it would obviously happen in different places at different times

lean sail
bleak garden
#

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;
    }
}
cosmic rain
cosmic rain
thick terrace
#

how often is it running? it looks like it's in Update, nearly 500kb is a big allocation to be doing frequently

bleak garden
#

it should only run once per item to serialize. So if I have like 8 items in my inventory 8 times

cosmic rain
#

Why do you need to serialize a texture anyway? Is it generates at runtime?

thick terrace
#

right, but how often does the serialization happen

#

it's somewhere in the Update loop based on this?

bleak garden
#

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

thick terrace
#

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 ๐Ÿ˜…

cosmic rain
bleak garden
cosmic rain
#

That doesn't explain anything

thick terrace
#

the first step would be, don't do that

cosmic rain
bleak garden
#

they are existing assets

cosmic rain
#

Then why duplicate them?

versed pagoda
#

Save when the game ends or on some loading screen

bleak garden
#

what if the game crashes?

lean sail
versed pagoda
#

You shouldn't be saving things on runtime or on update

lean sail
#

every orb does not need to run that logic, and they shouldnt have access to saving

cosmic rain
bleak garden
cosmic rain
thick terrace
cosmic rain
#

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.

steady bobcat
#

well this is interesting to read
never seen someone save an asset as a string before

bleak garden
#

well here's my JSON, yea it's storing the pictures for all the items in the inventory

steady bobcat
#

plz be joking

bleak garden
#

maybe it will work with UniTask or newtonsoft

hexed pecan
#

Isn't it clear already that you shouldn't be doing this at all?

bleak garden
#

of course

steady bobcat
#

to be clear this is shit and will always perform badly

thick terrace
#

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

steady bobcat
#

If you want runtime change-able icons or something you should load them separately and ref them smartly throughout this inv json.

bleak garden
#

some things are still lagging even with 0 items in the inventory but yes I'll have to get the sprites a different way

steady bobcat
#

use Resources, Addressables or just some serialized list and reference them with their name/address

versed pagoda
bleak garden
#

I thought you couldn't serialize a sprite

versed pagoda
#

Why would you want to serialize a sprite my guy

#

It's not making sense

bleak garden
#

well I don't think you even can

steady bobcat
#

its a unity serialized reference TO THE ASSET

#

can be anything (almost), audio clip, texture2d, material, shader...

lean sail
#

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

bleak garden
#

genius though right?

lean sail
#

not in the slightest

bleak garden
#

I paid for the CPU I'm gonna use the CPU

versed pagoda
#

Bad thinking

cold parrot
thick terrace
vestal arch
bleak garden
steady bobcat
#

Load json -> get id of item -> find item def -> get sprite from item def -> ??? -> profit.

versed pagoda
#
[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();
  }
}
vestal arch
lean sail
versed pagoda
#

It's called when the scriptable is created

#

So it attributes a new guid

steady bobcat
thick terrace
lean sail
#

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

thick terrace
#

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

vestal arch
#

ah

versed pagoda
#

Due to recompilation or something else, cant remember right now

thick terrace
bleak garden
#

what does Guid.NewGuid() do

hexed pecan
#

So the whole parroting of "never use constructors with unity objects" is just nonsense apparently

vestal arch
bleak garden
#

so I map GUIDs to each item?

hexed pecan
steady bobcat
#

You can also just put an id yourself that you understand like "pistol" or "shovel"

buoyant marten
#

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);
        }
    }
}
thick terrace
hexed pecan
#

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

steady bobcat
#

unity can be picky what you use or access from some constructors so its kinda shit

versed pagoda
# thick terrace ๐Ÿคท well, field initializers are essentially part of the constructor, so there s...

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)

mossy snow
#

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

stark sun
hexed pecan
#

Or should the lower legs not rotate at all?

#

Show the relevant code, settings and other context.

stark sun
#

that may be the problem

#

Okay I reverted it

hexed pecan
#

Yeah you generally don't want to scale any physics objects weirdly (negative or non-uniform)

stark sun
hexed pecan
#

Invert the axis of the upper leg joint

stark sun
edgy ether
#

Physics.RaycastNonalloc doesn't add things to array in order do it?

hexed pecan
#

No, you'd need to sort it yourself if you need that

languid hound
#

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

edgy ether
#

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)

edgy ether
dense pasture
#

anyone done a bunch of work with Graph editor foundations (experimental i think)? i need to ask some questions before diving into it

long phoenix
#

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

vagrant blade
tawny elkBOT
#

: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

long phoenix
long phoenix
leaden ice
#

so isn't the solution to just disable it before the player enters a car?

long phoenix
dense pasture
#

is it possible to restrict only a certain subset of custom nodes to certain visual scripting graphs?

river swift
#

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. ._.

long phoenix
#

when i click e, this pops up

leaden ice
#

The only reason you would see that is if you're rendering your game through a RenderTexture for some reason

long phoenix
#

but i cant find it

leaden ice
#

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

long phoenix
leaden ice
#

sounds like a really weird setup

long phoenix
#

.-.

edgy ether
#

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

leaden ice
#

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

long phoenix
#

oh good idea, imma try that, thx

leaden ice
#

cough use Cinemachine cough

long phoenix
#

doesnt work

#

same error

#

im feeling dumb rn ๐Ÿ˜ญ only bc of a car ๐Ÿ’€

#

ik ๐Ÿ˜ญ its everything of the car :P

#

lol

edgy ether
# leaden ice It might help if you explain what you're trying to do and what the actual issue ...

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.

leaden ice
#

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

edgy ether
#

ah ok sec

long phoenix
#

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

edgy ether
#
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)

leaden ice
#

I find it very hard to believe that Vector3.up aka (0, 1, 0) is the correct axis

edgy ether
#

oh ๐Ÿ™ƒ

#

lmao

leaden ice
#

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

edgy ether
#

aaaaaah

leaden ice
#

so:

NormalAngle = Vector3.SignedAngle(hit.normal, Vector3.up, Vector3.back);```
#

the axis is the normal of the surface the paper is resting on

edgy ether
#

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

buoyant marten
#

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

lean sail
#

I havent used them myself, but I think wheel colliders already have this functionality built in

forest patrol
#

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

GitHub

Contribute to apple/unityplugins development by creating an account on GitHub.

steady bobcat
#

always found it strange how these are distributed...

steady bobcat
strange rapids
#

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.

winter bramble
#

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?

cosmic rain
ocean hollow
cosmic rain
# strange rapids

You'll need to expand the hierarchy more. This only tells us that the issue is related to rendering.

cosmic rain
# strange rapids

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.

cosmic rain
# strange rapids

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.

strange rapids
#

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

steady bobcat
#

What is the Tri count for a frame?

#

And is there a lot of overdraw?

cosmic rain
#

It might be something else, we need to see the profiler data.

cosmic rain
strange rapids
steady bobcat
#

Ah I presumed it was also waiting for the GPU but this shows it's not doing much

cosmic rain
# strange rapids

Not many draw calls either. Need to see the profiler hierarchy for the full picture.

strange rapids
cosmic rain
cosmic rain
steady bobcat
#

I was lazy and did not open the screenshot fully (on mobile)

cosmic rain
#

The one you provided earlier expands too much. Just keep it expanded to the camera level.

strange rapids
steady bobcat
#

15ms physics ๐Ÿ˜ฎ

strange rapids
#

unity recommended frametime is 16ms or ??

steady bobcat
#

16ms is 60 fps
1/60 = 0.016

leaden ice
#

1 / target framerate gets your frame budget

#

if you target 144hz you need 1/144

strange rapids
#

ok

cosmic rain
# strange rapids

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 ๐Ÿค”

steady bobcat
#

@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.

cosmic rain
#

Also, shouldn't that be on the render thread?๐Ÿค”

strange rapids
#

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

cosmic rain
#

6ms for rendering is still arguably high. But I guess it depends on your game and frame time budget

steady bobcat
strange rapids
steady bobcat
cosmic rain
urban talon
#

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

cosmic rain
# strange rapids 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.

strange rapids
hexed pecan
urban talon
#

I dont know how to do it it doesnt have a share button on the website it told me to go

hexed pecan
#

Should probably also show your other movement code and related inspector setup

urban talon
#

what do you think? about it what could be the issue

hexed pecan
#

I only see one script and it looks AI generated

urban talon
#

which one do you see

hexed pecan
#

movementScript1

urban talon
#

so what do you think could be the issue @hexed pecan

lone bone
#

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)?

steady bobcat
#

e.g. manager.OnThing += MyCallback; to sub a member function to an event

leaden ice
steady bobcat
#

c# events are better as only the owning class can invoke them. a UnityEvent can be invoked by anyone.

lone bone
#

Thank you both for the input!

hexed pecan
steady bobcat
#

@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();

lone bone
#

Good to know. At the moment, I don't need it in the inspector. So I'll probably use that for now.

steady bobcat
#

a unity event is just a class instance so this does not apply there

urban summit
#

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>();
    }
}```
leaden ice
sullen urchin
winter bramble
#

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?

urban summit
#

Just a sec I'll upload the correct one

lean pike
#

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.

urban summit
urban summit
rigid island
urban summit
urban summit
# urban summit guys here's the correct video

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>();
    }
}```
rigid island
#

I seen it but looks fine at a glance , thats why i said comment out a line or two

leaden ice
#

the crashing has nothing to do with this script

rigid island
#

most likely its the inspector / GUI crashing (could be a bug)

#

the floatpoint warning seems weird

ocean hollow
#

does your editor also crash when you add the script outside of play mode?

rigid island
#

could be transform.localPosition += new Vector3(transform.localPosition.x + adding onto itself soo much that it goes "out of the map"

urban summit
urban summit
urban summit
urban summit
sullen urchin
#

what happen if you write this
transform.localPosition += new Vector3(xOffset, yOffset, 0);

ocean hollow
urban summit
leaden ice
#

why are you adding the script in play mode though

#

I think it's just a weird bug with doing that

urban summit
leaden ice
#

that tells us something is wrong with adding the script in playmode

rigid island
#

@urban summit did you actually start with script already attached?

leaden ice
#

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

urban summit
leaden ice
#

attach it in edit mode

rigid island
#

so you never tried it with script already on it?

leaden ice
#

then show a video

urban summit
# leaden ice attach it in edit mode

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

urban summit
sullen urchin
#

tell me if it works

leaden ice
#

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

urban summit
sullen urchin
leaden ice
#

but that shouldn't crash the engine

#

that's the weird part

urban summit
#

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

rigid island
urban summit
leaden ice
#

I see why that code is clearly wrong - it just doesn't make sense it would crash Unity ๐Ÿค”

urban summit
#

truly weird ngl

rigid island
#

yeah that part could just be the GUI not being able to handle gracefully

#

bug too

leaden ice
#

my guess is just some weird interaction with a huge position value and some other component

ocean hollow
leaden ice
#

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

rigid island
#

ya normally you just get this but doesnt crash the editor

ocean hollow
leaden ice
#

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

rigid island
#

I would def report this to unity if you can reproduce this @urban summit

urban summit
rigid island
#

they can better investigate it

leaden ice
urban summit
rigid island
urban summit
sullen urchin
# leaden ice true

well but is it not if the the values are growing too large then this error appears (Overflow in memory allocato) ?

leaden ice
urban summit
sullen urchin
#

oh yea right

urban summit
#

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

rigid island
urban summit
leaden ice
ocean hollow
#

are the docs down for anyone else?

#

nvm im not getting a server error anymore but the styling is all messed up

hexed pecan
#

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

vagrant oasis
#

๐Ÿ˜ˆ

steady bobcat
#

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

vestal arch
vagrant oasis
opaque vortex
#

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.

sullen urchin
#

just ask and we will see who can help

opaque vortex
#

How do I paste my code in here, is there some form of comment I need to do add in discord?

sullen urchin
#

well I use pastecord

cerulean grove
#

<@&502884371011731486> I have a user in my dms asking for volunteer work.

opaque vortex
#

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

vagrant blade
sullen urchin
opaque vortex
# sullen urchin 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

shadow wagon
#

!code

tawny elkBOT
opaque vortex
shadow wagon
#

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

opaque vortex
#

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

shadow wagon
edgy ether
#

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?

lean sail
edgy ether
#

cool, i'll try that out

modern epoch
#

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

craggy pivot
#

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
lean sail
craggy pivot
#

Yeah I am.

#

Should I cast it to a GameObject before doing the null check?

lean sail
#

a component isnt a GameObject, i assume casting to UnityObject should be fine, if you dont wanna use Monobehaviour or Component

craggy pivot
#

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)```
stable kayak
#

is there a way to NOT have my ide default to NUnit.Framework when List is mentioned

mossy snow
ocean hollow
stable kayak
ocean hollow
#

what IDE are you using

stable kayak
#

Visual Studio

ocean hollow
#

ive always had to include the using tag. what version of VS are you on

stable kayak
#

VS 2022

rocky jackal
#

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;
    }
}
modern epoch
#

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

devout silo
#

hi

#

i have some buttons i want to press on

hexed pecan
devout silo
#

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?

night storm
#

you should be doing that on everything you dont intend to be clickable

devout silo
#

nahh mann

#

i already tried everything

#

and its tha simple

#

thanks a lo man

small void
#

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.

mild vessel
#

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?

rigid island
#

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

mild vessel
#

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

rigid island
#

which tutorial 2D platformer? on Unity website?

mild vessel
#

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

rigid island
#

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

mild vessel
#

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

rigid island
#

I think in the beginning you might be overthinking it

mild vessel
#

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..

rigid island
#

I would mainly start with smaller bite siszed projects before diving into your dream project and kinda get a feel of the waters

mild vessel
#

May not be possible and I just need to dive in lmao

eager tundra
#

I would recommend just trying things out first and observing the downsides

#

there's isn't really a standard framework that everyone uses

mild vessel
#

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

eager tundra
#

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

rigid island
#

yeah ECS might be adding overcomplication you might not need rn

mild vessel
#

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.

rigid island
#

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

mild vessel
#

Yeah I remember reading somewhere on Reddit that there is some hybrid work there

#

and it's not full DOTS

rigid island
#

ya, DOTS is basically the whole system which includes things that can be used with gameobjects too like Jobs / Multithreading .

mild vessel
#

UniRx is archived, ahhh Aaand found R3.

eager tundra
#

I think R3 is the new one

rigid island
#

speaking of UniTask, unity finally added their own Awaitable class. Something to look into now

#

at least we get proper Async now..

mild vessel
#

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

eager tundra
#

UniTask adds quite a bit more than just async support, some pretty cool stuff there

rigid island
#

hmm need to look into more myself, I just get iffy when having so many dependencies from third party libraries..

eager tundra
#

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

young yacht
#

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

young yacht
#

(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

zinc tartan
#

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

worldly stirrup
#

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;
    }```
final thunder
#

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?

vestal arch
#

!code

tawny elkBOT
vestal arch
#

and don't dump all your code here

#

just the relevant parts

final thunder
#

sorry, my bad

vestal arch
#

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

final thunder
#

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

somber nacelle
#

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

vestal arch
#

and it'll make it much easier to absorb new knowledge and relate that to your current knowledge

thorn crag
#

Is there any way to get a reference to a script assigned to a scriptable object from UnityEngine.ScriptableObject?

lean sail
rigid island
thorn crag
#

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?)

lean sail
# thorn crag i think?

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

tawny elkBOT
rigid island
#

ya show code cause that error doesn't tell us much

thorn crag
#
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

rigid island
#

so GetRandomByWeight() returns an SO ?

#

and what type is Card_Template (class, struct etc..)

lean sail
#

the error is also really just a basic c# error

thorn crag
#

Card_Template is the scriptable object i made, so it is a script

#

i can send that here as well

rigid island
#

whats the return type of GetRandomByWeight();

thorn crag
rigid island
#

ohh ok. cause whatever it is, it isn't a Card_Template which is what the error is complaining about

thorn crag
#

i think it is just "ScriptableObject"

rigid island
#

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

thorn crag
#

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?

rigid island
#

and does GetRandomByWeight(); return an individual Card_Template

#

show the function

thorn crag
#

am i allowed to??? it is an asset i got off the asset store? idk if i am allowed to show it's code?

rigid island
#

if its a custom asset how does it actually return a class you made

lean sail
#

you would just have to cast it to the SO type which is exactly what the error tells u

thorn crag
# rigid island if its a custom asset how does it actually return a class you made

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;
        }
rigid island
#

oh its a generic

rigid island
#

or do (MyClass) thingReturned

thorn crag
#

like this: Test_Card = All_Cards_Weight.GetRandomByWeight() as Card_Template; ?

#

It worked!

rigid island
thorn crag
#

thank you :D

lean sail
#

if its generic that means you should probably be providing T at some point but not really sure how you've set that up

rigid island
#

its an asset normally you have that in the arguements no?

#

public T GetRandomByWeight<T>(T myData)

vestal arch
#

well seems like it's the class that's generic, no?

rigid island
#

maybe? i only see the return value is generic

vestal arch
#

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

lean sail
#

Yea it would be like MyClass : MyAsset<MyClass> i assume

#

in the definition of the SO

shell scarab
#

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.

chilly surge
#

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);
cedar terrace
#

I think I fucked it up atwhatcost

#

I don't think I was supposed to put a while statement there notlikethis

rigid island
cedar terrace
#

no gifs ig ๐Ÿ˜”

somber tapir
cedar terrace
#

okay ๐Ÿ‘

rigid island
#

alt + f4

cedar terrace
#

I just made animator spaghetti I am NOT doing all this again ๐Ÿ’”

rigid island
#

normally assets are saved

#

not scene objects

cedar terrace
#

hell yeah batman

#

thank you man ๐Ÿ™

hushed plank
#

can someone check for capitalization errors im bout to blow

somber nacelle
tawny elkBOT
hushed plank
#

sorry dont have discord on my laptop :( i shall get it

rigid island
#

just you know, as long as you don't take photos of a screen. thats painnn

edgy ether
#

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.

rigid island
#

is there a question here?

winter chasm
lean sail
edgy ether
#

oh i'm very sorry.

edgy ether
# rigid island is there a question here?

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

lean sail
#

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

edgy ether
#

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)

edgy ether
rigid island
#

if code isn't working or giving correct result should post here before deleting it completely

rigid island
#

something like this i think.. Array.Sort(hits, (a, b) => a.distance.CompareTo(b.distance));

edgy ether
rigid island
#

and => is just replacing a delegate/method

#

long version

Array.Sort(hits, delegate (RaycastHit a, RaycastHit b)
{
    return a.distance.CompareTo(b.distance);
});```
edgy ether
rigid island
#

=> depends on the context in c# yeah its a bit confusing at first

edgy ether
rigid island
#

"type inference" i think is technical term

#

they're not vague

edgy ether
rigid island
#

oh good ๐Ÿ™‚ glad it helped

edgy ether
#

Ah so it writes the type without having to specify the type

rigid island
#

it knows the type without declaring it again

#

coming from the array here , array is Raycasthit (a,b) have to be Raycasthit

edgy ether
#

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

rigid island
#

yeah its a bit confusing at first also because it has multiple uses

edgy ether
#

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?

rigid island
#

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

edgy ether
#

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!

steady bobcat
#

e.g. array is 6 big but you usually only get 2-4 results.

lilac frigate
#

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?

karmic stone
#

Quick question about csharp events, can you assume they are immediatly executed before the next line (after event.Inkoke());

naive swallow
#

Nothing is asynchronous unless you very specifically designate it as so

#

Code runs one line at a time, top to bottom

karmic stone
#

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

steady bobcat
#

Yes, when you call the event all the subscribers are called one after another.

naive swallow
#

Even coroutines are single-threaded

karmic stone
#

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.

shadow wagon
#

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

steady bobcat
#

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)

somber nacelle
naive swallow
steady bobcat
edgy ether
steady bobcat
edgy ether
steady bobcat
stone kraken
#

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.

stone kraken
stone kraken
#

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

rigid island
#

it works for other things but not methods ๐Ÿคทโ€โ™‚๏ธ Could be something to report on the github

edgy ether
edgy ether
rigid island
edgy ether
#

@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.

stone kraken
rigid island
#

keep in mind this is for Visual Studio, not VSCode

elfin quest
#

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)

rigid island
elfin quest
#

Sorry, I've never used that channel and it's less active, so I thought I'd give it a try but ur right.

rigid island
#

how is โ unity-talk less active? its literally the most active channel..

naive swallow
#

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

elfin quest
#

MB sorry

#

Fair enough

rigid island
steady bobcat
#

vs code is just worse at this compared to visual studio

#

if on windows just use VS

stone kraken
#

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

rigid island
stone kraken
#

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 ๐Ÿ˜…

rigid island
stone kraken
#

Done!

rigid island
#

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

stone kraken
#

If a suggestion is more than a couple down I like clicking ๐Ÿคทโ€โ™‚๏ธ ๐Ÿ˜… haven't made it to the keyboard-only elite yet ๐Ÿ˜›

sturdy saffron
#

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

robust dome
#

of course

#

use a Coroutine for example

hexed pecan
#

Coroutine is coupled with Update/FixedUpdate though

lean sail
sturdy saffron
#

oh ok then

#

ima ask there but i dont really want to use a framework, ive already spent a lof of time doing netcode

robust dome
#

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

lean sail
sturdy saffron
#

i was asking it here cause its not really a networking specific thing its an engine specific thing

hexed pecan
#

Not sure if it's helpful with networking, but the PlayerLoop API exist, might wanna take a look

lean sail
#

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

shadow wagon
#

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

shadow wagon
#

ive never written them out of order before

rigid island
#

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

steady bobcat
#

It can be used also to specify some optional args too if the order is not ideal