#archived-code-general

1 messages · Page 430 of 1

rustic agate
#

I found out that its the source of the memory leak

#

thats about it

#

I dont know why or how to solve it

cold parrot
#

what is?

#

the nested parallel for loops?

rustic agate
#

That looks awful

cold parrot
#

you should not do that

rustic agate
#

yeah I requested AI to do chores of writing 3 for loops

cold parrot
#

there should only be one parallel for loop

rustic agate
#

expected for it to have just one Parallel

#

yeah

#
        {
            for (int y = 0; y < 1000; y++)
            {
                for (int z = 0; z < 1000; z++)
                {
                    voxels[x, y, z] = new Voxel(VoxelType.Air);
                }
            }
        });```
#

much better

cold parrot
#

just chunk the loop by one coordinate, no need to make a thread for each index

rustic agate
#

huh..

#

I think I am finding something peculiar

cold parrot
#

you could also use a concurrent dictionary

rustic agate
#

wait

cold parrot
#

needs fewer locks

rustic agate
#

^ desparate attempt to get help

#

I have no idea how to resolve this

vestal arch
#

if you could put your words into text that would help

rustic agate
#

I occupied 2000x2000x2000 spaces

#

finished the running the scene

#

it won't release the memory

#

absolutely making me insane

vestal arch
#

perhaps the gc just hasn't run? thonk

rustic agate
#

All the source code is here

#

I mean maybe?

#

MAYBE?!

#

I DONT KNOW

#

but it slows down my computer

#

so it should run the god damn GC

#

also I tried to call

#

manuall GC collect

#

but I guess it could be just being lazy?

#

I dont know

#

someone help me. I think I am gona take a break for now

vestal arch
#

what happens if you run the scene again?

rustic agate
#

oh...

#

its not allocating more memory

#

oh wait

#

could it be that it just gave my unity scene those chunks of memory expecting the program might run it again?

vestal arch
#

oh that is possible

rustic agate
#

thats super interesting

#

I guess if I allocate x amount of memory in name of program y, the x amount of memory will be used for y program as long as it runs unless other program requests to allocate memory for themselves?

#

typo

cosmic rain
#

If GC doesn't collect stuff, then you're still referencing it

cosmic rain
rustic agate
#

I literally don't reference to it though, it is dictionary of struct and the scene is terminated

cosmic rain
#

What does it have to do with the scene?

#

Where does the dictionary live?

rustic agate
#

GameObject

cosmic rain
#

Do memory profiling

rustic agate
cosmic rain
#

It has some memory profiling capability, but it's better to use the dedicated memory profiler package.

#

You can also see allocations and frees in the regular profiler

rustic agate
#

Unity does not often release the memory pages allocated to the managed heap when it expands; it optimistically retains the expanded heap, even if a large portion of it is empty. This is to prevent the need to re-expand the heap should further large allocations occur.

cosmic rain
#

This would be visible in a memory profiler

icy galleon
#

TLDR : A same text, when the localization is set to french, will sometimes get displayed in french but sometimes in english (main locale) when fetched from the Table

Hi ! I hope everyone is doing great 😊
Feel free to redirect my question if it is not the place to post it!
I've been trying to set up a localization system for the game I am working on and I have been running into some issues for the past few days :

  • I have 2 locales, english as main and french
  • I am using Unity 2022.3.18f

As an example of the issue, I have scriptable objects for dialogues. I have a function that reads said dialogues. When I set the localization to french, a same dialogue will sometimes be displayed in french (as of now, the message saying there is no translation yet) but sometimes will be displayed in english even if the localization is set to french.

I have tried :

  • InitializationOperation.WaitForCompletion()
  • Preloading everything
  • GetLocalizedString and Async
    Initialize synchronously
    ...

and a bunch of others things as I've tried a good chunk of what could be found online

Would anyone know where the issue could be coming from ? Here are the functions and settings :

#

In DialogueSO.cs, in the OnValidate() function :

#
public void GenerateLocaleKeys()
{
    //Localization
    if (LocalizedDialogues == null) return;
    var table = LocalizedDialogues.GetTable();
    if (table == null) return;
    for (int i = 0; i < DialogueLines.Count; i++)
    {
        // string keytodelete = $"iddialogue{this.name}{i + 1}";
        // if (table.GetEntry(keytodelete) != null)
        // {
        //     table.RemoveEntry(keytodelete);
        // }

        string key = $"id_dialogue_{this.name}_{i}";

        if (table.GetEntry(key) != null)
        {
            // If it exists, do nothing
        }
        table.AddEntry(key, DialogueLines[i].LineTxt);
        DialogueLines[i].LineId = key;

    }
    EditorUtility.SetDirty(this);
    //
}```
#

In DialogueUI.cs, the call to get the right string to display :

#
public IEnumerator WriteDialogue(DialogueSO.DialogueLine line)
{
    string linetxt = LocaleStringFetcher.FetchLocaleString(this.gameObject.name, "LocalizedDialogues", line.LineId);

...
}
#

The function used to fetch the string :

#
//LocalizedString table and string
public static string FetchLocaleString(string objname, LocalizedStringTable table, string key)
{
    if (table == null || key.IsNullOrWhitespace())
    {
        Debug.LogError(objname + ": LocalizedStringTable or key is null");
        return "";
    }
    //LocalizedString ls = new LocalizedString(table.TableReference, key);
    //var operation = ls.GetLocalizedStringAsync();
    var operation = LocalizationSettings.StringDatabase.GetLocalizedStringAsync(table.TableReference, key, LocalizationSettings.SelectedLocale);
    operation.WaitForCompletion();
    string res = operation.Result;
    if (res.IsNullOrWhitespace())
    {
        // If it does not exist, log an error
        Debug.LogError(objname + " : couldn't find localization id " + key + " in " + table.ToString());
    }
    return res;
}

//OVERLOAD : string and string
public static string FetchLocaleString(string objname, string table, string key)
{
    if (table.IsNullOrWhitespace() || key.IsNullOrWhitespace())
    {
        Debug.LogError(objname + ": LocalizedStringTable or key is null");
        return "";
    }
    //LocalizedString ls = new LocalizedString(table, key);
    //var operation = ls.GetLocalizedStringAsync();
    var operation = LocalizationSettings.StringDatabase.GetLocalizedStringAsync(table, key, LocalizationSettings.SelectedLocale);
    operation.WaitForCompletion();
    string res = operation.Result;
    if (res.IsNullOrWhitespace())
    {
        // If it does not exist, log an error
        Debug.LogError(objname + " : couldn't find localization id " + key + " in " + table.ToString());
    }
    return res;
}
#

And my settings

#

I would be eternally grateful to anyone who could help or direct me towards the right way of doing this. I am so sorry that my first message ever in this discord is a call for help, but I can assure you that I truly want to improve and am not just looking for an easy solution to my problem 🙏

#

Also it is the first time I ever post for help rather than just reading everything I can find, if my message isn't good (formatting, way of speaking...) in any way, feel free to indicate that to me !

stable osprey
#

so people that CAN help can continue reading, and others that can't might wanna skip

icy galleon
stable osprey
#

second, since the operation seemingly completes (?) and ANY string is returned, seems the issue would be in GetLocalizedStringAsync (?)

#

@icy galleon if NO localization methods ran, would the english text still appear?

#

As in, is the english version of the text baked on the UI elements as the default value?

icy galleon
stable osprey
#

well if the operation ACTUALLY completes, there's no room for doubt -- GetLocalizedStringAsync just returns the wrong string

#

sec

#

yeah you should switch to GetLocalizedString for production anyway.. less lines of code and you're indeed in non-async context

icy galleon
stable osprey
#

your code looks a little too complex though

#

why not just this?

