#archived-code-general
1 messages · Page 430 of 1
That looks awful
you should not do that
yeah I requested AI to do chores of writing 3 for loops
there should only be one parallel for loop
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
just chunk the loop by one coordinate, no need to make a thread for each index
you could also use a concurrent dictionary
wait
needs fewer locks
if you could put your words into text that would help
I occupied 2000x2000x2000 spaces
finished the running the scene
it won't release the memory
absolutely making me insane
perhaps the gc just hasn't run? 
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
what happens if you run the scene again?
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?
oh that is possible
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
If GC doesn't collect stuff, then you're still referencing it
Do proper profiling. Otherwise we can't help you
I literally don't reference to it though, it is dictionary of struct and the scene is terminated
GameObject
Do memory profiling
Do I run just regular Profiler ?
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
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.
This would be visible in a memory profiler
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 !
can you TLDR the issue in like... a sentence? 😛 helps to start with that always when asking long questions lol
so people that CAN help can continue reading, and others that can't might wanna skip
Yes sorry !
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
(I'll put the sentence up there)
Well first of all there'se an else missing here
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?
It is not
I've tried GetLocalizedString, and I think GetTableAsync and not async .LocalizedValue as well, I had the same result for all 4
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
I have given it the LocalizationSettings.SelectedLocale as well as logging it to ensure it's the right one to try and ensure it would pick the right language but it visibly doesn't, would there be another way to do it then ? Also thank you so much for taking the time to help
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);
...
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 ?
not necessarily, but I think you should always try to make something work first with code as simple as possible before moving on
for example to make this more performant and streamlined, you could set up your tables to already contain LocalizedString instances instead of string instances, so you could retrieve them via string txt = ..GetTable().GetLocalizedString(line.ID);
I'll try to see if I can do that, thank you so much
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
I tried to put this directly rather than using the Fetch function, I still sometimes get english and sometimes french when the locale is fixed to french
Thank you so much for the time you took, I'll do my best to fix it !
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 😊
awesome ^^ and gz on the internship
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?
You would need to know the index of a given Transform to update it in the buffer
unless the order of the result doesnt matter in which case you overwrite the whole buffer each frame or something
yes thats fine
My main question is the fastest way to update the GPU-side data with the CPU matrices
yeah was thinking if you actually have the indices on CPU, you can pass them along as a parameter to the compute shader
I know the indexes they go to
I just want to know if theres something faster than standard buffer.setdata(transformarray)
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?
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
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?
Sorry— code used during custom inspector and property drawers should be here or should it be in #📲┃ui-ux?
perhaps #↕️┃editor-extensions
Thanks!
You can perform the write from a Burst compiled job if you use BeginWrite to get a NativeArray and then use TransformAccessArray to be able to read Transform values from a job.
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.
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?
@copper crescent are you using continous or discrete on your rb?
continous
could you send a video of what the hop looks like?
also @copper crescent how are you checking for the ground/wall etc
with raycast going down
are you checking walls too?
overall yes, but it did happen with floors so far
if you check the Y on the video you can see the weird behaviour
interesting thanks for sending
it's the connection of different box colliders as far as i know
which is the problem
im assuming all the y's of the colliders themselves are the same, correct?
and the ys of the platforms
correct, platforms have the same Y pos
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?
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
ok, as it's only the top plane visible (realy thin) is that fine picture?
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
i added box to it
i was thinking of making a one bigger collider to ommit connection of smaller planes
there is no issue with box collider 😲
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?
yay @copper crescent im glad you fixed it!!
bump
This is a code channel - Delete and ask in #🏃┃animation
To clarify, is your issue that this solution is Windows-Only, but you want cross-platform?
no, I am making this specific implementation for windows only
my issue is that it's not working
cool. The next screen starts from Screen[0].Width so you can + offsetFromLeft to move it to second display
DisplayInfo is helpful for this.
I see, are you sure that's the case tho?
I am testing this on my brother's windows pc and his 2nd display is to the left of his main one(both physically and virtually).
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
i just figured the actual trigger was used in the code
yeah determining the positions is an issue. But Screen 0 indeed ranges from [(0,0) to (Width,Height)]
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:
and you gotta do all movement with the first screen's bottom-left corner as anchor.
Idk how to fix it, Im new to all this. When cayote time activates double jump stops working
@cursive moth check this repo out: https://github.com/micdenny/WpfScreenHelper/blob/master/src/WpfScreenHelper/WindowHelper.cs#L71
Doesn't seem to be case on his setup.
I was initially setting the app to (0,0,width,height), and that moved the app to his 2nd display, not the main one.
I assumed the the leftmost virtual desktop has 0,0 coords in the top left because of this.
ik, that's not the case everywhere, e.g. on hyprland you'd move the left display to -coords so idk tbh
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
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
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
I looked into it and that window helper is used to move the window too coordinates, not another display, will look at other scripts tho
there's a Screen parameter
oh, I missed that, let me look into it again, thanks
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 😛
window.SetWindowPosition((int)Math.Round(coordinates.X), (int)Math.Round(coordinates.Y),
(int)Math.Round(
@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
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
Glancing through it, it doesn't look like your code actually checks for coyote time being active. Try changing the line if (IsGrounded() || doubleJump) to if (IsGrounded() || doubleJump || coyoteTimeCounter > 0)
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
it's already doing that, it's a background/visualizer, sort of like wallpaper engine
uh. Have you tried Display.displays[id].Activate(), then? 😛
that should move the app to that display, right?
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
@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
You solved 2 days of my life with one message. I might need permission to kiss you
I'm not sure my fiance would approve lol. Glad it worked
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...
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
Damn, I didn't know that. Definitely gonna use that now. I only have one last question
Which line of code are you referring to here?
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
Inside of that if statement you just changed.
{
rb.velocity = new Vector2(rb.velocity.x, jumpingPower);
doubleJump = !doubleJump;
//new line here
coyoteCountTimer = 0;
}```
I should delete the whole "if" and instead just set coyote time counter to 0?
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
I see, thanks for the info once again. Have a great night man
Which makes more sense for a parkour game, rigid body or an fps controller?
There seems to be ways of making a parkour game both ways and I want to know y’all’s opinion on which would be able to add mechanics too
why couldnt a first person controller also be rigidbody?
those two arent mutually exclusive, a fps controller is something youd build yourself
I think they're referring to the character controller
Yeah sorry I’m still new to unity and what I’m reading online says there’s 2 ways of making the player actually move, through like actually applying physical force to the rigidbody or just an input making the character move a direction from what I’ve gathered
Sorry if I’ve got it really wrong, it feels like every forum I look at has a different view on it
@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.
Alright thanks 🙏
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
Yeah, as I said I’m still really new to unity and just want to learn what stuff is best for which I guess
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
only example i can think of is UniTask
https://github.com/Cysharp/UniTask/blob/8042b29ff87dd5506d7aad72bd6d8d7405985f27/src/UniTask/Assets/Plugins/UniTask/Runtime/PlayerLoopHelper.cs#L293
maybe AfterAssembliesLoad isn't the time to get the player loop
What would happen with just [RuntimeInitializeOnLoadMethod]?
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
well anyway you don't need that to customize the player loop -- you can just SetPlayerLoop 😛
Agreed 🙂 this is probably the way im going to go. I appreciate the help though guys
Would you mind expanding on this? This is obviously overkill for what im using it for as an example/exercise (literally a timer lol) but i was imagining times where this could be helpful?
i guess im asking - is this a massive code smell that i should avoid 😂
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 😆
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 😆
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.
Can just place it in world and add a script that makes it always look towards the active cam (?)
I've done that in the past but I want to try and avoid it this time. Partially to keep things cleaner and also to git gud at graphics programming related stuff.
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).
have you tried DrawMesh with the proper 3D position, though?
I just realized you could reuse the same mesh + material and just do separate draw call per billboard.
this is the thing I'm going to try next
also https://docs.unity3d.com/ScriptReference/Graphics.DrawMeshInstanced.html for one draw call
I also looked at that, I'll try optimising after I get the general functionality working first
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
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); }
oh shit I hadn't heard of that TRS constructor, cheers
Matrix4x4 matrix = Matrix4x4.TRS(position, rotation, doorSize) sure beats Matrix4x4 matrix = Matrix4x4.Translate(position) * Matrix4x4.Rotate(rotation) * Matrix4x4.Scale(doorSize)
damn
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?
There is no possible way we can know from that explanation alone, sorry. >_>
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?
How are you enabling the ragdoll state? Like, in plain english, what is your strategy?
That's a good start. What does "freak out" mean in the context of your problem?
Hold up; maybe here's a better question: can you spawn an object in ragdoll state without it "freaking out"? @mossy flare
Sorry for the recording. OBS really doesn't want to work on windows.
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?
Yes. No issue at all.
Well,
Okay; have you tried setting the velocity of the rigidbodies to zero immediately after you enable the ragdoll* state?
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
public void SetRagdoll(bool state) {
core.isKinematic = !state;
foreach (ConfigurableJoint j in joints) {
Rigidbody rag = j.GetComponent<Rigidbody>();
rag.isKinematic = !state;
rag.angularVelocity = Vector3.zero;
rag.linearVelocity = Vector3.zero;
}
}```
It doesn't seem to make a difference
I don't know what your metric is, but that doesn't seem like the same kind of "freak out" as what I saw before.
Can you show an example of a character spawning in ragdoll and collapsing exactly as you expect them to?
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
Sorry I went on a rabbithole of solving 10 different other bugs because everything started falling apart
I'm not exactly sure what's going on in the video, but it certainly doesn't do that anymore.
I know it's a problem with the animations because if I put a different, more simple one (an idle animation, in this case) the transition is much smoother
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
@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
I just want a ragdoll they were doing this shit in like 2010
Wait. Do you stop the animator when enabling the ragdoll ?
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
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
nice
I was going to say, is there a reason you chose configurable joints? Because usually the ragdoll wizard gives you character joints
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?
configurable joints are way more complex and a pain in the ass to setup properly
A custom setup for active ragdolls.
Drive is needed
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
Since you likely know, should I enable projection?
I heard about it when researching this issue
Well, the animation clearly makes it do something that the limits can't, even if it looks fine. What are you suggesting? To make the limits springy instead of hard?
I doubt that would look very natural
I dont think I did but honestly dont remember, it'll be best if you just
. From the docs it looks useful if you're gonna be in scenarios often where the joints have something between them
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
active ragdolls
god it looks horrifying without limits
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
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
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
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
hm if something small like this is causing the issues you had in the video before, check the weights of your rigidbodies on each component too. The ragdoll wizard will assign proper weighting to each component, relative to what an actual body part should weigh
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
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?
can someone help me with some unity errors ill start with the first one. its a double ambigous error (error code: CS0121)
Take a screenshot of the error instead. Or at least type the whole error message correctly
As well as the code line that throws it.
There are plenty of tutorials on it online.
i sent the error message @cosmic rain
I see that.
This seems to be an issue with a plugin. Did you read it's requirements properly and installation instructions?
well everything was fine before i added a google library and thjen it doesnt work anymore
Must be a library/dll that was included in that google library. You should read instructions of every plugin you add properly.
oke, but how do i fix this now
hello?
They told you
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.
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?
The probably easiest option would be to have a component next to the TMP that listens for the device changed event on some global manager (PlayerInputComponent or whatever you have built) and changes the TMP component to display the correct glyph or sprite. (ie not searching for TMP components but using events instead)
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!
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
(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
SerializedClasses should usually be the first go-to assuming unique instances are used only once, but there's actually one major problem with these and that multiple nested SerializedClasses do create problems on the editor eventually, while ScriptableObjects are drawn as an independent object entirely on the editor.
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.
Is there any alternative to this bloat? Could you give an example of assuming unique instance only being used once?
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.
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?
A better example is having like 5 different SOs for a gun object; ProjectileSO, StatsSO, IdentitySO, StatRequirementSOs (just throwing out some bs)
And by nested serializedClasses do you include normal C# classes as well or strictly SO
You're saying that this is a bad idea and therefore should not be done?
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
I've seen people abstract the stats for a gun into a singular scriptableoBject let's call it gunSO, and bulletSO, impactSO, etc etc
Gotcha. What was the usual way of dealing with this pre-scriptableObjects? I imagine it had to be similar since SOs seem like the best way of doing this now from my limited experience
Prefabs and SerializedClasses
I'll look into serializedClasses
SOs were actually a newer feature
Just to be clear this means [Serializable] right
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
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
I see, what would the workflow involve? This serializedReferences you've mentioned? I'm genuinely curious how they solved the bloat problem
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
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
Gotcha, so a local SO/dataclass
A prefab variant would be useful if you had a Zombie prefab, and you wanted a RoboZombie, Vampirezombie, PoisonZombie as 3 of their own prefabs
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.
What do you mean by less-derived types?
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)
I see, then serializeclasses loses some benefits of inheritance
That's ultimately the problem with them (besides running into problems if you nest too much)
Thank you so much mao!
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
why is this here
@median wren Don't post off-topic on the server. Read #📖┃code-of-conduct
Hey i hope its fine i ask here. Ive made a new android project, where im trying to create an instance of a Java class using AndroidJavaObject, but the java class in question is generic and the constructor requires a type parameter. If anyone can help it would be greatly appreciated.
Ive also created a forum post with more info including error logs:
https://discussions.unity.com/t/unable-to-create-instance-of-generic-java-class-java-lang-nosuchmethoderror/1612398
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.
Let's see how to get an FPS Character Controller up and running in no time!
REGISTER with APPTUTTI: https://www.apptutti.com/partners/registration.php?utm_source=brackeys&utm_medium=social&utm_campaign=brackeyssponsor1
LEARN MORE: https://www.apptutti.com/corporate/?utm_source=brackeys&utm_medium=social&utm_campaign=brackeyssponsor1
● Ultimat...
@tame yoke Look at your semicolons
As the error says, you're missing a semicolon ;
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
so js delete that. no replacement code correct?
correct
oop i was missing a semi colon
you may need to reduce the mouse sensitivity to compensate
alrighty thank u very much
mhm
ill reduce to 75%
thank u @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
gotchu
(in the inspector)
@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"???
no
Well
it depends
I don't know how your movement works
I don't have enough information to answer it
if i was to send a ss of the code could u take a look?
Most likely you need deltaTime if you're using a CharacterController
oh alright
the problem with it on the mouse input is that mouse input is already framerate independent
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
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.
btw for future mkvs dont embed, use mp4
i coulda sworn i was recording in mp4. pcs being weird ig
assuming you're using OBS, file>remux recording and then put the recording in. it will automatically convert it to an mp4 for you
Looking for a solution to the turret not having the same orientation as the rest of the vehicle.
I think the issue is ur setting turretLookDir.y to 0 for some reason
!code
tf
one sec it causes a dif problem
Also post ur code correctly #854851968446365696
i don't understand how my code was posted incorrectly
oh i see
no i want the turret body to stay aligned with the main car body but be able to turn 360 degrees
Oh wait I get it
only the barrel is supposed to look up/down
Yes I get it now
is this the correct way to post code btw?
nope
No, just use a paste site when posting !code . . .
dyno is asleep today
Make sure the turret body only rotates along the y axis and not all three . . .
okay ill try that
so from what i have researched i need to use a Euler angle and not a Quaternion.
If you're working in 3D it is always correct to use Quaternion
okay so im trying to figure out how to get the turretLookDir.y = the cars rigidbody.y
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
i needed to use Vector3.ProjectOnPlane
Could have also used https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Transform.TransformDirection.html with the local forward direction
Actually not even sure why you need that world direction as you only need to rotate on the local y
Help! how does one fix this? i've looked everywhere, but can't seem to find a solution.
Have you tried clearing your library
i'll try it
doesn't work :(
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
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:
are you testing via test flight or something else? As long as your product is added to app store connect and you have unity iap installed correctly it should work just fine
But it's not though
Have u seen the code?
I am launching straight to app store connect and yh Test flight sometimes
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.
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.
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?
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.
Ah, I see
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
Since it has exit time, it would loop as much as you specify in the settings. In this case it loops 2.1 times before exiting.
You can see that the "shoot" block appears 2+ times in the diagram
it never left the animation though
Then there's something else going on. Perhaps the parameter is being set back to 1 just when it's ready to exit.
Or it enters back right away(depends on the entry transition)
Anyways, next time #🏃┃animation for this kind of questions.
hmm, when I played the build version it does not have this issue
Could be an issue in code as well, since you probably set the animation parameters in code.
maybe, well thanks for the help! Ill try some stuff, cya!
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?
I would record a video and send it to the developer. If they have a website or forums, check if a similar problem has occurred. Beyond that, it's hard to discern anything with the information provided . . .
Yeah, that's about where I am. I have sent them the footage, with a very general idea of how I've had it happen. I know at least one other person has seen it, but very rarely. I suppose that, worse comes to worse, I can write code that will fix it in real-time for my own product... but it really bugs me (pun slightly intended) that I can't figure out why this is happening. 😄
third-party asset issues are hard to debug/fix because someone (here) would need to have used it . . .
So noted. Mainly trying to figure out if there are any good techniques for finding what might be changing the scale.
Though, I would definitely check the animation . . .
don't have your projects in a onedrive folder
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.
The documentation for the call is super vague, not really specifying what requirements exactly need to be met for it to function
Are you sure downloads doesn’t remap to OneDrive? Try placing the project in a new folder in the root of the C drive
i need help when the player is standing and when walk he lays down and walks
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
Honestly just leave it that’s hilarious
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
fr how do i fix it
we cant really do anything if we dont know how it works
send the relevant !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
although from taking a look at this. i assume you just forgot to constrain the rotation of hte rigidbody
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
Initialize them manually in a loop or just use a class
Class allows field initializers
I... want different sizes, that won't work probably?
you mean in awake?
I mean wherever the code you showed is
in a constructor for the struct
public MyStruct(int arrSize) {
myBools = new bool[arrSize];
}```
or using an object initializer
this code is just hanging nowhere, it's not executing on runtime
...I guess
MyStruct ms = new MyStruct() {
myBools = new bool[56]
}```
it compiles allowing me to predefine size for an array
Ah , yes, for example
You can't really do field initializers for structs
and I want different ones
then make them
Then a field initializer wouldn't help you anyway
myStructs = new MyStruct[] {
new MyStruct() { myBools = new bool[5] },
new MyStruct() { myBools = new bool[5463] },
};```
You're going to need to set them individually whether they were classes or structs
mindblowing
or the old fashioned way:
myStructs = new MyStruct[2];
myStructs[0].myBools = new bool[5];
myStructs[1].myBools = new bool[324];```
yeah this old way would prolly only work runtime
...fair
If you're talking about setting something up for the inspector you need Reset() or OnValidate()
i don't think you can do this in a field initializer
but maybe you can'
ok cool
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
why not
what is a niche for that
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
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
It’s not the boxes responsibility to decide how to ideally fill itself
I guess I am too rookie so I never encountered a need to have some optional array of data
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)
I was redacting an example with cats with fur vs cats without so you have me beat either way
It's valid to return null instead too (and have the caller handle nulls)
yeah but then you need a special case
Don't think i have ever initialized an array with 0 length
you need to write those if statements
it's uggo
every caller needs to check the special case
generally you don't need to be aware
That's automatically handled if you use a for loop or even foreach
generally for arrays you're just doing foreach (Leg leg in legs)
It just... does nothing
won't for return error if length zero?
ex ^
no
why would it
I recall having issues with for and arrays of length zero
for (int i = 0; i < legs.Length; i++)```
but I don't remember details
you're misremembering
or thinking of a null array
maybe I am thinking of null array
almost certainly
...yeah I recalling the null reference exception
and what foreach does about null array btw?
nothing without throwing an error?
NRE
okay i forgot where I have screwed up that time
foreach would call null.GetEnumerator which would throw the NRE
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
Have you logged it? The tangent for the first and last are probably 0. I think the tangent can only be calculated when there are points before and after the knot maybe?
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
yeah teh tangent is the zero vector
should the tangent not be 0 in all of them?
just checked, after evaluate, the first and last knots produce a tangent of 0,0,0
whereas the other knots, do not
did I misunderstand the way this is phrased?
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
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
funnily enough, I previously had those, but when I noticed the two ends being incorrect, I assumed it was a result of those
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 😄
note there's no reason to have the number of mesh subdivisions(vertices) match the number of knots
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 ...
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?
As I wrote in the other channel, show the code. Checking it for null with == null should be fine
You should step through with the debugger so you can actually see every value. If a value doesnt align with what you expect, you'll have a lot more insight to what's actually wrong.
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);
By debugger do you just mean using debug logs?
Visual studio debugger, it would be easier in this case since you can use breakpoints and go line by line. Debug log would be tedious but yea it can work too
Ah, sorry. Overlooked that:```cs
UnityEngine.AudioSource o = ...;
// ...
// later:
if (o != null) {
UnityEngine.GameObject go = o.gameObject; // Crash
//...
}
When you say crash, do you mean unity actually closes or you just get an error in console?
The Unity Crash Handler pops up
That window with the exclamation mark. And then the game closes.
honestly ive never seen SoundSource before, so im not really sure what that is even. doesnt seem to exist on the docs either
I quickly copied this out of memory on my phone, just came back to my PC. It's AudioSource
The rest is accurate though, just double checked
you should show the actual code from the start to avoid stuff like this. Although that code itself seems fine. Is there anymore info in the window that pops up?
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
How are you getting the GameObject?
One way to solve it is inverting de dependency and make the AudioSource dispose itself during the OnDestroy()
In Debug view you can check what exactly is happening to data inside of the object. If in Inspector increasing the size only increases it downwards, I assume pivot.y is set to 1. Check out if your code changes .anchoredPosition alongside with sizeDelta.y. If it does, I would suggest changing it back after modifying .sizeDelta.y.
I have fixed it by checking o.IsNativeObjectAlive() instead of o != null
It's working perfectly now
hey team,
I'm having some issues with my animation transitions.
- the animations work if they're on default
- The transition is occuring (i.e. the "Slow Run" is active (i've got a isWalking bool that turns on correctly)
- But the slow-run animation isn't being run
Any thoughts on why that's happening?
#🏃┃animation question probably. check if you have animations on other layers that are overriding this (and check for an avatar mask too)
Thanks Rob, no to both. only a single layer, and no masks set up.
animation plays in the "preview" pane as well.
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?)
thanks. i'll keep having a play
Hmm... so it looks like it probably is an animation, but it might be an overridden one? Does anyone know where one would look to find the current override?
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..🦆 🦆
OK, found a way to name the current override, and found that there is one being generated based on the initial setup.
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?
vector is just a struct of 3 floats
Is it worthwhile converting vectors to floats in computing speed
You cannot implicitly convert them
into what
float value, vectors inherently are more baggage compared to floats
which is my whole concern
what about float3 ?
in what sense?
yeah like your own implicit conversion ? is that a biggie
Are you talking Unity.Mathematics.float3? There's already conversion operators between the two provided
pretty sure V3 is implicitly convertible to f3
Raw speed as far as I am aware, I am trying to optimize my code and saw this type of way in handling vector
whats the use case? what is tons of computation ?
Like 100k meshs
There's nothing inherent about float3 that is fastor or less memory. It's the math functions in the Unity.Mathematics library that are optimized
float3 and Vector3 have the same exact footprint in memory afaik
But to use them I must convert the value of my existing variable to accept it. Is this worthwhile?
ya I was under the same impression
You don't have to do much to convert them
you just call the functions
they are implicitly converted
Any time you pass Vector3 into a Unity.Mathematics function it will be converted to float3
because they only take f3 parameters
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
I have never worked with the unity.mathematics before
If you're not using burst you miss out on most of the optimizations
even this works afaik```cs
float3 myFloat
myFloat = new Vector3(0, 2, 3);
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
So is it creating garbage?
computation time doesnt always mean garbage
allocating objects on the heap creates garbage
Would this be considered the most optimal method?
the most optimal method to do what
Handle large numbers of vectors
^ still unclear what you're doing with these 100k meshes
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?
Voxel rendering
If you start using Jobs/Burst, then yes you will benefit from using Unity.Mathematics
multithread / core is awesome!
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
git for VC
many, many projects
Github for me is fine
LFS is per file. what do you upload thats bigger than 1gb ?
the hub is fine, though I don't have many projects . . .
& imo should probably not be in VC if its some type of big art asset or something that big anyway
I think the github LFS cap for free tier is for all your repos, not per-file? It wouldn't make sense for them to let you store a infinite number of files
https://docs.github.com/en/billing/managing-billing-for-your-products/managing-billing-for-git-large-file-storage/about-billing-for-git-large-file-storage#about-billing-for-git-large-file-storage
huh did they change it ? it used to be like 10gb or something like that
but I guess Gitlab has that still iirc
Configure the maximum number of projects users can create on GitLab Self-Managed. Configure size limits for attachments, pushes, and repository size.
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?
iirc the total for "regular" repo is total 5gb still no ?
It might be? But it doesn't seem listed here https://github.com/settings/billing/plans
I don't see LFS storage listed there either. I only see it in this page: https://github.com/settings/billing/summary
And again, no mention of storage space for the repos there either
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":
dropbox 😏
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
Dropbox on the library folder 😢
dropbox , google drive etc.. is acceptable for art assets
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
one reason dropbox sucks for a project like this ^
yeah my boss was shocked that such a thing was remotely possible
that is absolutely bonkers they even used a system where you could do that
Code reviews are one big advantage version control has over a system like Dropbox
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
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.
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
fixed
It would be easier to help you with your coroutine approach, as not many people know that tween asset.
i use the tween in the coroutine as well. i wont not use tween
maybe the issue isn't in the tweening
can I use there where keyword (when defining a class with a type parameter), to limit the class to not be abstract?
no
like public class MyClass<T> where T is not abstract
I'm trying to get this to work
thats why i tried using wait in corutine and now use events....
i dont get why the code is even called before the animation ends... i tried debugging each second, but couldnt find out why now...
where Foo<T>() where T : new()
niiiiiice, thanks!
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?
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
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.
easy, use the steamworks api or similar to get info and use it?
here the drink is a child of the player, the object never moves, but its transform updates.
reason for using the gizmo is just to give an obvious indication the item was picked up by the player and actually moves with them
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
actually, thinking about it, the position of the drink should have a local position of 0,0,0
are you changing it again somewhere else?
e.g. another script or an animator or a constraint component
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
it can still work if you use rigidbody.MovePosition() for example or if the rb is kinematic.
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?
im not getting any help
you are meant to use the argument as the "job index" so im not sure why you are trying to grab the thread index
my character's arm keeps coming apart
it doesnt rotate when kinematic and when dynamic it comes apart from the body
not a code question, ask in the correct place and give more information so someone can help you properly
ok
to store a minimum value and index local to each thread, but it doesnt like that
using the job index to calculate the error (but that isnt in the sc i put in)
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.
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)
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
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
you could look into IK animations and have it be a little more dynamic, if you want to go a super "realistic" way of wrapping the enemy
Interesting problem... Could calculate a convex hull out of the enemy's bone positions and somehow wrap it around that
personally I'd try to do it as a shader on the enemy's mesh, rather than a separate net object
Another idea is create a lattice for this net's mesh and each enemy a SDF of points where the lattice points would match
My suggestion would be doing a network of configurable joints (watch Youtube tutorials on how to make ropes and bridges). You should skin your net mesh and link the bones to the joints. It may be jittery but when erasing all parasites like elasticity on the joints, gravity on the rigidbodies... You might manage something
--
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)
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
@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
do it the gamedev way: fake it
vfx graph is pretty good idea to grab data from from the current skin render it's wrapping
if we care about physics
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?
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
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
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
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?
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
oh, ICloneable seems perfect, thanks!
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.
oh, yeah, just realised... that's such a shame
There's just too much involved for a way that is automatic
Even reflection might not work, or map irrelevant content over
It's not difficult, just make a method
if I remember correctly, C++ would make this super easy
C++ doesn't worry with references, though
yea but I don't want to create a separate method for all 20 classes I need this to work on
or so
Is using structs a possibility?
c++ has simpler memory management
in c++ a copy constructor is basically just copying a block of data, then checking if subblocks need to be copied
sadly, not in this case
I need it to possibly be null
isn't copy constructing recursive?
although I guess I can make a nullable struct
That would still end up keeping references to nested reference types, fyi
Not sure how nullable structs are copied
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
Also, just making it a struct for the sake of not working with a reference is a very bad idea
This is not relevant to the C# version, this is still a problem in modern C# due to the fact that structs can skip constructors
The idea was "for the sake of easy copying"
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
protobuf messages are given a MergeFrom() and Clone() function, not hard to add your own
Does Unity support Records?
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
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
why does it say this then
there's a little benefit using records than just regular custom class/struct
all custom classes/structs can do what records can
My struct knowledge with this doesn't go too far unfortunately
wait, if I change the ScriptableObject data, it won't update my objects anyway and the overrides will be equal to the old data...
Read this, though: https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/choosing-between-class-and-struct
goddamnit I have to figure out sth else
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
You can just try the Json serialize-deserialize combo and see how it works for you
If you want the same data that unity serializes then plain old JsonUtility will work
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?
You can use the Bounds of the renderer(s) or collider(s)
For example, myRenderer.localBounds.size.y
If you always have a certain collider you can use the collider's size.y or height property
Hey there! I have a little problem with the pick up script. When I drop an item above horizontal it drops normally, but when I look down a little and drop the item, it teleports to the cameras 0,0,0. Any Idea? I cant figure it out. :/
Heres the script: https://hastebin.com/share/eqovajiqat.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
it's probably colliding with the player
Yeah, I think so, but I don't know how to fix it.
don't drop the object inside the player
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
start debugging
add a collision callback to the object and print out what, if anything, it's colliding with
yeah, thats a good idea, i'll try. Thanks!
How can I export CSV in Unity to an already open file so it automatically updates the values?
Is that even possible?
wdym an already opened file?
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
As long as the file can be written to again then you can.
This for example
https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendtext?view=net-9.0
Unless your text editor is scanning for changes, changes to the file won't update the opeed copy.
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)
Any way to enable/disable the "Render Shadows" option in camera programatically?
what render pipeline are you using?
Default
I don't see a "Render Shadows" option on my camera
(this is in a 2022 VRChat project)
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
camera.GetComponent<UniversalAdditionalCameraData>().renderShadows = false;
This works I think, cheers!
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
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
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
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
Cause I want to use another script to be able to edit them for a shop
A compromise is to set the default values you want in Start or Awake
which will override whatever's in the inspector
If theyre public but NonSerialized I can still make like a "Buy Flamethrower" button that adds 1 to it
Yeah
Wait where does [NonSerialized] go
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
you'll have to add a using System; directive if you haven't already
If this works
auto property would work too
(or spell it out explicitly)
that would give you the same result, yes
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)
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
how are you doing this? the built-in JsonConvert only supports things that Unity can serialize
(and dictionaries are notably not serializable)
I have a SerializasbleDictionary class
Probably meant JsonUtility.
ah, yeah
wrong one
I'd suggest using Json.NET if you want to serialize anything complicated.
yep I'm using JsonUtility.ToJson when converting
someone pls
Will JsonUtility use mechanisms used by SerializasbleDictionary class to handle serialization?
I'd expect it to work as long as the type shows up in the inspector correctly
I've tested it and it's able to convert into json cleanly when using the default supported types like primitives
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?
one option would be to put the rigidbody on an empty parent object
No parenting can be done.
why not?
if you have no idea why, reconsider
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
it's certainly unreasonable to assume that it won't work :p
i do feel like there should be another way
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.
So, I would like to just know how I can make a rigidbody rotate about a position.
yo, for some reason my instantiated object is not behaving correctly
what does " not behaving correctly" mean
my instantiated transform "buffPanel" is still null
just switched over to json.net and it's all working perfectly! Thanks!
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)
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'.
Json.NET looks for properties and serializes those
this repo adds custom converters that correctly serialize common unity types
awesome!
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?
My project is due tomorrow