public IEnumerator WriteDialogue(DialogueSO.DialogueLine line)
{
    string txt = new LocalizedString("LocalizedDialogue", line.ID).GetLocalizedString(line.Text);
    ...
icy galleon
#

I wanted to try to have a main function that does this and that I could just call, because I use it for a lot of different UI elements and I didn't want to copy paste code everywhere

#

Do you think I should just give up on that ?

stable osprey
#

not necessarily, but I think you should always try to make something work first with code as simple as possible before moving on

stable osprey
icy galleon
#

I'll try to see if I can do that, thank you so much

stable osprey
#

np gl ^^ I think it'll make the code cleaner but not sure if it'll fix the issue, so I'm still looking around lol

icy galleon
icy galleon
#

I just started an internship at a tiny studio, if I can't fix it until then I have a weekly on Monday, I'll try to see if my tutor can help 😊

stable osprey
#

awesome ^^ and gz on the internship

zinc parrot
#

Say you had a compute buffer of length 6k that just stores the localtoworld transform matrix of 6k physics gameobjects
Say 2k of these objects are constantly moving, but their indexes in the compute buffer are random
What would be the FASTEST way to update these matrices in the compute buffer with the actual new transform of each object that has moved?

leaden ice
#

unless the order of the result doesnt matter in which case you overwrite the whole buffer each frame or something

zinc parrot
#

yes thats fine
My main question is the fastest way to update the GPU-side data with the CPU matrices

stable osprey
#

yeah was thinking if you actually have the indices on CPU, you can pass them along as a parameter to the compute shader

zinc parrot
#

I know the indexes they go to
I just want to know if theres something faster than standard buffer.setdata(transformarray)

zinc parrot
#

but isnt that only really useful for contiguous writes?

#

not random-writes?

#

the gameobject transform matrices dont already exist on the GPU from unity stuff right?

leaden ice
#

Looks like you can probably pass in the size of the whole buffer and write to whichever indices you want in the nativearray

#

Note this is a write-only array

#

The returned native array points directly to GPU memory if possible. If it it not possible to write directly to GPU memory, the returned native array points to a temporary buffer in CPU memory. Whether it is possible to write directly to GPU memory depends on many factors, including buffer mode, active graphics device, and hardware support.

Because of this, the contents of the returned array are not guaranteed to reflect the data content of the GPU side buffer. You should therefore use the returned array only for writing to, and not for reading from.

#

It might jsut be faster to rewrite the whole buffer regardless

#

with the new data

#

like clear and rewrite. It really depends

stable osprey
#

Unity just queues stuff to the GPU and doesn't wait for them until a sync is needed, so it might still run in parallel, even if you queue multiple commands.
But -- did you try something like output[indices[idx]] = values[idx]; in a compute shader and found it slow?

dark salmon
#

Sorry— code used during custom inspector and property drawers should be here or should it be in #📲┃ui-ux?

vestal arch
dark salmon
#

Thanks!

late lion
astral oriole
#

Hey yall, a weird thing is happening w my project when I install "Advertisement Legacy" for Ads, all of a sudden the project is not being able to read that jar JDK file

#

Even though I changed nothing. I haven't been able to find anything online about this issue either.

copper crescent
#

yoo, hi! I have a problem with Unity 3D i have a capsule collider for the player and box colliders for platforms, but when the player reaches the edge of the platform it jumps a little on each edge, so if they are next to each other it destroys the movement feeling, has anyone faced this issue before? how to solve it?

fast nacelle
#

@copper crescent are you using continous or discrete on your rb?

fast nacelle
#

could you send a video of what the hop looks like?

#

also @copper crescent how are you checking for the ground/wall etc

copper crescent
fast nacelle
#

are you checking walls too?

copper crescent
#

if you check the Y on the video you can see the weird behaviour

fast nacelle
#

interesting thanks for sending

copper crescent
#

it's the connection of different box colliders as far as i know

#

which is the problem

fast nacelle
#

im assuming all the y's of the colliders themselves are the same, correct?

#

and the ys of the platforms

copper crescent
#

correct, platforms have the same Y pos

fast nacelle
#

and the colliders all have the same y offset?

#

could you control click two of the platforms and zoom in so I can see the colliders next to each other?

copper crescent
#

something like this?

fast nacelle
#

one sec ill show you what i mean im explaining it bad

#

if you have a clear side angle like this :

#

and include the inspector if possible

copper crescent
#

ok, as it's only the top plane visible (realy thin) is that fine picture?

fast nacelle
#

ya thanks!

#

are those built in colliders like when you bring a plane in or did you add and shape them yourself?

#

a quick fix would be just to create a new empty and add box col component and then you can bend and shape it yourself, or you could edit the colliders and look at the y offsets and size to see if maybe the discrepancy is there, otherwise maybe try temporarily changing your players collider to a box collider so that you can see exactly how its getting stuck more vividly with the flat bottom. also you could comment out the ground check just to see if the raycast is affecting it. you could also go ahead and mess with slope movement but that can kinda become a headache. i need to go so if anyone else wants to help please jump in but there are some things you can try for right now

copper crescent
#

there is no issue with box collider 😲

fading swallow
#

If i set the speed of an animation state to -1 to play it in reverse, will the event on the motion still trigger when the scrubber passes it?

fast nacelle
#

yay @copper crescent im glad you fixed it!!

cursive moth
#

bump

trim schooner
stable osprey
#

To clarify, is your issue that this solution is Windows-Only, but you want cross-platform?

cursive moth
#

my issue is that it's not working

stable osprey
#

cool. The next screen starts from Screen[0].Width so you can + offsetFromLeft to move it to second display

#

DisplayInfo is helpful for this.

cursive moth
#

it's actually located on the top left, not just left of his main display

#

and i am sure there are countless other combinations people create

fading swallow
stable osprey
#

yeah determining the positions is an issue. But Screen 0 indeed ranges from [(0,0) to (Width,Height)]

bright olive
#

hey guys I have a small technical issue.
Im making a 2d platformer, working on a movement script. I want to have a double jump AND cayote time but they dont seem to work well with each other. Heres the script:

stable osprey
#

and you gotta do all movement with the first screen's bottom-left corner as anchor.

bright olive
#

Idk how to fix it, Im new to all this. When cayote time activates double jump stops working

stable osprey
cursive moth
cursive moth
stable osprey
#

could be. I think it's actually the MAIN monitor that's an anchor, not the 0th on index

#

but it's personally tested that the anchor needs to be 0,0

cursive moth
#

that's what I thought too, I am not so sure anymore

#

his main display is 100% set to the right one in windows settings, yet if I set the window position to 0,0 it moves to his 2nd display

stable osprey
#

maybe his "2nd monitor" is marked as the second display?

#

ah..

#

well my main monitor always was bottom-left even with ID: 2 so maybe I was lucky 😄

#

the repo though will get you covered.. it has bunch of useful stuff in both NativeMethods and WindowHelper

cursive moth
cursive moth
stable osprey
#

there's a Screen parameter

cursive moth
#

oh, I missed that, let me look into it again, thanks

stable osprey
#

they use a dummy point to find the anchor monitor and marks it as primary, though. So maybe it's faulty for your use-case too 😛

toxic schooner
#

window.SetWindowPosition((int)Math.Round(coordinates.X), (int)Math.Round(coordinates.Y),
(int)Math.Round(

stable osprey
#

@cursive moth I recommend trying to get something to work in WPF first before investing time into writing something specifically for Unity

#

the WpfScreenHelper package is available via nuget there so you'll be able to find out if it works AS IS in a few minutes

cursive moth
#

oke, will do

#

I also found an older post from a unity dev that suggested some windows api, it's not too bad I was just wondering if it's possible to do it w unity api

quick roost
stable osprey
#

well it may be possible if you make your app "Continue running in background" but that might be expensive -- Unity uses CPU and GPU even on background

cursive moth
stable osprey
#

uh. Have you tried Display.displays[id].Activate(), then? 😛

cursive moth
stable osprey
#

yup

cursive moth
# stable osprey yup

I was doing something similar, however, issue is, when I move the app to the background layer(requires windows api), I also gotta set it's position and scale it to fit the display.
That moves it to the 2nd display regardless of what I did with the Display/Screen class:

public static void MoveToDisplay(int displayIndex = 0, Vector2Int position = new())
{
    if (displayIndex < 0)
    {
        Debug.LogError($"{DebugPrefix}Display Index is less than 0, returning: {displayIndex}");
        return;
    }

    List<DisplayInfo> displays = new();
    Screen.GetDisplayLayout(displays);
    
    if (displayIndex >= displays.Count)
    {
        Debug.LogError($"{DebugPrefix}Display Index is too high, returning: {displayIndex}");
        return;
    }

    Screen.MoveMainWindowTo(displays[displayIndex], position);
}
#

So I think I have to get actual coordinates of that display in order to be able to send it to the bg layer properly

quick roost
#

@bright olive I think you'd also want to change coyoteTimeCounter to 0 inside of that if statement so that the player can't quickly press the jump button twice within the coyote time window to get a free extra jump

bright olive
quick roost
#

I'm not sure my fiance would approve lol. Glad it worked

bright olive
#

Lol thanks for the help either way. Im not a programmer, I just use tutorials, taking parts of scripts and glueing them together to make my own. So this has been bugging me for days...

#

I try to adjust what I understand but coding is... Yeah...

quick roost
#

If you wrote code then you're a programmer. We all gotta start somewhere. Also you should look up a tutorial on how to use a debugger with unity. If you are using Visual Studio, the debugger in it works great with Unity. it allows you to insert breakpoints in your code which pause your game when it hits a certain line and you can let the code run one line at a time and see what all your variables are. Super helpful for debugging

bright olive
#

Damn, I didn't know that. Definitely gonna use that now. I only have one last question

bright olive
#

I try to do what I do as best as I can, so I would like to implement your help if it makes the game smoother

quick roost
bright olive
#

I should delete the whole "if" and instead just set coyote time counter to 0?

quick roost
#

no at the bottom of the if statement I added the line coyoteCountTimer = 0;

#

@bright olive still inside the if statement. The reason is that after you jump, you don't need coyote time anymore, so you don't want the player to be able to jump using coyote time after they've already jumped, if that makes sense

#

in that code block look where it says //new line here

bright olive
#

I see, thanks for the info once again. Have a great night man

mighty junco
#

Which makes more sense for a parkour game, rigid body or an fps controller?

mighty junco
shadow wagon
#

those two arent mutually exclusive, a fps controller is something youd build yourself

quick roost
#

I think they're referring to the character controller

mighty junco
#

Sorry if I’ve got it really wrong, it feels like every forum I look at has a different view on it

quick roost
#

@mighty junco I think one of the big differences is that character controller has a harder time interacting with physics objects. So if you wanted your character to be able to run into boxes and have the boxes get knocked over or something like that, it might be more complicated with a character controller.

quick roost
#

I don't do a lot with fps type games though so I could be missing some details but that's what I remember being one of the major differences

mighty junco
exotic crypt
#

Hi guys, im following a tutorial which describes customizing the PlayerLoopSystem and for whatever reason when running this initialize method (which is basically the only thing ive done so far) internal static class TimerBootstrapper { [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)] internal static void Initialize() { PlayerLoopSystem currentPlayerLoop = PlayerLoop.GetCurrentPlayerLoop(); PlayerLoopUtils.PrintPlayerLoop(currentPlayerLoop); } } PlayerLoop.GetCurrentPlayerLoop() returns null.

#

unfortunately documentation isnt very good for this sort of thing so was wondering if anyone has come across this

stable osprey
#

What would happen with just [RuntimeInitializeOnLoadMethod]?

exotic crypt
#

i did think this and tried BeforeSceneLoad with a similar result. Attempting the recommended attribute also provided a null error.

#

I am going to just create a playerSystemLoop and append the subsystems that unity is giving me as seen in my screenshot above

stable osprey
#

well anyway you don't need that to customize the player loop -- you can just SetPlayerLoop 😛

exotic crypt
#

Agreed 🙂 this is probably the way im going to go. I appreciate the help though guys

stable osprey
#

although the default player loop should be enough -- just saying 😄

#

np, gl

exotic crypt
#

i guess im asking - is this a massive code smell that i should avoid 😂

stable osprey
#

Yeah, I'd say so. For educational purposes it should be fine, but I can't think of any reasons it'd be needed during production.

#

Worst case you can set up a system that utilizes [DefaultExecutionOrder(..)] nicely.

#

Also, it's not as extensible as you may think 😆

exotic crypt
#

Ah , i missed that in the Docs lmao. Ill probably just go back to my old methods of doing this sort of work then and leave the deep dark world of unity internals alone 😆

blazing smelt
#

How would I go about rendering a billboard sprite procedurally? E.g. in a similar way to Graphics.DrawMesh() or GUI.DrawTexture()? I used the latter but it appears over everything else in the scene, and I'd like it to appear in world space and be covered up by things in front of it. I'd also prefer not to spawn a bunch of prefabs and mess around with object pooling.

stable osprey
blazing smelt
stable osprey
#

ohh I see..

#

from how I understand your use-case though simply "graphics programming in Unity" isn't gonna cut it 😅 You'd need to rewrite a substantial part of a rendering engine to make Z order possible

#

I can explain my train of thought in case something clicks, though.

#

So, with post-processing you could manage something similar but it's not gonna be easy, since you'd be writing pixels on the top of the screen -- you'd need to detect which pixels you shouldn't write on.

#

Then you could go with geometry and UVs, rendering all billboards on one go, but the object's center would likely need to always be in the screen (there should be ways to deal with this actually).

stable osprey
#

I just realized you could reuse the same mesh + material and just do separate draw call per billboard.

blazing smelt
stable osprey
blazing smelt
#

but yeah I can just set up an array of matrices, then for each thing that needs to be drawn that frame I can populate an array entry and increment the index by one. Then I just input the array and count

stable osprey
#
Matrix4x4[] matrices = billBoards.Select(GetBillBoardMatrix).ToArray();
Graphics.DrawMeshInstanced(mesh, 0, material, matrices);

Quaternion GetLookAtCamRotation(Transform billboard) { ... }
Matrix4x4 GetBillboardMatrix(Transform billboard) { return Matrix4x4.TRS(billboard.position, GetLookAtCamRotation(billboard), billboard.lossyScale); }
blazing smelt
#

Matrix4x4 matrix = Matrix4x4.TRS(position, rotation, doorSize) sure beats Matrix4x4 matrix = Matrix4x4.Translate(position) * Matrix4x4.Rotate(rotation) * Matrix4x4.Scale(doorSize)

stable osprey
#

damn

mossy flare
#

I have an animated character to ragdoll transition, on some ragdolls it freaks out when the transition happens and spazzes out into space

#

What the fuck causes this?

earnest epoch
mossy flare
#

Right

#

I suspect it's something to do with constraints being violated with whatever animation is played, but I have no idea how to fix that

#

How do I just get good, clean ragdolls like I see in so many games that smoothly go from animated to simulated?

earnest epoch
mossy flare
#

Animator gets disabled, loop through rags and unkinematic them

#

That's all, really

earnest epoch
#

Hold up; maybe here's a better question: can you spawn an object in ragdoll state without it "freaking out"? @mossy flare

mossy flare
#

Sorry for the recording. OBS really doesn't want to work on windows.

earnest epoch
# mossy flare

My best guess is that your forces are something out of control. Have you tried setting masses to something very high to see if they respond more reasonably?

chilly lake
earnest epoch
mossy flare
#

it's definitely not without issue, but none of them freak out like in the video

#

I think I was doing that before and removed it for some reason. One second

mossy flare
#

It doesn't seem to make a difference

earnest epoch
#

Can you show an example of a character spawning in ragdoll and collapsing exactly as you expect them to?

quick roost
# mossy flare

Could it be caused because when you make all the rigidbodies dynamic from kinematic they are colliding with each other? So they're snapping to a place where they aren't colliding which gives a lot of velocity

mossy flare
#

Sorry I went on a rabbithole of solving 10 different other bugs because everything started falling apart

mossy flare
mossy flare
#

The back still kind of breaks and it certainly does not look as clean as I'd like but it doesn't shoot itself into space

#

I would have thought this is a far more common problem than it was, and that there were common solutions for it. What the hell am I doing wrong? this has happened every time I've made a ragdoll with an animation

quick roost
#

@mossy flare This is outside of my wheelhouse so I can only guess that it's something with the colliders overlapping or the joints between the limbs not being misconfigured in some way

mossy flare
#

I just want a ragdoll they were doing this shit in like 2010

west lotus
lean sail
# mossy flare I just want a ragdoll they were doing this shit in like 2010

did you follow a guide on it? because there really isnt much you need to do. skimmed a bit above, but if your rb's were previously kinematic then its not like you need to assign 0 to the velocities.
its basically just a matter of disabling your previous movement system and enabling all the colliders + rb

mossy flare
#

Of course. Otherwise it wouldn't work at all.

#

Well now I know for sure that it is an issue with the joint limits. I disabled those and the rag folds like a doll.

#

Perfectly smooth

quick roost
#

nice

lean sail
#

I was going to say, is there a reason you chose configurable joints? Because usually the ragdoll wizard gives you character joints

mossy flare
#

That just creates another issue though. There should be limits. How do I reocncile that with animations that don't seem to want to follow human anatomy?

lean sail
#

configurable joints are way more complex and a pain in the ass to setup properly

mossy flare
#

Drive is needed

lean sail
#

ah ok, ive done the same before. Well then the issue is simply in the setup of your joints. Yes you need limits, maybe the forces you have are way too high or the settings are wrong. I played around with configurable joints and active ragdolls for far too long..

#

it really is just a complete pain

mossy flare
#

Since you likely know, should I enable projection?

#

I heard about it when researching this issue

mossy flare
#

I doubt that would look very natural

lean sail
lean sail
# mossy flare I doubt that would look very natural

its not gonna look natural anyways, trust me when i say the entire process is going to be just trial and error. I kinda question what you mean by an active ragdoll with animations though, these 2 things don't really make sense together. Are you using the ragdoll for example when its dead, or is this something thats on all the time?
also im not sure what you mean make the limits springs instead of hard. I dont remember that being an exact option, rather the options being like "limited" and then setting spring values

#

god going through the docs for configurable joints just reminds me exactly why i stopped. theres like no good resources on it either. Games that made active ragdolls like human fall flat have their own system in place

mossy flare
#

god it looks horrifying without limits

lean sail
# mossy flare active ragdolls

i see, not a bad use case for it. much easier than having one walk around at least.
What i did, make a new object with your model/rig and use the ragdoll wizard to create a ragdoll. Copy the values from the character joints into your configurable joints and at least you'll have semi decent limits already

#

then you can customize it further with the gizmos which is slightly a pain but not so bad

mossy flare
#

I manually configured all of the limits to match human anatomy. I guess that was a waste of time.

#

Since apparently animations don't respect human anatomy

lean sail
#

its not like there is a definition of what human anatomy is, animations simply move and rotate the objects needed. If they fall outside what you defined for limits, then your limits are likely not correct

#

Either that or your animations would probably look off

mossy flare
#

Consider your forearm. It can't actually rotate on the Z axis, that's your upper arm. It's likely that the animations just don't care about that and animate it anyway for the sake of convenience

#

It wouldn't look freakish or anything

#

I'll probably just get it a bunch of very lenient limits to work with so this issue doesn't happen in the future

#

Thanks for all the help

lean sail
#

I do definitely remember having the same-ish issues as you, but I never had animations. Mine was more when a hand would get stuck inside another object, and the entire body would freak out.
If you need to test it in the future i recommend setting up a separate scene for that. Have objects that move into your ragdoll (to get between the colliders). possibly attach the configurable joint to another collider and shake that other collider around to see how it moves

shrewd igloo
#

Hey I wanna try and learn procedural world generation but it seems very complicated. Anyone have good resources or have advice on what I should be looking into to learn it?

novel nexus
#

can someone help me with some unity errors ill start with the first one. its a double ambigous error (error code: CS0121)

cosmic rain
#

As well as the code line that throws it.

novel nexus
cosmic rain
novel nexus
#

i sent the error message @cosmic rain

cosmic rain
novel nexus
#

well everything was fine before i added a google library and thjen it doesnt work anymore

cosmic rain
#

Must be a library/dll that was included in that google library. You should read instructions of every plugin you add properly.

novel nexus
#

oke, but how do i fix this now

night harness
#

They told you

cosmic rain
# novel nexus oke, but how do i fix this now

Remove the plugin that caused the issue, delete the library folder if there's still an issue. Then read the plugin instructions and requirements properly if you want to add it again.

dense isle
#

Hey guys, I'm trying to implement dynamic button prompts so the user knows what button to press if they change controller type, so TMPro might initially show E to interact when on keyboard, but if the user presses a button on their Xbox controller, it would change to the 'A' button to interact for Xbox controllers. The logic is pretty much already there, but I am struggling with the last part.
I'm relying on using TMPro's 'Default Sprite Asset' in Project Settings > Text Mesh Pro > Settings . If the user presses a button on their Xbox controller, I can successfully change the Default Sprite Asset to be my Xbox_Controls_Sprite_Asset that I have, but the string displayed on screen does not update to reflect this. When I stop and re-run the game, the string does reflect the Xbox button correctly, is there any part I'm missing? I saw a not very conventional method that would FindAllObjectsOfType<TextMeshProUGUI>() and then loop through them and re-assign their spriteAsset to be the correct controller layout sprite asset. It does work but I was wondering if there's any more conventional methods of updating strings to show the correct Default Sprite Asset at runtime?

cold parrot
dense isle
#

Implemented a very basic version and that seems to do the trick! So now it's just relevant strings that have the listen for changes and can update their spriteAsset to the new Default Sprite Asset when needed instead of all strings that shouldn't have to be updated. Many thanks!

crimson plaza
#

Is having a lot of scriptableObjects a point of concern? I just find them to fit perfectly in many use cases, especially configuring static default values

#

I'm not exaclty sure what I expected the alternative to be, just that I find myself having a lot of scriptableObjects for coniguring different items and was wondering if this was the way to go

night harness
#

(Personal experience, not so much professional). ScriptableObjects seem like the objectively best way to handle a lot of stuff but it can become abit of a nuisance iteration and organisation wise so a lot of the times it just ends up being a trade off between what feels more right and what is gonna just be more straight forward

#

regarding your example of static defaults, as someone who is likely way overusing them i use scriptableobjects in place of enums in pretty much every occasion nowadays

latent latch
#

Ultimately, there's not really a problem with ScriptableObjects even if unique instances aren't shared, but they can create a bunch of bloat in your asset directories.

crimson plaza
latent latch
#

Think of a Projectile/Gun class where you are setting these default values. But, is there any instance that you may have a second gun with similar default values? Usually no, so you end up with this unique SO instance.

crimson plaza
#

Ahhh gotcha

#

Would "future proofing" in case these values were used elsewhere later be a good enough argument to still use SOs for this purpose?

latent latch
#

A better example is having like 5 different SOs for a gun object; ProjectileSO, StatsSO, IdentitySO, StatRequirementSOs (just throwing out some bs)

crimson plaza
#

And by nested serializedClasses do you include normal C# classes as well or strictly SO

crimson plaza
latent latch
#

It's not a bad idea, it's just that it can create a bunch of bloat. What happens to me is I end up making a whole directory per gun to contain all these SOs

crimson plaza
#

I've seen people abstract the stats for a gun into a singular scriptableoBject let's call it gunSO, and bulletSO, impactSO, etc etc

crimson plaza
latent latch
#

Prefabs and SerializedClasses

crimson plaza
#

I'll look into serializedClasses

latent latch
#

SOs were actually a newer feature

crimson plaza
latent latch
#

But a prefab workflow and prefab variant workflow was the usual way to do everything

#

Yeah

#

There's also SerializedReferences which is the 'newer' way to construct data classes on the editor, but they were never fully implemented requiring you to make custom editor scripts to get it to display properly. You can technically get a SO workflow without the bloat using them, but it's usually a pain to get it going

crimson plaza
#

Would it be right to say that using prefab variants workflow would've introduced the "whole directory to contain all those gun variants"

#

Rather than SOs

#

What would one use the prefab variant for nowadays

crimson plaza
latent latch
#

They allow you to embed the dataclass directly into prefab and removing the need to have the asset in the directory. This allows you to get the benefit of the polymorphism that you couldn't get with general SerializedClasses

crimson plaza
#

Previously I imagined something along the lines of having a csv/excel sheet contain all the stats you'd put in an SO and have it be built during runtime

crimson plaza
wheat spruce
latent latch
#

Well, it's more than that I forgot to mention, but SOs allow you to have less-derived types to be inserted into these prefabs, while SerializedClasses can only create the instance that's defined.

crimson plaza
#

What do you mean by less-derived types?

latent latch
#

If you derive the SO multiple times, but you serialize as the base abstract type, then you can insert any derived type of that SO onto the prefab

#

SerializeClasses do not get that privilege and you must serialize by that defined type (if you don't use serializeReferences)

crimson plaza
#

I see, then serializeclasses loses some benefits of inheritance

latent latch
#

That's ultimately the problem with them (besides running into problems if you nest too much)

crimson plaza
#

Thank you so much mao!

grizzled vortex
#

are there any tools to profile the process of building a unity project?

#

i could cobble together my own tools with log parsing and platform native profiling tools, but that's a lot of work and before i embark on that quest i'm curious about any existing solutions

unkempt cobalt
#

why is this here

sleek bough
topaz fable
tame yoke
#

can anyone help me out? im currently learning how to program and im trying to make movement. im following a brackeys tutorial (https://www.youtube.com/watch?v=_QajrabyTJc) and im currently 8 minutes in at the end of his first portion of the mouse rotating the body. currently, im facing an error (you'll see down below) but ive followed the code exactly the way it is.. can anyone help?

my code is the first image, brackeys code is the second, and the error is the third image.

steep herald
#

@tame yoke Look at your semicolons

leaden ice
#

Also - premptively- I will tell you this tutorial has an issue. You should remove the * Time.deltaTime because it was a mistake in the tutorial and will lead to jittery rotation

tame yoke
leaden ice
#

correct

tame yoke
#

oop i was missing a semi colon

leaden ice
#

you may need to reduce the mouse sensitivity to compensate

tame yoke
tame yoke
#

ill reduce to 75%

#

thank u @leaden ice

leaden ice
#

whatever number you have before you'll want to reduce by about 50-100x

#

e.g. if you had 100 before, you would change it to 1 or 2

tame yoke
#

gotchu

leaden ice
#

(in the inspector)

tame yoke
#

x axis rotation working smooth now! thanks a bunch

tame yoke
#

@leaden ice i dont mean to constantly ask but since delta time makes movement buggy for the mouse rotation, would that apply to the movement meaning that i shouldnt multiply by "time.deltatime"???

leaden ice
#

Well

#

it depends

#

I don't know how your movement works

#

I don't have enough information to answer it

tame yoke
#

if i was to send a ss of the code could u take a look?

leaden ice
#

Most likely you need deltaTime if you're using a CharacterController

tame yoke
#

oh alright

leaden ice
#

the problem with it on the mouse input is that mouse input is already framerate independent

tame yoke
#

i am using character controller atm

#

ohhh okay.

#

so when it comes to CharacterContollers, multiplying by delta time is the better option

#

alrighty thank u man

tame yoke
#

anyone know why my jumping is a little buggy? it slows down but then falls the rest of the jump. vid down below shows the buggy jumps and the code will be provided.

EDIT: fixed. turns out ground check was too low.

rigid island
tame yoke
quick token
magic sparrow
minor swan
#

!code

#

tf

magic sparrow
#

one sec it causes a dif problem

minor swan
magic sparrow
magic sparrow
#

oh i see

minor swan
#

Right?

magic sparrow
#

no i want the turret body to stay aligned with the main car body but be able to turn 360 degrees

magic sparrow
#

only the barrel is supposed to look up/down

minor swan
#

Yes I get it now

magic sparrow
#

is this the correct way to post code btw?

rigid island
#

nope

rain minnow
#

No, just use a paste site when posting !code . . .

rigid island
#

dyno is asleep today

rain minnow
# magic sparrow

Make sure the turret body only rotates along the y axis and not all three . . .

magic sparrow
#

okay ill try that

magic sparrow
#

so from what i have researched i need to use a Euler angle and not a Quaternion.

latent latch
#

If you're working in 3D it is always correct to use Quaternion

magic sparrow
#

okay so im trying to figure out how to get the turretLookDir.y = the cars rigidbody.y

latent latch
#

If you child it to the car then it would simply be the identity

#

oh direction, then you're using local z forward so that's just 1

magic sparrow
#

i needed to use Vector3.ProjectOnPlane

latent latch
#

Actually not even sure why you need that world direction as you only need to rotate on the local y

next heath
#

Help! how does one fix this? i've looked everywhere, but can't seem to find a solution.

minor swan
next heath
next heath
fading swallow
#

Im trying to set this up such that when the player clicks in the correct time window it it flows to the text attack animation. The problem Im running into trying to play them successively is how Im checking if an attack animation is playing is a sequence of attack animations will always be true. If I use an IEnumerator to add delay, then it is too late and its already transitions back to the idle. .

Im having a hard time coming up with a way to transition this properly

steady bough
#

Need help with my In app purchasing for my ios. When I launch it in Unity, it opens the dummy store but once I shift to apple store and launch it doesn't open anything. And I can't see anything. Emulator says store not initialized but I was told emulator is not reliable for testing in app purchasing:

https://paste.ofcode.org/bxyRXkkpH3fGizrvG662Kn

steady bobcat
steady bough
#

But it's not though

#

Have u seen the code?

#

I am launching straight to app store connect and yh Test flight sometimes

steady bobcat
#

tbh i dont know what you mean by "launch it in unity", you mean in the editor?

#

it will log errors too btw on device if the product ids you give are invalid. you need to test it properly on a device to verify it works.

steady bough
#

Yes

#

Launch on the editor

toxic vault
#

If I want to encourage players playing a demo of my game to wishlist my game, do you know how to generate a link that takes you to the store page inside Steam (not the website) for them to easily wishlist?

I could not find any documentation around this.

soft shard
# toxic vault If I want to encourage players playing a demo of my game to wishlist my game, do...

You would likely need to send a command to the Steam client if you want to trigger it to go to a specific page, similar to how Discord links sends a command to the client to go to a specific server - while its possible to do through a process or web request, chances are the Steam API/SDK probably already has this feature, as Steam has a integrated client as a overlay in whatever game your playing, other approaches wouldnt use that overlay though I dont see why you wouldnt want their browser to open your steam page instead?

toxic vault
#

Thanks, will look in the SDK.

First preference would be the Steam Client, since they are already logged in and everything.

Browser would work, but if it's 2 extra steps (log in, 2FA, etc.) it might put them off from wishlisting.

soft shard
#

Ah, I see

rose willow
#

why, why world why. It keeps looping this animation and as you can see, state is equal to 4 and to go back to "Retreat" it needs to not equal 1. is this a glitch

cosmic rain
cosmic rain
rose willow
cosmic rain
#

Or it enters back right away(depends on the entry transition)

rose willow
cosmic rain
rose willow
cosmic roost
#

Ee... I don't know whether this would be beginning, general, or advanced. I have an asset that I use (cinematic melee combat system) which occasionally (pretty rarely, but often enough that it's an issue) is warping the player character model in one dimension or another, leaving them kind of 2-dimensional, or sometimes stretched out. I have not figured out what exactly triggers it other than that it may have something to do with camera angles. I have not found any code in the asset that would be changing the transform.scale or transform.localScale of the object. I think that I may be able to rig a script to pause when the scale changes, but I'm not certain how I could tell what changed it.

#

Maybe something to do with animations?

rain minnow
cosmic roost
rain minnow
#

third-party asset issues are hard to debug/fix because someone (here) would need to have used it . . .

cosmic roost
#

So noted. Mainly trying to figure out if there are any good techniques for finding what might be changing the scale.

rain minnow
#

Though, I would definitely check the animation . . .

worldly gust
#

why?

night harness
#

don't have your projects in a onedrive folder

worldly gust
warped kayak
#

Does anybody know how to use the steamworks SetPlayedWith thing?
https://partner.steamgames.com/doc/api/isteamfriends#SetPlayedWith

Currently I just call it with all of the player IDs aside from the local player upon joining a steam lobby. Despite this the recent players never gets reflected on the steam website.

I'm using https://github.com/rlabrecque/Steamworks.NET

GitHub

Steamworks wrapper for Unity / C#. Contribute to rlabrecque/Steamworks.NET development by creating an account on GitHub.

#

The documentation for the call is super vague, not really specifying what requirements exactly need to be met for it to function

echo ferry
tepid sand
tawny elkBOT
minor swan
woven cairn
#

Hi there, any ideas on how to get humanoid animations stop getting stuck on the ground when moving with IK activated ?
I was wondering if there was a way to get the right or left feet transform position on the Y axis in the clip, and then use it to change the IK weight at runtime

tepid sand
quick token
#

send the relevant !code

tawny elkBOT
quick token
kind willow
#

how do I define an array of structs having an array?

#

I can do (not exact code)

[System.Serializable] public struct MyStruct {public bool[] mybools}
public MyStruct[] mystructs = new MyStruct[10];

for example, but how do I set the sizes of inside arrays?

#

asking for sake of using this to make save system into json

#

not very relevant info

hexed pecan
#

Initialize them manually in a loop or just use a class

#

Class allows field initializers

kind willow
#

I... want different sizes, that won't work probably?

kind willow
hexed pecan
#

I mean wherever the code you showed is

leaden ice
#
public MyStruct(int arrSize) {
  myBools = new bool[arrSize];
}```
#

or using an object initializer

kind willow
#

...I guess

leaden ice
#
MyStruct ms = new MyStruct() {
  myBools = new bool[56]
}```
kind willow
#

it compiles allowing me to predefine size for an array

hexed pecan
leaden ice
#

You can't really do field initializers for structs

kind willow
leaden ice
naive swallow
leaden ice
#
myStructs = new MyStruct[] {
  new MyStruct() { myBools = new bool[5] },
  new MyStruct() { myBools = new bool[5463] },
};```
naive swallow
#

You're going to need to set them individually whether they were classes or structs

leaden ice
#

or the old fashioned way:

myStructs = new MyStruct[2];
myStructs[0].myBools = new bool[5];
myStructs[1].myBools = new bool[324];```
kind willow
#

yeah this old way would prolly only work runtime

leaden ice
#

they all only work runtime

#

code only runs at runtime

kind willow
#

...fair

leaden ice
#

If you're talking about setting something up for the inspector you need Reset() or OnValidate()

leaden ice
#

but maybe you can'

kind willow
#

seems like I can

#

it compiles and it works

leaden ice
#

ok cool

kind willow
#

exactly what I needed, so cool, yeah

#

thanks for helping

#

I wonder why it is allowing me to define an array with a length of 0

leaden ice
#

why not

kind willow
#

what is a niche for that

leaden ice
#

it's an array that has no elements

#

you can write code that process all the elements of an array without needing any special cases

#

if there are no elements, so be it

kind willow
#

I guess sometimes you be having a container for data but not always need it to be filled...

#

that's pretty cursed tho

#

like there could be a better solution

night harness
#

It’s not the boxes responsibility to decide how to ideally fill itself

kind willow
#

I guess I am too rookie so I never encountered a need to have some optional array of data

leaden ice
# kind willow I guess I am too rookie so I never encountered a need to have some optional arra...

Example:

public abstract class Animal {
  public abstract Leg[] legs { get; }
  public abstract Antenna[] anntenae { get; }
}

public class Cat : Animal {
  public override Leg[] legs { get; } = new Leg[4];
  public override Antenna[] anntenae { get; } = new Antenna[0];
}

public class Snake : Animal {
  public override Leg[] legs { get; } = new Leg[0];
  public override Antenna[] anntenae { get; } = new Antenna[0];
}```
#

(contrived and silly example but yeah)

steep herald
#

I was redacting an example with cats with fur vs cats without so you have me beat either way

hexed pecan
#

It's valid to return null instead too (and have the caller handle nulls)

leaden ice
#

yeah but then you need a special case

hexed pecan
#

Don't think i have ever initialized an array with 0 length

leaden ice
#

you need to write those if statements

#

it's uggo

#

every caller needs to check the special case

kind willow
#

...or to be aware that array length can be zero

#

not sure what is more annoying

leaden ice
#

generally you don't need to be aware

hexed pecan
leaden ice
#

generally for arrays you're just doing foreach (Leg leg in legs)

hexed pecan
#

It just... does nothing

kind willow
#

linq foreach don't care but

#

yeah other cycles won't like that

leaden ice
#

wdym by "other cycles"?

#

regular for and foreach loops don't mind

kind willow
#

won't for return error if length zero?

leaden ice
#

no

#

why would it

kind willow
#

I recall having issues with for and arrays of length zero

leaden ice
#
for (int i = 0; i < legs.Length; i++)```
kind willow
#

but I don't remember details

leaden ice
#

0 is not less than 0

#

so it simply won't run the first time

leaden ice
#

or thinking of a null array

kind willow
#

maybe I am thinking of null array

leaden ice
#

almost certainly

kind willow
#

...yeah I recalling the null reference exception

#

and what foreach does about null array btw?

#

nothing without throwing an error?

leaden ice
#

NRE

kind willow
#

okay i forgot where I have screwed up that time

hexed pecan
#

foreach would call null.GetEnumerator which would throw the NRE

shadow wagon
#

I'm creating knots on a spline with

          for(int i = 0; i < Subdivisions; i++)
          {
            float3 position = new(0f, 0f, (Length / (Subdivisions-1)) * i);
            BezierKnot knot = new BezierKnot(position);
            spline.Add(knot, TangentMode.Linear);
          }```I then need to find positions to the left and right of each knot so I can start to create a road like mesh, for some reason the first and last knot, seems to have the wrong tangent. As the left/right positions end up being located on the knot
```cs
      float step = 1f / (float)knots;
      for(int i = 0; i < knots+1; i++)
      {
        float t = step * i;

        float3 position;
        float3 tangent;
        float3 up;
        SplineUtility.Evaluate(spline, t, out position, out tangent, out up);

        float3 right = Vector3.Cross(tangent, up).normalized;
        float3 p1 = position + (right * width);
        float3 p2 = position + (-right * width);

        p1Vert.Add(new Vector3(p1.x, p1.y, p1.z));
        p2Vert.Add(new Vector3(p2.x, p2.y, p2.z));
      }

      for(int i = 0; i < p1Vert.Count; i++)
      {
        Debug.DrawLine(p1Vert[i], p1Vert[i]+(Vector3.up * 10f), Color.red, 1000f);
        Debug.DrawLine(p2Vert[i], p2Vert[i]+(Vector3.up * 10f), Color.blue, 1000f);
      }```
#

there doesnt seem to be any difference between both these knots, other than the position

leaden ice
shadow wagon
#

I checked it earlier and couldnt see anything that stood out as strange, let me get a breakpoint and see if its the same as it was

leaden ice
#

yeah teh tangent is the zero vector

shadow wagon
#

should the tangent not be 0 in all of them?

leaden ice
#

Well wait

#

we should be looking at the result of Evaluate()

#

let's look at that

shadow wagon
#

just checked, after evaluate, the first and last knots produce a tangent of 0,0,0

#

whereas the other knots, do not

leaden ice
#

yep that's what I thought

#

what if you evaluated the tangent at like t = 0.01

shadow wagon
#

did I misunderstand the way this is phrased?

leaden ice
#

instead of t = 0

#

Yeah that makes sense - they are computed based on the preceding and following knot

#

so if there is no preceding knot or following knot

#

you can't get a tangent

shadow wagon
#

ill see if a tiny t value works on the two ends

#

it sounds like it should

leaden ice
#

yeah because then you would be somewhere between two knots

#

you could also consider having two control knots before and after the end of the spline

#

which you wouldn't include in the rendering

shadow wagon
#

I had 2 positions to be the start and end, and added those manually to the list of knots, and then generated 10 of the inbetween knots

#

altering the time value worked!

#

thanks 😄

#

and it correctly builds a mesh 😄

leaden ice
thorn ibex
#

I'm trying to add an edge correction detection for my FPS platformer kind of like this section of the Tarodev video: https://youtu.be/3sWTzMsmdx8?si=gG28KuGftYsX2N8W&t=110
Here is my code so far. It doesn't really work properly. All the composite parts work in isolation in the rest of the script, and I think the variable names are clear enough to get at what I'm trying to do. It just doesn't work though, and I'm not sure what I'm doing wrong, or how to correct. I've tried pumping the values up to massive values and there is no visible movement

    {
        if (Posture != PostureState.Air || RB.linearVelocity.magnitude < 0.1f) return;

        Vector3 ForwardDir = new Vector3(RB.linearVelocity.x, 0f, RB.linearVelocity.z);

        Vector3 RayOrigin = RB.position + Vector3.up * EdgeStepHeight;

        Debug.DrawRay(RayOrigin, ForwardDir * EdgeDetectionDistance, Color.green);

        if(!Physics.Raycast(RayOrigin, ForwardDir, out RaycastHit Hit, EdgeDetectionDistance)) {
            float Dist = Vector2.Distance(new Vector2(RB.position.x, RB.position.z), new Vector2(Hit.point.x, Hit.point.z));
            RayOrigin = RayOrigin + ForwardDir * Dist;

            Debug.DrawRay(RayOrigin, Vector3.down * EdgeStepHeight, Color.red);

            if(Physics.Raycast(RayOrigin, Vector3.down, out RaycastHit TopHit, EdgeStepHeight, GroundLayer)) {
                Vector3 TargetPos = ForwardDir + Vector3.up * (TopHit.point.y + PlayerCollider.height * 0.5f);
                RB.MovePosition(Vector3.Lerp(RB.position, TargetPos, EdgeStepLerpSpeed));
            }
        }
    }```

Source & game: https://github.com/Matthew-J-Spencer/Ultimate-2D-Controller
Extended source: https://www.patreon.com/tarodev

Learn how to build an amazing player controller.

This Unity character controller is built using custom physics and incorporates all the hidden tricks to make it feel amazing. 2D player controllers can be difficult to get ...

▶ Play video
elfin socket
#

I am storing a reference to a component that at this point still exists, when the component gets removed from the scene later, the reference remains non-null but accessing into it causes a Unity crash. How do I check if the reference is still valid?

lean sail
lean sail
stone rock
#

I am trying to make a rendererfeature where i create an RFloat texture storing the depth in the red color channel. I want to make the texture have mips so i can accelerate some visual effects such as screen space reflections. i have tried the following below but i do not think there are any mips in the texture.
I am not sure how i can debug it either and verify if the texture has mip levels. Below is most of the code where i create a texture in the recordrendergraph function. the actual blitting and stuff is not shown but i do not think it's relevant.

                UniversalResourceData resourceData = frameData.Get<UniversalResourceData>();
                UniversalCameraData cameraData = frameData.Get<UniversalCameraData>();

                if (resourceData.isActiveTargetBackBuffer) return;

                depthPyramidRenderTextureDescriptor.width = cameraData.cameraTargetDescriptor.width;
                depthPyramidRenderTextureDescriptor.height = cameraData.cameraTargetDescriptor.height;

                int mipCount = Mathf.FloorToInt(Mathf.Log(Mathf.Max(depthPyramidRenderTextureDescriptor.width, depthPyramidRenderTextureDescriptor.height), 2)) + 1;

                depthPyramidRenderTextureDescriptor.useMipMap = true;
                depthPyramidRenderTextureDescriptor.mipCount = mipCount;
                depthPyramidRenderTextureDescriptor.autoGenerateMips = false;
                depthPyramidRenderTextureDescriptor.enableRandomWrite = true;

                depthPyramidTextureHandle = UniversalRenderer.CreateRenderGraphTexture(renderGraph, depthPyramidRenderTextureDescriptor, "_DepthPyramidTexture", false, FilterMode.Point, TextureWrapMode.Clamp);
thorn ibex
lean sail
elfin socket
lean sail
elfin socket
#

That window with the exclamation mark. And then the game closes.

lean sail
elfin socket
#

The rest is accurate though, just double checked

lean sail
dim umbra
#

what exactly is the height field here displaying? I searched online and people seem to say it's sizeDelta.y, but they don't behave the same way. Changing height in the inspector only increases the size downwards, but doing changing sizeDelta.y extends the object in both directions

#

the way it works in inspector is how I'd like to have it work in the script, if that wasn't clear

lofty orchid
hard estuary
elfin socket
#

It's working perfectly now

carmine gorge
#

hey team,
I'm having some issues with my animation transitions.

  1. the animations work if they're on default
  2. The transition is occuring (i.e. the "Slow Run" is active (i've got a isWalking bool that turns on correctly)
  3. But the slow-run animation isn't being run

Any thoughts on why that's happening?

steady bobcat
carmine gorge
steady bobcat
#

check if you are previewing the correct animator then, if it shows its playing at runtime then it should be. Could also be the animation actually cannot play, perhaps due to it not being configured correctly (are you using humanoid retargeting?)

carmine gorge
#

thanks. i'll keep having a play

cosmic roost
rigid island
#

Is this a code smell ?
should I approach this another way or is non-issue?
(Btw this array wont go over 10 or 20 max.)

var letterScrambler = letterScramblersHistory.Pop();
                    letterScrambler.StartShuffle();
                    currentScramblerIndex = Array.IndexOf(letterScramblers, letterScrambler);
                    SetSelectorPos();```
#

hmm I suppose I could just store the index history instead of the whole object..🦆 🦆

cosmic roost
#

OK, found a way to name the current override, and found that there is one being generated based on the initial setup.

opaque vortex
#

I am working on something that uses vectors, like tons of them for computation. So I had this idea to use the float value that unity math extension has, but I will need a conversion script.

Is this worthwhile or should I stay with using vectors?

rigid island
opaque vortex
#

Is it worthwhile converting vectors to floats in computing speed

opaque vortex
rigid island
opaque vortex
#

which is my whole concern

rigid island
#

what about float3 ?

opaque vortex
#

You must have a converting script for the value

#

It is not automatic

rigid island
#

yeah like your own implicit conversion ? is that a biggie

leaden ice
#

Are you talking Unity.Mathematics.float3? There's already conversion operators between the two provided

#

pretty sure V3 is implicitly convertible to f3

opaque vortex
rigid island
#

whats the use case? what is tons of computation ?

opaque vortex
#

Like 100k meshs

leaden ice
#

float3 and Vector3 have the same exact footprint in memory afaik

opaque vortex
rigid island
#

ya I was under the same impression

leaden ice
#

you just call the functions

#

they are implicitly converted

opaque vortex
#

No they are not

#

I just spent an hour on them

leaden ice
#

Any time you pass Vector3 into a Unity.Mathematics function it will be converted to float3

#

because they only take f3 parameters

opaque vortex
#

How do you pass it?

#

I was creating a separate script just to do this

leaden ice
#

The normal way...?

#
math.mul(myVector3, 3f)``` for example
#

Regardless most of the benefits from Unity.Mathematics are going to come if you are using Burst and the Jobs system

opaque vortex
#

I have never worked with the unity.mathematics before

leaden ice
#

If you're not using burst you miss out on most of the optimizations

rigid island
leaden ice
#

yes, because there's an implicit conversion^

#

that being said the implicit conversion does have a small cost

#

it's a function that needs to run

opaque vortex
#

So is it creating garbage?

leaden ice
#

no

#

calling functions doesn't create garbage

rigid island
#

computation time doesnt always mean garbage

leaden ice
#

allocating objects on the heap creates garbage

opaque vortex
#

Would this be considered the most optimal method?

leaden ice
#

the most optimal method to do what

opaque vortex
#

Handle large numbers of vectors

rigid island
#

^ still unclear what you're doing with these 100k meshes

leaden ice
#

if you're just writing your own code and wondering if you should use f3 everywhere instead of V3, and you're not using Unity.Mathematics, then no it's not going to help you

#

what are you actually doing?

opaque vortex
#

Voxel rendering

leaden ice
#

If you start using Jobs/Burst, then yes you will benefit from using Unity.Mathematics

opaque vortex
#

I will have to go and look into this

#

thank you

rigid island
#

multithread / core is awesome!

abstract swallow
#

How many projects do y'all have and what do you use for version control? I tried out using github LFS but realized it has a pretty small size cap (1GB). Unity VCS also has a small size, like 10GB if I remember correctly

leaden ice
#

also note that GitHub is not the only git cloud repo provider

#

there are many others

rigid island
#

LFS is per file. what do you upload thats bigger than 1gb ?

rain minnow
#

the hub is fine, though I don't have many projects . . .

rigid island
abstract swallow
rigid island
#

but I guess Gitlab has that still iirc

leaden ice
#

To be perfectly honest github billing policies are completely arcane and inscrutable to me

#

It does seem LFS has a 1GB limit. But I don't see any limit for storage for non lfs objects anywhere?

rigid island
#

iirc the total for "regular" repo is total 5gb still no ?

leaden ice
#

And again, no mention of storage space for the repos there either

rigid island
#

ahhh wth it used to have it now they changed it

#

azure also seems to give more

#

Repositories should be no larger than 250 GB. To retrieve the size of your repository, execute git count-objects -vH in a command prompt, and look for the entry called "size-pack":

shadow wagon
#

dropbox 😏

rigid island
#

oh god no use VC

#

backing up ALL the files each time you change 1 is cumbersome

shadow wagon
#

i worked for a studio that used dropbox and i couldnt work from home for the first day cause it had to sync for the first time

leaden ice
#

Dropbox on the library folder 😢

rigid island
#

dropbox , google drive etc.. is acceptable for art assets

shadow wagon
#

also somehow I managed to delete an entire other teams directory, absolutely no idea how that occurred, but it caused a big delay

#

my only guess was the folder got added to my db sync, i removed it from that list, but it somehow made db think i was trying to delete the folder

leaden ice
#

one reason dropbox sucks for a project like this ^

shadow wagon
#

yeah my boss was shocked that such a thing was remotely possible

lean sail
#

that is absolutely bonkers they even used a system where you could do that

leaden ice
#

Code reviews are one big advantage version control has over a system like Dropbox

shadow wagon
#

it was a fairly small scale agency, (not a tech agency, mind you)

#

id be horrified if somebody was using dropbox for vc

#

actually, i'd probably admire their patience and fortitude

woeful veldt
#

Hello, my name is P4RTYP00P3R ! I am solo developping a Bionicle inspired game, and I have lots of things planned, notably a modular building system.
I’m asking you about a relatively simple but troublesome issue. For context, right now I’m trying to create a procedural walking animation.

First I have implemented with some AI help a script for placing and rotating feet position relatively to a raycast hit. It works great !
Then I setted up a two bone IK constraint on my leg rig. Working fine as well.

All I needed to do was now to make the IK target fixed to the position detected by the raycast. I figured out I would use a Position Constraint component on the object containing the IK target (so I can animate the weight later by script to make smooth transitions). The feet adapts but the Two Bone IK Constraint does not update the correct target position.

I tried another component, the Multi-position constraint component, but no results.
I tried to update in Update() and LateUpdate() the target position in the Two Bone IK component, but no success either.
I watched back at YT video on procedural animations with those components and a custom script to shoot foot targets, but I can’t figure out why his works and not mine.

The problem is simple : why the target position of the Two Bone IK does not update when the IK Target position is controlled in real time ?
It’s a dire situation. If I can’t get any answers, I think I’ll scrap the Two Bone IK Constraint and script my own Two Bone IK Solver.

woeful veldt
#

OK SOLVED.

Turns out just setting the IKTarget as the LeftFootTarget (the object moved in real time by script) works.

This is still a workaround because the leg tip and the feet despite being at the same position are not linked

subtle path
#

fixed

cosmic rain
# subtle path fixed

It would be easier to help you with your coroutine approach, as not many people know that tween asset.

subtle path
#

i use the tween in the coroutine as well. i wont not use tween

cold parrot
wintry crescent
#

can I use there where keyword (when defining a class with a type parameter), to limit the class to not be abstract?

wintry crescent
#

like public class MyClass<T> where T is not abstract

#

I'm trying to get this to work

subtle path
cold parrot
wintry crescent
shadow wagon
#

i feel a little silly asking this, but i cant figure out why the position of my energy drink item isnt moving with my player. when the player walks over the energy drink i do this

public class PlayerCharacter : MonoBehaviour
{
  public void CollectEnergyDrink(EnergyDrink booster)
  {
    booster.transform.SetParent(transform);
    booster.transform.localPosition = Vector3.zero;
    booster.transform.localRotation = Quaternion.identity;
  }
}```in the energy drink class, I draw the gizmo with this
```cs
void OnDrawGizmos()
{
  Gizmos.color = Color.magenta;
  Gizmos.DrawWireCube(transform.position, Vector3.one * 5f); // also tried using localposition, same result
}```even though the object is a child of my player, why does my gizmo not stick with the player?
steady bobcat
#

Check that the gizmos are showing on pivot and not center, then check if your mesh is positioned correctly

#

dont see why you need a gizmo to verify this though

night stratus
#

Anyone know how to make a game be hyper-self-aware?
I'm thinking of doing something similar to DDLC, where the game knows a lot of things that aren't a part of the actual game, like your account name and if OBS is on.

steady bobcat
#

easy, use the steamworks api or similar to get info and use it?

shadow wagon
steady bobcat
#

that image doesnt help me. If the "drink transform" is a child of the player transform, and the drink transforms local pos is (0,0,0) or what you desire then its going to follow.

#

your initial code where you set the parent transform + local pos is correct

shadow wagon
#

actually, thinking about it, the position of the drink should have a local position of 0,0,0

steady bobcat
#

are you changing it again somewhere else?

#

e.g. another script or an animator or a constraint component

shadow wagon
#

oh, whoops, I forgot to remove[RequireComponent(typeof(Rigidbody))]

#

ive got another item class that used a rb, so I just copied that class to make the energy drink, but forgot there was a rigidbody

steady bobcat
#

it can still work if you use rigidbody.MovePosition() for example or if the rb is kinematic.

hot sorrel
#

Hi, I'm trying to get the argmin from a large list using jobs and I'm wondering how to deal with race conditions. It thought i could just access the index corresponding to the thread number but it doesnt seem to like indexing that isnt the index passed in the argument. Is there a proper way to do this or should i just populate a list of errors and then cop the bullet and get the argmin in the main thread after completing the job?

sweet forum
#

im not getting any help

steady bobcat
sweet forum
#

my character's arm keeps coming apart

#

it doesnt rotate when kinematic and when dynamic it comes apart from the body

steady bobcat
sweet forum
#

ive asked for 2 days straight

#

with no response

steady bobcat
#

ok

hot sorrel
#

using the job index to calculate the error (but that isnt in the sc i put in)

steady bobcat
#

a job is not executed on its own thread

#

stop using it. the point of parallel jobs is for many to be scheduled that share data but only work on a single index.

#

that is why its not letting you read and write from other indexes in the native array. If its read only then it wont care where you read from.

hot sorrel
#

the only other way i could think to get the argmin is by making minIndicies and minErrors the same length as trhe parallel for, then assuming the i-1th index is the minimum for all indicies less than i - 1 then making a comparison between i - 1 and i and writing it into index i. But then im storing like 100,000 redundant ints and floats

#

had a browse online and someone was saying you could store values local to workers so that there was no conflict but they never explained how (unless im misunderstanding them)

true heart
#

Im using using UnityEngine.Windows.Speech; for my voice recognition and it works great, my problem is that if someone has not en-GB as their default windows language, the voice recognition doesn't work.

Anyone knows a turnaround for this?

Thanks

tough obsidian
#

Hey everyone,
Actually I am working on a fps and want to add a bullet which will spawn a net and wrap around the enemy and disappear after time. So now I have the net model but I am not able to understand how can get the wrapping effect on the enemy. As there are many type of enemy so it won't be efficient to create the animation in blender then play that animation in unity. Another alternative was to use cloth components but by my research and understanding it won't give me that tight wrapping effect
Any suggestions will be appreciated

plucky inlet
hexed pecan
#

Interesting problem... Could calculate a convex hull out of the enemy's bone positions and somehow wrap it around that

wintry crescent
latent latch
#

Another idea is create a lattice for this net's mesh and each enemy a SDF of points where the lattice points would match

woeful veldt
#

--
Otherwise maybe you can create your net mesh through script, apply your net texture to it, and give behavior to the vertices when they encounter surfaces (check for people making bouncing balls, I know there was one on YT but it was really hard stuff)

lean sail
#

i really dont think configurable joints are the play there

#

it just doesnt make sense to use them. you dont need physics/collisions on the objects. its not like it solves the problems without causing 10 more problems

#

a shader or vfx graph would be my first attempt

steep herald
#

@tough obsidian Me I'm with Osmal,

  • Generate a convex hull
  • Find where the bullet hits the hull, then unwrap the net in a circular fashion. Say your central position is at the hit. Take the hit normal, offset the points from the first ring to hit position + normal * distance from the first ring, and raycast in the unwrapping direction. If hull wasnt hit, rotate the point and raycast in the adjusted normal. Repeat the op till the hull is hit, and then move on to the next vert until the ring is complete.

It won't be precise, but it'll be fast if the number of points/particles you use isnt too high, and it'll be reliable

latent latch
#

vfx graph is pretty good idea to grab data from from the current skin render it's wrapping

#

if we care about physics

cold parrot
#

i would start looking at what part of that effect the player can actually see and whether it even has to be a simulated effect or anything with continuity. How many frames are we talking about for the animation?

latent latch
#

Also big brain idea, just map your uvs for all characters in a way that mapping a texture across it wouldnt become warped

#

ez

#

Oh, world UVs would work fine in that regard too

hexed pecan
#

I'm not imagining an effect where a simple texture wrap would work. Im imagining a separate mesh for the net that wraps around the enemy

#

Maybe OP can specify

steep herald
#

Ya, texture wrap would stick to skin where the mesh is concave and it should feel like the net is stretched out. Imo I think it'd look cheap.
And since things are skinned at runtime, need to dynamically generate the hull. From there you can get some pretty cool effects

#

Actually there is no mention of enemies being skinned, so I'll see myself out

wintry crescent
#

silly question, but is there a way to clone an instance of a class (not deriving from UnityEngine.Object don't worry) without creating a custom constructor for it, and without using reflection?

thin aurora
#

Serialize to JSON, then serialize back

#

Usually people do this, but it has its own pitfalls when it comes to the deep cloning, not to mention it might still end up losing data or throw an exception by design.

#

If you want a reliable clone, just do it manually. Also prefer implementing ICloneable for consistency

wintry crescent
#

oh, ICloneable seems perfect, thanks!

thin aurora
#

You need to implement it manually, so it's not a build in fix. You still need to manualy create the new instance and map the content over.

wintry crescent
thin aurora
#

There's just too much involved for a way that is automatic

#

Even reflection might not work, or map irrelevant content over

wintry crescent
#

why is this so difficult in c#??

#

wtf

thin aurora
#

It's not difficult, just make a method

wintry crescent
#

if I remember correctly, C++ would make this super easy

thin aurora
#

C++ doesn't worry with references, though

wintry crescent
#

yea but I don't want to create a separate method for all 20 classes I need this to work on

#

or so

vestal arch
wintry crescent
#

I need it to possibly be null

vestal arch
wintry crescent
#

although I guess I can make a nullable struct

thin aurora
#

That would still end up keeping references to nested reference types, fyi

hexed pecan
#

Not sure how nullable structs are copied

wintry crescent
#

nevermind - that's just the same thing again

#

20 constructors needed

#

gotta love unity and its outdated-ass C# version

#

where is CoreCLR when I need it

thin aurora
#

Also, just making it a struct for the sake of not working with a reference is a very bad idea

thin aurora
hexed pecan
#

The idea was "for the sake of easy copying"

thin aurora
#

Still, don't just make stuff a struct lol

#

Literally just make a "Clone" or "Deepclone" method and add an extra constructor for it

public partial class CompileTask, ICloneable
{
    public CompileTask()
    {
    }

    public CompileTask(string? name, string? inputFilePath, string? outputFilePath)
    {
      ...
    }

    public object Clone()
    {
        return DeepClone();
    }

    public virtual CompileTask DeepClone()
    {
        return new CompileTask(Name, InputFilePath, OutputFilePath);
    }

    public virtual void Merge(ProjectTaskBase task)
    {
        Name = task.Name;
        InputFilePath = task.InputFilePath;
        OutputFilePath = task.OutputFilePath;
    }
}
#

Why discuss 5 different complex solutions when a bit of manual labour does it

steady bobcat
#

protobuf messages are given a MergeFrom() and Clone() function, not hard to add your own

thin aurora
#

Does Unity support Records?

wintry crescent
#

alright, maybe I'm overthinking it, perhaps there's a different approach entirely - I have a class called AnimationConfig, that is present on a ScriptableObject, and in my Animation class
so my Animation has 2 variables in this case - ConfigOverride, and a reference to the ScriptableObject called DefaultConfig
and my desire is that whenever the ScriptableObject changes, the ConfigOverride clones itself to be exactly like the config on the ScriptableObject, so that I can do per-object overrides to the config, without modifying the ScriptableObject config

#

I'm currently making a custom editor to handle that cloning whenever the SO changes

craggy veldt
#

unity doesn't support record, but there's a hack for that
the catch is,it wont get any specia treatments on both mono/il2cpp

hexed pecan
#

It is very much a language version limitation

#

No struct field initializers in unity

craggy veldt
#

there's a little benefit using records than just regular custom class/struct

#

all custom classes/structs can do what records can

thin aurora
wintry crescent
thin aurora
wintry crescent
#

goddamnit I have to figure out sth else

thin aurora
#

Switching to a struct is not a bad thing, but don't just switch because of how copying is handled, that link explains it p. well

hexed pecan
#

If you want the same data that unity serializes then plain old JsonUtility will work

placid edge
#

if im trying to move an object in the Y axis by its height, am I adding it's scale, or is there a way I can access the object's actual height?

hexed pecan
#

For example, myRenderer.localBounds.size.y

#

If you always have a certain collider you can use the collider's size.y or height property

placid edge
#

Ohhh right

#

yeah this should work cuz the size will always be the same

#

thanks :)

wet plover
leaden ice
wet plover
#

Yeah, I think so, but I don't know how to fix it.

leaden ice
wet plover
#

Okay, but I dont, and still happens. I shrinked the character colliders radius, its a bit better, but the item is not in the collider and it teleports

leaden ice
#

start debugging

#

add a collision callback to the object and print out what, if anything, it's colliding with

wet plover
#

yeah, thats a good idea, i'll try. Thanks!

upper pilot
#

How can I export CSV in Unity to an already open file so it automatically updates the values?
Is that even possible?

rigid island
#

wdym an already opened file?

upper pilot
#

Exactly what it says.

#

The file is open on my system

#

like a txt file with a notepad

#

or a csv file with an openoffice

steady bobcat
#

As long as the file can be written to again then you can.

leaden ice
wraith cobalt
zinc parrot
#

hey so when I hot reload a shader(cuz I modified it during play mode), all vertexbuffers get invalidated basically
How can I tell when a vertexbuffer gets invalidated in this way? calling IsValid() returns true exclusively during this
its still a valid vertexbuffer, but it contains no vertex data suddenly

#

I have an array of VertexBuffer and thats the buffer and/or reference that its happening in, I populate it via SkinnedMeshRenderer.GetVertexBuffer()
The only way ive found to get around this is to every frame(I do stuff with it every frame) call .Release on every element of the VertexBuffer array, and then repopulate it

#

which feels super inefficient
especially in cases where I have like 500 skinned meshes(each one is only about 500-700 polys)

viscid plaza
#

Any way to enable/disable the "Render Shadows" option in camera programatically?

heady iris
viscid plaza
#

Default

heady iris
#

I don't see a "Render Shadows" option on my camera

#

(this is in a 2022 VRChat project)

viscid plaza
heady iris
#

that's the URP

#

(universal render pipeline)

#

i forgot that that's the default now :p

#

I'm using the built-in render pipleine, or BiRP

#

You're going to want to look at the "additional camera data" component

#

That's where the settings actually live

#

yep, there it is

#

The component is attached to the same object as the camera

#

You'll see this pattern for a few other things, like lights and reflection probes

viscid plaza
#

camera.GetComponent<UniversalAdditionalCameraData>().renderShadows = false;
This works I think, cheers!

heady iris
#

yep!

#

The Camera component itself doesn't get changed by the URP/HDRP, but they do give it a custom editor to show those extra settings

inland tangle
#

Can someone please help me with my code

using UnityEngine;
using System.Collections.Generic;
using System;
using UnityEngine.UIElements;

public class UserInventory : MonoBehaviour
{
    public int FlameThrowerQty = 1;
    public int KatanaQty = 0;
    public int BarQty = 0;

    void Start()
    {
        Debug.Log("Initial flame value: " + FlameThrowerQty);
        Debug.Log("Initial katn value: " + KatanaQty);
        Debug.Log("Initial bar value: " + BarQty);
    }

    public int HasItem(int itemID)
    {
        if (itemID == 0)
        {
            return FlameThrowerQty;
        }
        if (itemID == 1)
        {
            return KatanaQty;
        }
        if (itemID == 2)
        {
            return BarQty;
        }
        return 9;
    }
}
#
using UnityEngine;

public class WeaponSwitcher : MonoBehaviour
{
    public GameObject flamethrower_YK;
    public GameObject katana_YK_TX2;
    public GameObject SewerBar_YK;

    private GameObject activeWeapon;
    private UserInventory userInventory; // Change from GameObject to UserInventory

    public GameObject playerInventoryGameObject; // Assign in Inspector

    void Start()
    {
        // Get the UserInventory component from the assigned GameObject
        userInventory = playerInventoryGameObject.GetComponent<UserInventory>();

        // Ensure all weapons start deactivated
        flamethrower_YK.SetActive(false);
        katana_YK_TX2.SetActive(false);
        SewerBar_YK.SetActive(false);
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Alpha1))
        {
            SwitchWeapon(flamethrower_YK, 0);
        }
        else if (Input.GetKeyDown(KeyCode.Alpha2))
        {
            SwitchWeapon(katana_YK_TX2, 1);
        }
        else if (Input.GetKeyDown(KeyCode.Alpha3))
        {
            SwitchWeapon(SewerBar_YK, 2);
        }
    }

    void SwitchWeapon(GameObject newWeapon, int itemValue)
    {
        int itemCount = userInventory.HasItem(itemValue);
        Debug.Log("Item ID: " + itemValue + " | Item Count: " + itemCount);

        if (itemCount > 0)
        {
            if (activeWeapon == newWeapon)
            {
                activeWeapon.SetActive(false);
                activeWeapon = null;
            }
            else
            {
                if (activeWeapon != null)
                {
                    activeWeapon.SetActive(false);
                }
                newWeapon.SetActive(true);
                activeWeapon = newWeapon;
            }
        }
    }

}

#

It returns:
Initial flame value 0
Initial katn value 0
Initial bar value 0

heady iris
#

check the inspector -- you probably have a 0 for the "Flame Thrower Qty" property

#

The field initializers provide default values, which are then replaced by anything you've set in the inspector

inland tangle
#

Omg ty

#

So how do I change it so its all done in the code and not in the inspector

heady iris
#

You'll have to avoid serializing the fields if you don't want Unity to remember their values

#

make them private or use [NonSerialized]

#

this does prevent you from viewing them in the inspector, annoyingly

inland tangle
#

Cause I want to use another script to be able to edit them for a shop

heady iris
#

A compromise is to set the default values you want in Start or Awake

#

which will override whatever's in the inspector

inland tangle
heady iris
#

Yeah

inland tangle
#

Without any getter methods etc

#

Alr ty

heady iris
#

They're still public fields

#

they just won't appear in the inspector

inland tangle
#

Wait where does [NonSerialized] go

heady iris
#

It's an attribute. You put it in front of the field declaration

#

e.g.

#
[NonSerialized] public int foo;
#

note that it comes from the System namespace

inland tangle
#

Ohhh ty

#

Bro ur such a legend

heady iris
#

you'll have to add a using System; directive if you haven't already

inland tangle
#

If this works

latent latch
#

auto property would work too

heady iris
#

(or spell it out explicitly)

heady iris
inland tangle
#

Yh I have using system;

#

Works!

#

Now I need to figure out how to make a shop and how to make the item quantity work (The # 1 above every item)

quartz anchor
#

Hey everyone! I'm trying to make a save system that uses JSON files and dictionaries, my serialized dictionaries work with primitive data types but don't when I try to make dictionaries with classes for values, does anyone know how to solve this? I've checked and it works properly when converting a single class to json

worthy tundra
#

can anyone help with this pls

#

ive been stucked forever with this

heady iris
#

(and dictionaries are notably not serializable)

quartz anchor
oblique spoke
heady iris
#

ah, yeah

#

wrong one

#

I'd suggest using Json.NET if you want to serialize anything complicated.

quartz anchor
worthy tundra
oblique spoke
#

Will JsonUtility use mechanisms used by SerializasbleDictionary class to handle serialization?

heady iris
#

I'd expect it to work as long as the type shows up in the inspector correctly

quartz anchor
mossy flare
#

I have a bit of a math problem, and I am stupid.

// code is in fixedupdate
        Vector3 targetPosition = Hand.position;
        Quaternion targetRotation = Hand.rotation;

        Vector3 grabOffset = grabPoint.position - rb.worldCenterOfMass;

        Vector3 targetGrabWorldPos = targetPosition + transform.rotation * extraPos;

        Vector3 linearVelocityForCOM = (targetGrabWorldPos - grabOffset - rb.position) / Time.fixedDeltaTime;
        rb.linearVelocity = linearVelocityForCOM;

        Quaternion rotDiff = targetRotation * Quaternion.Euler(extraRot) * Quaternion.Inverse(grabPoint.rotation);
        if (rotDiff.w < 0) { rotDiff = new Quaternion(-rotDiff.x, -rotDiff.y, -rotDiff.z, -rotDiff.w); }
        rotDiff.ToAngleAxis(out float angle, out Vector3 axis);
        angle = Mathf.Min(angle, 180f);
        Vector3 angularVelocity = axis.normalized * (angle * Mathf.Deg2Rad / Time.fixedDeltaTime);

        rb.angularVelocity = angularVelocity;```
So this code takes the object I'm holding and manipulates the rb to follow it. The issue is with the rotational force. Since the grip may be offset from the center, any rotation dislocates it from the grip before being corrected by the position. This causes a wobbly feel to the objects.
Here is a frame-by-frame of the issue.
#

How do I fix this code so that rotates the rigidbody about the grip?

heady iris
#

one option would be to put the rigidbody on an empty parent object

mossy flare
#

No parenting can be done.

heady iris
#

why not?

mossy flare
#

The design forbids it. I forgot why.

#

Something to do with physics overhead.

heady iris
#

if you have no idea why, reconsider

mossy flare
#

I have done it many times before and it has led me to this solution.

#

Is it customary to try a solution that has failed before once you forget why exactly it failed?

#

Lol

heady iris
#

it's certainly unreasonable to assume that it won't work :p

#

i do feel like there should be another way

mossy flare
#

I remember

#

Parenting is incompatible with networking in most cases. If the event is missed, everything breaks.

#

Whereas a pick up event can be missed here, and the position will be updated anyways

#

It is less failure prone

#

Of course, parenting can be done, but you need to set up complicated network events that account for what happens if the event never reaches the client, the host, etc.

#

Something I have neither the time for nor effort to learn how to do.

mossy flare
quasi elbow
#

yo, for some reason my instantiated object is not behaving correctly

rigid island
quasi elbow
#

my instantiated transform "buffPanel" is still null

quartz anchor
heady iris
#

nice (:

#

it's a really nice package

#

I originally thought you were asking about using classes as keys in dictionaries, which I've done before :p

#

(you have to turn it into a string -- this was to use a GUID as a key)

quartz anchor
#

One thing though, when I just noticed that it's throwing an error with vector3's Error name: Newtonsoft.Json.JsonSerializationException: Self referencing loop detected for property 'normalized' with type 'UnityEngine.Vector3'. Path 'playerPosition.normalized'.

heady iris
#

Json.NET looks for properties and serializes those

#

this repo adds custom converters that correctly serialize common unity types

quartz anchor
#

awesome!

inland tangle
#
    void SwitchWeapon(GameObject newWeapon, int itemValue)
    {
        int itemCount = userInventory.HasItem(itemValue);
        Debug.Log("Item ID: " + itemValue + " | Item Count: " + itemCount);

        if (itemCount > 0)
        {
            if (activeWeapon == newWeapon)
            {
                activeWeapon.SetActive(false);
                activeWeapon = null;
            }
            else
            {
                if (activeWeapon != null)
                {
                    if (activeWeapon == clonedSewerBar_YK)
                    {
                        Destroy(activeWeapon);
                    }
                    activeWeapon.SetActive(false);
                }
                if (newWeapon == SewerBar_YK)
                {
                    GameObject clonedSewerBar_YK = Instantiate(SewerBar_YK);
                }
                else
                {
                    newWeapon.SetActive(true);
                }
                
                activeWeapon = newWeapon;
            }
        }
    }

}

Can someone help me: If its a sewerBar as the item I want it to clone and use that, and then when its unequipped I want it to delete the clone if you guys understand?

quasi elbow
#

so can anyone help me pls? Idk what to try anymore

#

OH MAJOR MISTAKE ON MY SIDE

inland tangle
#

My project is due tomorrow