#💻┃code-beginner
1 messages · Page 14 of 1
type switch or is statement
if (item is Armor) { or if you need to access stuff on Armor
if (item is Armor armor) {
what Passerby said, but why are you adding them to separate lists?
if you got more cases you can do the same with a switch where the switch is on the object, and each case is a type
switch (item) {
case Armor:
break
case Weapon:
break
default:
break
}
can also have it cast for you if needed by adding a name after the type like in the if example
though in your graph notice your subtypes do not have actual new or different fields on them
I decided to go this way because I want to avoid having to sort the list by type, and I want to display different inventories* at different times. Ideally, when the player clicks on an armor slot the inventory area will display the armor of that type, same goes for weapons. If no slot or filter is selected, the inventory will show a list of their generic items. Green = Inventory space, red = specific slots
so might also just model this all in data not in inheritance
I left a lot of them empty since there are no "physical" items to build just yet. I am trying to get a working / scalable interface before I start adding actual items with proper data attached to them
and some are literally just there to define a type, like with armor.
either way the type checking via if or switch like i showed will work
yeah I switched the method to is already, but I am Definity considering switch especially if we end up adding more
its also very good for cases where you got a parent type, and need to check what subtype it is to act on the extra data
switch (item) {
case Armor armorItem:
// do stuff with armorItem
break
case Weapon weaponItem:
// do stuff with weaponItem
break
default:
break
}
for example
anyone know how to fix lines in tiles glitch
you are providing the instance you are checking the type on
so my game runs just fine from the play button but when i try to build it i'm getting this weird NRE that's in the editor codebase not my code, what's going on?
at UnityEditor.Rendering.AnalyticsUtils.DumpValues (System.Collections.IList list) [0x0000c] in .\Library\PackageCache\com.unity.render-pipelines.core@14.0.8\Editor\Analytics\AnalyticsUtils.cs:97
at UnityEditor.Rendering.AnalyticsUtils.GetDiffAsDictionary (System.Type type, System.Object current, System.Object defaults) [0x00106] in .\Library\PackageCache\com.unity.render-pipelines.core@14.0.8\Editor\Analytics\AnalyticsUtils.cs:185
UnityEditor.EditorApplication:Internal_CallGlobalEventHandler ()
Error building Player: Exception found while parsing UnityEngine.Rendering.HighDefinition.DiffusionProfileSettings[] m_Value, System.NullReferenceException: Object reference not set to an instance of an object
at UnityEditor.Rendering.AnalyticsUtils.DumpValues (System.Collections.IList list) [0x0000c] in .\Library\PackageCache\com.unity.render-pipelines.core@14.0.8\Editor\Analytics\AnalyticsUtils.cs:97
at UnityEditor.Rendering.AnalyticsUtils.GetDiffAsDictionary (System.Type type, System.Object current, System.Object defaults) [0x00106] in .\Library\PackageCache\com.unity.render-pipelines.core@14.0.8\Editor\Analytics\AnalyticsUtils.cs:185```
From a quick google, it seems like the diffusion profiles list includes some null values:
https://docs.unity3d.com/Packages/com.unity.render-pipelines.high-definition@14.0/manual/Override-Diffusion-Profile.html
Check your volume components for any diffusion profile lists that might be culprits.
I only have a single volume, my starting Sky and Fog Volume, and I don't see anything about diffusion anywhere on it
....it just worked even though i didn't change anything
weird but ok
For weird unexplained errors you might want to try restarting editor, removing affected package in Library or regenerate entire library folder if some meta data borked.
hi for some reason my code whenever i instantiate an object it does it twice. once as a child of the parent i told it to go to and one just in the game not under a parent
any ideas?
need to see code . . .
{
Instantiate(genTube, cylinder.transform.position, cylinder.transform.rotation, instanHolder.transform);
}```
thats in the update loop
is this the only code?
no the only code that mention instantiate
place a log before Instantiate and see if it appears twice from the console . . .
oki
You are not showing the important part where you set it to false to lock it. Also Debug.Log is the first thing you need to do with objects reference parameter as well to check if you don't have other copies of the script.
i wont be able to tell if it appears twice or not
cause as soon as thats activated it will call it every frame
I need some assistance for a game jam due tomorrow
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
use a paste or bin site to share your code . . .
Alright
The issue I am having; it is destroying my tank, when I want it to shoot out of the enemy at my player tank. The aiming seems to work, but it is not shooting, or maybe it is but instantly destroying my tank, the mouse down part works, but it seems like the just regular shooting one isn't; I've used multiple different ways, just this is due later today, and my "group" for my game jam provided me with 2 tiles in total for a 7 man group, so I'm trying to build the whole game in my first 2 weeks
Im not sure how your game works entirely, but is it a possibility that your bullet object is colliding with the tanks own mesh and killing it?
I believe it's shooting inside of the tank, and destroying it as well. I can set the health high and remove the 2d collider to test
where does the bullet shoot out from?
the spawn position used for the bullet should be at the tip of the cannon . . .
The bullet shoots out of my tank perfectly fine, but the other one I don't think is even shooting come to think of it
There are two sprites, a robot used for shooting at my tank/trying to stop him from completing the level, and the tank, who shoots bullets
The getmousebuttondown if statement is for the regular tank, and the timer one is for the other
I was trying to make it shoot from my laser prefab, but realized it can't hold gameobjects (not sure if it's true but looked like it), so I moved it into my managerscript which handlesmy other bullets firing and thought if I changed the values to what I thought it would work.
It appears when I shoot though it destroys the tank, so I must've done something wrong with colliding
https://gdl.space/watuqupadi.cs
I put it into a seperate script, maybe something will stick out to someone?
does anyone know how i can get this directory in vscode? ive been trying to unlock vscode editor in package manager and it keeps locking itself. is there some save option i gotta do in package manager than i cant see?
Check the dependancies tab
Do you perhaps have the Engineering package?
Also, vs code now uses just the Visual Studio package, not the vs code one, since august 8th
idk where the dependancies tab is but i do have the engineering package, if thats what this is
wait really?
oh
Dependencies tab is in your screenshots here
#💻┃code-beginner message
On the right
They are, they just both use the same package now
Remove the engineering package to unlock those packages
okie
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
i still dont see the dropdown directory (and im only screenshoting cuz its a vscode thing)
(in the middle of typing TransformDirection)
You want a string variable, and you set the TMP_Text to that variable, if i'm understanding you right
public string textIWant;
like this. I did think that. Just didn't know how to implement it into my script
updatetext.text = answer;
Do you mean like that?
Just setting the text?
omg. I think I have having a stupid moment. I should of known that. Thank you.
Yeah, it feels weird sometimes doing somethingTEXT.text
Just keep in mind that TMP_Text is the component, not the actual text field.
I get it though. Happy I helped!
Yes. I know this. I've been spending like 12 hours a day studying C#. I've just woken up. That is my excuse. Thank you though. You are extremely helpful and is very appreciated
if the other is active, yes
ok great thank u
its not switching to the other camera
when i set it to active = false;
i just get no display rendering
Trying to set camera background colour to Color(99.0f, 99.0f, 99.0f, 255.0f) and it gets set to Color(191.0f, 191.0f, 191.0f, 255.0f) instead. What might be happening?
Color values are between 0 and 1
Thanks! I thought they went all the way to 255. Weird that the values are being set to 191 instead of 255. Anyways, thanks again!
If you want to use 0-255 there's Color32
Hello, i would like to make a simple camera script in first person where the camera rotates up and down and the body rotates left to right but instead of the player being always straight up he can be in any rotation, for example the camera should work as a normal first person camera when the player is tilted 90 degrees and standing on the wall, I have this for the body rotation, where frame velocity is the amount of rotation in 1 frame from the mouse :
character.Rotate(cam.transform.up, -frameVelocity.x);
But it doesn't work
how do i reference script's float value from another script?
Check out the Course: https://bit.ly/3i7lLtH
Learn 5 different ways you can connect your gameobjects in Unity. Ranging from direct references & singletons to scriptableobjects and injection.
More Info: https://unity3d.college - (and where you can submit your own questions)
Join the group: http://unity3d.group
Error seems to suggest that dateOld (not _dateOld) can't be converted because it isn't a valid string for ToDateTime. Log dateOld and tell us what it is
?
^
anyone know why my trees in my terrain look blurry and grainy but when i get closer they good more high quality
from this:
to this:
It's billboarding to save the frames. You can increase or decrease from the distance it does that.
Its somewhere in your terrain settings, afaik. Check the docs or #⛰️┃terrain-3d
I put everything high for my game, so it only billboards in the distance.
hey guys I was following the Game Maker's Toolkit tutorial to make my first game, a flappy bird type game and while trying to implement character death I changed the if statement on line 27 so that my command will only register if the boolean on line 11 is true i got no errors but now when I run the game I have no input as in I press the spacebar and no upward velocity is added to the bird
You made birdIsAlive public, so it's serialized in your editor, aka you can change it in your editor, and it is probably on false. It completely ignores the values you set in your script if it's serialized.
i changed it to private, didnt fix, then just cut out the private, but that didn't fix either
Hmm, well, there is something weird that you have a constructor, are you sure you don't have any errors in your console?
Move that part to either Awake or Start
Constructors don't work with MonoBehaviours, so I'm not sure why you did it this way, is that in the GMT tutorial? 
Also, private is the default state, so if you don't put any access modifiers it's private.
is there a specific style that this has
Probably a #archived-lighting or #💥┃post-processing question, nothing to do with coding
How do I turn a rigidbody's velocity and rotational velocity to 0
Since resetting it's rotation with quaternion.identity makes it keep on spinning
what have you tried or searched?
Same with resetting it's position
Not much really
I think I have before and just decided to fix other bugs before that
I was sure that returned a read-only error
sure, as in, you tried it or just guessed?
Pretty sure I tried it but as I said it was a while ago and I don't remember
Hey guys, I need to find a way to save player progress.
I searched for some tutorials, but everything that I tried didn't work, can anyone help me find a good way of saving player data?
do you need saving between play sessions (ie application closing)? or just within a play session (ie respawning)?
Saving to a JSON text file is pretty common
between play sessions, the two main options are: 1) PlayerPrefs package (which you have to download). Playerprefs is good for quickly saving really small bits of info separately, like “This tutorial textbox has already been shown once on this save file.”
2) Save a JSON/BSON text file to persistent application path. Better if you need to save a big thing, like inventory
Is playerprefs a package now?
i got it off openupm
idk if we have a built in playerprefs. I just saw it on openupm and snagged it
PlayerPrefs is in the UnityEngine namespace builtin
yeah PlayerPrefs is built in. not really suitable for save data though
I use it for debug settings, thats pretty much it
from what I understand, PlayerPrefs is best for one off tiny little things
PlayerPrefs was the original way for saving stuff. it's been there since the beginning . . .
i too enjoy bloating the registry with random bits of data instead of saving it to a file somewhere
/s
it's not though. it's meant for preferences for the application (aka player). hence the name
it's random tutorials that "market" it for saving in-game save data
this is not unity's player prefs
because “score” is a preference to be saved
What is the name of that package
i’m not talking about unity playerprefs
Unity PlayerPrefsEx
that’s the full name
i wonder if they needed to add the ex to avoid the conflict?
☝️ oh, you never said the before . . .
ew PlayerPrefs.
Well it wouldnt make sense to call it PlayerPrefs since it already exists built in 🤷♂️
i didn’t know playerprefs was a built in unity thing tbh
yes that package is just an "extension" for it and still uses unity's PlayerPrefs under the hood. so it's just saving your data as json strings in the registry
do yourself a favor and learn how to save properly, to a file
i only save things to JSONs right now
that's all you need
PlayerPrefsEx mostly promises to help save really small random bits of data so you don’t need to code a bunch of crap to save a random bool
like “TutorialTextbox420AlreadyDisplayed”
ie one off little things
You're gonna have a bunch of random strings in your registry for bools?
yuck
yes, that's what this package is marketing itself for. however it is still using PlayerPrefs under the hood which is not meant for save data as has already been explained
"i'm using this tissue box as a shoe. i wrote 'shoe' on the outside of it because i want to market this as a shoe"
none of that makes it any saner to be using a tissue box as a shoe
i’ve yet to give it a whirl, but given it has a ridiculous number of downloads, apparently it is being used a lot
and I can’t envision people using it for something outside of saving little knick knacks of data
There was a pretty recent controversy about Kerbal Space Program 2 using player prefs because it left users with gigabytes of data in their registries that wasn't cleared out when the program was uninstalled and could only be removed manually.
If you're going to be saving any more than like, a bakers dozen atomic pieces of data, you should be using a custom solution that puts the file somewhere the user can easily delete
how much are they paying you (just kidding)? 😆
Oh wow, thought PlayerPrefs had a 2KB limit
was KSP saving like a whole level’s of data to playerprefs?
i think only webgl has an actual upper limit for amount of data that can be saved to player prefs. though if there is a 2kb limit then it is probably per key
i’m talking about something like maybe 300 bools/ints max for a gigantic AAA project.
ahh ok was about to say.
that makes more sense. Per key, but still why would they do that (KSP) lmao
Because it's easy
Doing things the right way is harder
there’s nuance that got lost in translation lol
Unity really should add in a data saving package or something at this point because the player prefs system has been abused for over a decade at this point
yeah really wouldn't even take much..
It was a very early feature added back when unity was mostly a novelty and it's an albatross around the neck of modern games
That would be wonderful, if they actually worked with console manufacturers to make it a shared API there, 🤤
Make that the keystone feature for unity 2024 and I'm sure people would reconsider sitting on their current version
People who are considering sitting are already missing out on a lot
great, now they're going to start a new feature. i wonder what gets put on the back burner? 😆
A twelfth render pipeline
@languid spire don't you already have smth like this?
you wanna do PlayerPrefs right use
https://assetstore.unity.com/packages/tools/utilities/player-prefs-lite-222004#description
and it's free
aye!
I think Unity should be able to install a game directly into the Windows Registry
store allllllllll of the game data in there
cries in MacOs
I think you need to go and lie down in a darkened room
.plist time
In the history of Microsoft making bad decisions, the Windows Registry almost certainly ranks as the most badly thought out, badly designed and badly implemented decision of them all
for which we pay the price every single day
it's kind of insane there isn't a Unity standard for it, it's invariably one of the first significant hurdles that trips up people using the engine, shortly followed by a google search "how do I save my game in unity", and then into a string of scuffed youtube tutorials using awful shortcuts and misuses
I'm trying to access my sanity script from my flashlight so i can increase my sanity when it's on. Any reason I cannot access the script?
and what is the error?
yep, hence
https://assetstore.unity.com/packages/tools/utilities/save-for-unity-core-242812
and the rest of the Save for Unity eco system
I'm assuming cause it's a UI? it's a slider
no, it's because a SanityManager is not a GameObject
that's it
I presume SanityManager is a class you created.
that extends MonoBehaviour
GameObject is something you can attach components to (and MonoBehaviours are a kind of component)
If you want to store a reference to a SanityManager, then make your variable hold a SanityManager
yeah, kind of off-topic question for this channel but how do you feel about Unity missing what I'd think would be core features for a game engine, and offloading that to people like you who can sell the solution? would you mind if Unity implemented it and cut into your asset use?
Not at all and you know why? Because Unity know less about their own engine than publishers like me and put less time and effort into providing solutions to problems that actually work
But to come back to the crux of your question, I have designed and developed more custom game engines over the years than I care to think about, not one of them left me without having a save/load system. The fact that Unity only has PlayerPrefs and JsonUtility I find totally unacceptable and just shows the lack of understanding of game dev that I have come to expect from them
That makes sense. Thank you for teaching me something new. I'm just a bit confused because I'm grabbing similar scripts onto other scripts if that makes sense?
have you ever had contact from them about bringing your tools into the engine, similar to TextMeshPro?
Nope, Unity don't like me, I criticize too much
haha, fair
Kind off? So I have 2 scripts. 1 handles my sanity(SanityManager) and the other I drag onto anything with a box collider and by using the unity events, I can lower, raise sanity via on trigger enter/stay/exit. I'm now trying to get my sanity to raise when my flashlight is on. Shall I share my codes for the 2 sanity scripts and the flashlight?
If you need a reference to the SanityManager, then change your variable to hold a SanityManager
you can then drag the SanityManager into that field in the inspector, or get it at runtime with GetComponent
once you have it, you can do whatever you need to with it
@twilit pilot I've got a new asset in the works, Real Time Collaboration, something Unity should have done long ago, hopefully this time they will sit up and take notice
could you dumb this down for me. I do apologise. :/
yeah, sounds like a big one, looking forward to seeing it
even better, the basic version will be free
hey, im trying to make a security camera rotate within set limits, but im not sure how to do it really
Hi I am a beginner and was wondering what updating unity did with existing game files? can you still open them? how does that work?
so theres a v2 with the limits, and a float for the rotation speed
which existing files?
using Clamp
I mean my existing projects
Your prooject files are associated to a particular verision of Unity
whatever you used when creating the project
You can upgrade a project to whatever version you want but with caution, if the version is too drastic.
Ie 2021 to 2022 . Depends which packages you have.
ah okay and if you update unity, will you just be able to open the older projects in another version?
What do you guys use for a c# script???
why is 2021 to 2022 too drastic? what changed?
visual studio
like you can use note pad but what third party software should i use
ok
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
thanks!
Not much core wise, but some assets (custom ones usually) depend on a particular version of editor
anyway you should alwasy be using Git / Version control anyway before any updates
i prefer making a copy of the project folder into a different folder. who needs git
thats not very smart to do lol
why?
you're probably also copying the Library folder
that's old school, for sure . . .
so your backups must be gigabytes
because it doesn't keep track of your changes
there is reason why git is standard everywhere. trust the standard practices
ive never needed to though
i had .bat script when i started which copied folder and saved it as zip but its not efficient at all
what if github pulls a unity and claims all the code posted on it as their own? 😱
all the people who are leaving unity for trust issues should think about this
Microsoft is making enough money from github to not do such a thing
how else they will train github pilot 😛
they need free code
i mean repos
git is not github.
they're using our code to train AI? 😱
if you don't understand that, then i'm not sure you're in a position to make sweeping statements about the value of version control
well whoever owns git then.
more likely , hey not everything is free
no one "owns" git per se
github is just a host
like bitbucket
etc
i think my point is making itself here.
You own git
guess who? yes you
wait me? couldn't be . . .
If github were to be suddenly deleted right now all that would happen is I'd spend the next hour going through all my repositories and doing a git push --set-upstream [some other web URL]
and that's it
I use git entirely locally for a number of small projects
I have a git repo for my house that I have various tax and financial documents with the repo server on a WD external hard drive I have plugged into my router
I self-host a server
Doesn't have to be online, doesn't have to be code
what're you using for the server, btw?
i could use something that's not a full GitHub clone
I don't actually need a server, all the computers that can access it have it as a network hard drive. Effectively every computer is using a "local" git repo, but that local copy is a different drive so I have redundancy
Ah right.
I've done that occasionally: clone from a local repository
it's distributed!
reminds me of Llama academy
If the house like, explodes, I'll lose the repo, but if that happens I'm pretty sure I'm not gonna be too worried about my 2017 tax returns
put the hard drive in a lead-lined fridge
Is there a way to turn a dictionary into an array without iterating every item (or, better, a way which is computationally cheap) or a way to copy a dictionary without iterating or at least cheaply?
not really. the internal structure of a dictionary is not a neatly packed array
maybe the keys are
a dict has a list of its keys and values . . .
need the values T.T
why do you need it to be an array
can you not just use myDict.Values directly?
Also a list
what are you trying to do with it
there's basically no way to do something to N elements without doing N operations
I guess you could reach into the dictionary and steal its Entry[], but that sounds abysmal
explain your actual problem
No, sadly not - they need to be merged with another list of the same type as the values
argh, it's waaay bigger and harder to explain that
i'll try..
can't you just do theOtherList.AddRange(myDict.Values)?
if you can't explain your problem to us, then you probably haven't given it enough thought yet to be implementing a solution
we know but you can just add them to another list . . .
It lags. That's what I'm trying to avoid by creating a copy of the values and sending both lists to a different thread, then sending it back to the main thread merged and finally using the list.
creating the copy itself will be an issue. I believe we were discussing this before.
but you can't create a copy without iterating them
impossible
Worked flawless until I encountered some error because the KeyCollection actually didn't copy the dictionary but it was a reference to it, so when the main thread and the other detatched thread used it in the same moment, it crashed
Yes I was helping you the other day with that issue
I can, it's simply large
I'll try
Ahh! I remember
tysm for some days ago
dealing with references across threads?
it's the same probelm though, just hadn't time to find another way, today I spent some time to try to find a solution but couldn't find any
Basically, I've got a dictionary of type GameObject, NavMeshBuildSource. Every object of my game (many, many objects) that has a collider will be carved into my navmesh. It's added in this dictionary to be easy accessible to its navmesh, so I can add and remove obstructions into the navmesh simply by adding and removing the sources inside the dictionary with a gameobejct. This works perfectly well, it simplifies a lot everything. Problem: for many reasons, I have another list of navMeshBuildSources. The dict contains most of the objects, the list contains some external objects that could not be added directly for many reasons to the dict (for example, they were not linked to gameobjects). The code worked like this: every object that needs to add a navmeshbuildsource simply uses the dictionary. When it's time to build (some conditiosn trigger thsi event, like adding or removing an object or a chunk) the dict and the navmeshbuildsource list are merged into one in a single navmeshbuildsource list. Once it's done, I just call UpdateNavMeshDataAsync with the freshly new list as an input, and it simply works. Everything is cool until I try to optimize my game and realize that both the creation of a list from my dict and the addRange used to add the other list take a lot of time, because they got on average 20k objects total inside. What did I try? I created a thread that listens to new calls ready to merge the two lists. When the main thread has the buildNavMesh method called, it prepares the data (e.g. it copies the two lists in a thread safe list, a ConcurrentQueue), sends it to the detatched thread, and continues to do its business. The detatched thread detects a new list to be merged in the ConcurrentQueue, merges it, and sends it back to the main thread, flagging a thread-safe boolean. The main thread then checks on the bool and takes back the merged source, finally calling the UpdateAsync method.
Put a debug log inside the updatetext function. If it prints then this code is working and the issue is in playerui
But now I can't find a way to create a copy of the dict to be sent inisde the thread, where it can be safely merged.
brother i know what are you saying
If I create a copy iterating it (like a list), the whole point of reducing the lag is lost
can I paste my class in pastebin?
so you can better understand the code
explaining it it's pretty hard 😛
LookRotation on a child object
if you need to iterate fast and frequently, dictionary isn’t the best data structure
Yeah but changing it would make all the adding/removing navMeshBuildSources extremely hard to code
I mean it does its work
@polar acorn dm please
I can add and remove objects easily, the only problem is when I need to create a list from its values 😦
let’s start from a simpler position
- how many entries usually go in the data structure (non-empty things)
about 10-20k
no.
- What features need to be called most
ie add, remove, call by key, index, iterate, sort…
nvm i got it to work 😂
Well, add and remove, which is done always with the key (I add the gameobject and its navMeshBuildSource, then when the gameObject is being deleted I just call .Remove() on the dictionary with the GameObject passed as a parameter, so it gets removed)
maybe it’s better to ask: which features get called a lot every frame?
iterating a dictionary once is ok. iterating a dictionary every frame is sus
uhm... none? relative to this
it's not iterated every frame
it's iterated every time the navmesh needs to be baked
That's an example of the profiler
every time I need to iterate it, 10ms are taken away
which is like every 1-2 seconds?
in a worst case or so?
of player constantly doing as much as they can to fuck with the navmesh?
it really depends, it goes by distance (if I travel and a new chunk spawns), or if I place or remove an object. It's a sandbox survival
if 10 trees fall down in the same moment, might be 10 times in a frame. Which is nto bad, if I remove this iteration
but it might also be 0 times per minute, maybe the player is in the base not placing or removing any obj
Also currently the thread that merges the two lists sleeps for 100ms if the merge queue is empty
first, we probably should never call more than once a frame. your navmesh should probably wait for changes that frame to finish before baking
so in this precise moment worst case scenario is once every 100ms
have you tried using a ConcurrentDictionary?
It's a good improvement for the future, but this would courrently change literally nothing 😦 it happens extremely rarely (currently never happened)
true, but just saying that would need to happen
it seems to me like part of the issue is that you have so many things in your dictionary to iterate through
No but I don't need it: objects inside the dictionary doesn't need to be extracted. They must stay
not that you are using a specific data structure
yeah, that's always what everyone say. "You can't have so many objects loaded! Reduce your count" always seems to be the answer to my problems. Still, I always fixed every problem without reducing the loaded objects count. "Reduce your count" seems the easy solution when you want to sacrifice features for performance, but the hard solutions make you perform better with the same features. I look for those ones.
is !false is true and !true is false?
i’m not talking about reducing your count
i’m talking about reducing the amount you need to count at once
Yes that's literally the definition of the not operator
uhm, what do you mean?
Maybe reading, idk, 100 objects per frame?
yes but thought it only works in ifs not that i can for example setactive(!false)
ifs literally just take in a boolean. There's nothing special that if statements do that you can't store in a boolean
I considered it, that's the approach I do to things that can't be sent in a different thread (like the Instantiate method - it needs to be called once per object, and I got thousands of them, so I created an instantiate queue) but the problem is that an object could be added or removed during the reading phase, potentially creating nullpointerexceptions or other issues
let me better understand what you are doing: is it: Dictionary has everything; and then you iterate to filter to make a list of just what is relevant?
Dictionary has everything but the chunks, which are added manually every time I try to build the navmesh
is that why you merge and unmerge? like, what is going on
That's an example of the completely built navmesh
like the dict has everything really loaded, and the list has things loaded out of range which are relevant?
Row 202 is where I add both the terrainSources (the "base" of the navMesh) and the objectSources.keys (currently in an array format).
yeah, the list has around 30 objs, which are the active chunks
the dict is updated at runtime by other scritps
an object simply calls the Add or Remove method of this script, which itself adds or removes the gameobject and the navmeshsoruce from the dict.
Never lagged with an add or removed
you can ignore row 174 to 183, it's just for testing purposes when the game is not loaded via the menu but it's in the playground
i’m feeling like this merging might be the problem
well - if I could pass only the objectSources.Keys, and they're not iterated when I pass them, it would probably not lag and I wouldn't even need a second thread
but I need to somehow add the terrain, and they haven't got a single gameObject so I can't add them to the objectSource dict.
It would also be a problem to remove them
is the final output you need a list of navmesh build sources?
yes
i’m wondering if it would be possible to make the final output an enumerator instead
that doesn't depend on me, the UpdateNavMeshData takes it as an input
so the enumerator just first iterates through the list, passing each entry one at a time, and THEN it iterates through the dictionary
i’m just wondering if we could get an iterator in here instead, or a custom IEnumerable
it's so unfortunate they used List here and not IList or IEnumerable
so is the problem that it takes too long to create this list?
see if Visual studio can lead you to the source
Tried, it doesn't
He wants to iterate over a dictionary’s keys and a list (combined). But his dictionary is massive, so making an separate input list with everything combined is expensive as shit
and UpdateNavMeshDataAsync (the built in function he needs) takes in a list, and not an IList or IEnumerable
understand the problem?
if you can avoid modifying the dictionary for a while, you could build the list in a coroutine
smearing the work out over several frames
(any modification to the dictionary would invalidate its Values enumerator)
i’m thinking that there’s gotta be a way to avoid the needless and expensive operation in the first place
indeed
e.g. keep a HashSet and a List of whatever these values are
if you decide something needs to be updated, add it to the set and list if it's not in the set
(that will be more efficient than checking if it's in the list, but will also give you a list, rather than just a hashset that you have to transform into a list)
that might be the way. A very shitty but necessary way, if we can’t get the source code
I've done things like this before.
we probably can
Using one data structure to signal that I can put things into another data structure
If you just clear the list and hashset instead of creating new ones entirely, you also shouldn't have garbage problems
you'll just have one very big hashset and one very big list
but with a dictionary of 10k-20k elements, you need to make sure everything stays synced, and you also double the cost of using a dictionary in general to update everything
so you can get weird bugs if the two things get desynced
that’s why I try to avoid double saving the same data as much as possible
the easiest fix would be to get the source code for UpdateNavMeshDataAsync, and then make an extension method with an IList or IEnumerable as input
or even an IEnumerator
IEnumerator would actually be the cleanest imo
i have yet to use IEnumerator<T>, but I want to
can’t find the best guides for it tho
i mean, it's just like returning IEnumerator, except you yield something more specific than object
public static T Draw<T>(this IEnumerable<T> enumerable)
{
int count = enumerable.Count();
if (count == 0) {
throw new System.Exception("Empty enumerable.");
}
int choice = UnityEngine.Random.Range(0, count);
return enumerable.ElementAt(choice);
}
i wonder if this is actually iterating over the entire list if I call this on a list
i'm a little fuzzy on how that shakes out
it sucks that some of unity’s code gets injected from C++ behind a black box
My Plattform effector doesnt work properly that if i fall of the stage and i walk into the side of it that i slip down but its not working can anybody help?
what do you mean? platform effectors normally get rid of side friction
yeah but this one doesnt
check the dropdown on the platform effector under “Sides”
does it have removing side friction enabled?
"Use Side Friction" no checkmark
"Use Side Bounce" no checkmark
i forget which way that reads, but i’d first try flipping the checkmark
didnt work
and on side walls, you’re seeing the player get stuck (0 speed) or slow down (falling slower, but not zero speed)?
0 speed
that doesn’t sound like a friction issue
that sounds like a collider got snagged issue
I would quickly make a dynamic rigidbody (lock Z rotation) with circle collider, and give it a constant force component going right. make sure rigidbody has gravity. Put that right next to the side of the platform
tell me what you see
it probably also helps to make the platform very tall to have lots of testing area to work with
if you only see issues at corner, it is an edge effect. if you see issues in the middle, then it is not
make sense?
yeah i started unity like yesterday but i will try
if i was you i would read the documentation
will help you alot
eh still
no explanations
I will look into it after i solved this bug
the documentation is vital to your success
i'm making documentation right now. i think i went a bit overboard though . . .
should i send a video?
how do you only have scripts in a scene run when the scene is active?
i have an ingame timer for a game level, but i notice it still runs in the background even when the scene isnt loaded
your scripts will not run unless they are loaded into the game
unless you mean you have multiple scenes loaded
You'd have to show how you implemented this timer though
the normal Unity way would be:
float elapsedTime;
void Update() {
elapsedTime += Time.deltaTIme;
}```
public class WaveSpawnerLogic : MonoBehaviour {
[SerializeField] public int MaxGameTime; // in seconds
public TMPro.TextMeshProUGUI text;
public GameObject[] targets = { };
int currEnemyCount = 0;
public float gameTimeLeft = 0;
public static System.Action<GameObject> onTargetSpawn;
private void Start() {
gameTimeLeft = MaxGameTime;
}
private void Update() {
if (gameTimeLeft <= 0) {
SceneManager.LoadScene(0);
return;
}
UpdateTimer();
}
private void UpdateTimer() {
gameTimeLeft = Mathf.Clamp(MaxGameTime - Time.time, 0, MaxGameTime);
text.text = System.TimeSpan.FromSeconds(gameTimeLeft).ToString(@"mm\:ss\:fff");
}
}```
Well you're just using Time.time which is https://docs.unity3d.com/ScriptReference/Time-time.html
This is the time in seconds since the start of the application
I can also try with the dict and another list! That's a wonderful solution
ohh
Maybe you mean to use something like this? https://docs.unity3d.com/ScriptReference/Time-timeSinceLevelLoad.html
This is the time in seconds since the last non-additive scene has finished loading.
Though I would recommend just using a timer with deltaTime like my example above.
I can do some checks in the update to be sure it stays sinched and correctly debug if it gets unsynced
I'll try that now
yup, i for some reason didnt think to do that. thats a lot better. thanks
Ok that solution worsened the problem: the Remove() function iterates through the dictionary T.T
The remove of the list iterates 😦
Are you both adding and removing constantly?
What if you just update more regions than are strictly necessary?
so that you never remove single items
Every time I add or remove to the dict, I do that to the list
can't do, and even removing a single object lags now
when a scene is reloaded after you unload a scene, and all the game objects in it are cleaned up, how do you get new references to the new objects?
im getting a MissingReferenceException cuz my script doesnt get new references
which script?
You have a DDOL script I guess?
whats that 😃
how do I check?
Well you would be calling DontDestroyOnLoad in the script on its gameObject
and the object would be moved into the DontDestroyOnLoad scene
without that I'm not really sure how you are managing to have references to destroyed objects sticking around
or maybe you're using a static event?
You really need to just show your code and show the full error message
sure, i didnt because its long. i will return with a pastebin
ERROR OUT:
MissingReferenceException: The object of type 'BeamRifle' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
MyGame.BeamRifle.Aim () (at Assets/MyGame/Scripts/BeamRifle.cs:39)
PlayerInputs.Update () (at Assets/MyGame/Scripts/PlayerInputs.cs:24)
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
in the script i commented where the error is originating from
private void Aim() {
isAiming = !isAiming;
if (isAiming) {
transform.SetLocalPositionAndRotation(Vector3.zero, Quaternion.identity);
} else {
transform.SetLocalPositionAndRotation(initialPos, initialRot)// line39;
}
}```
line 39
you'd have to show the PlayerInputs script
using System;
using UnityEngine;
public class PlayerInputs : MonoBehaviour {
public static Action shootInput;
public static Action aimInput;
public static Action reloadInput;
[SerializeField] private KeyCode reloadKey = KeyCode.R;
// Update is called once per frame
void Update() {
if (Input.GetMouseButton(0)) {
shootInput?.Invoke();
}
if (Input.GetMouseButtonDown(1)) {
aimInput?.Invoke();
}
if (Input.GetMouseButtonUp(1)) {
aimInput?.Invoke();
}
if (Input.GetKeyDown(reloadKey)) {
reloadInput?.Invoke();
}
}
}```
I see the problem
Yeah It's like I mentioned before
you are using a static event
but you are forgetting to unsubscribe from the event
you need to do this:
void OnDestroy() {
PlayerInputs.shootInput -= Shoot;
PlayerInputs.reloadInput -= StartReload;
PlayerInputs.aimInput -= Aim;
}```
ohh okay
hello, im having more of a conceptual problem that I could use some advise on... I am making an inventory and I have gotten most of the visual items done. If you walk over an item it will add it to the inventory and you will be able to see it etc. My problem is Moreso with how do I store the item's data?
in a class / struct
that's up to you. You need to decide what data needs to be stored
then just... make a type that captures that data and store it in your inventory
I made a flow chart to sort of show the system that I currently have since compiling all of the scripts and pasting them here would probably be hard to track
this disabled the gun. is there something else i need to do
I would guess you copied it incorrectly
it will not disable anything
this will only unsubscribe when the gun is destroyed
seems you got something going , go with it
private void Start() { // event subscriptions
initialPos = transform.localPosition;
initialRot = transform.localRotation;
gunData.currentAmmo = gunData.magSize;
PlayerInputs.shootInput += Shoot;
PlayerInputs.reloadInput += StartReload;
PlayerInputs.aimInput += Aim;
}
void OnDestroy() {
PlayerInputs.shootInput -= Shoot;
PlayerInputs.reloadInput -= StartReload;
PlayerInputs.aimInput -= Aim;
}```
yeah that looks fine. What do you mean by "disabled the gun" then?
when i added that, it seemed to disable the event subscriptions. making the gun do nothing
like it's not working in the first place now? Or perhaps it's not working after the scene reload?
well the problem that I am running into is that since there are many different types all with different fields, making a generic SO to store them seems not right (struggling to find a word lol)
i commented that code out, and things went back to normal
this code won't run until the gun object is destroyed, so that will only happen if you're destroying the gun
destroying.... hm.. im not doing anything of the sort. but that script is a part of a scene thats loaded by the main menu
does that affect anything
is Item a regular class or inherits from SO ?
no
Start using Debug.Log and see what's going on
Question: Why does this code slow down the turrets rotation more and more as it approaches the target rotation? I though this was only a problem with Lerp
which code is running when, etc.
ItemSO is an actual SO, but Item (the parent class for all items) is just a class
But I am not using Lerp
Ohh thought you said you had problem with lerp
I can see code well, can you send codeblock
But yes the problem is the same one as the lerp it approaches, doesnt reach the target
lmfao well, im not sure what changed, maybe i just forgot to press CTRL S in vs. it works now. thanks
What is a codeblock
like this ```
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
hmmm maybe you can try Quaternion.Slerp
I think linear interpolation does that slowing down / speed up effect on rotation. Don't quote me on this tho..someone might have a better answer
Hi all, I'm trying to create a sort of hover-ship controller, I have most of it working fine but having issues with surface alignment.
The alignment is currently done via Quaternion.FromToRotation() and Quaternion.Lerp(), which aligns the ship to the surface
However, it also results in the player not being able to turn the ship, because its Y-axis is being modified every frame to match the surface's Y-rotation
How could I go about rotating the ship so it's Y-axis remains unmodified / still controllable by the player?
Would I be able to make a copy of the class and store it in the SO before it gets deleted (and or transfer the instance)?
Yeah it does reach the target now but is still slows down, I am trying to just keep it the turret at the same speed
why not use normals
I will post what I am doing, already using the surface normal from a raycast :)
private void AlignToSurface()
{
if (Physics.Raycast(transform.position, Vector3.down, out hit, 30f, settings.WorldMask))
{
transform.localRotation = Quaternion.Lerp(transform.localRotation, Quaternion.FromToRotation(Vector3.up, hit.normal), settings.AlignSpeed);
}
}
if you switch it to SLerp make sure you do the interpolation correctly (use a Coroutine)
the one you did for rotwatetowards doesn't work well
drag?
hmm I think create a vector3 as target and add the ships rotation as the Y instead
I'm trying to remember how I did my hoverboard year ago
or would it be better to make multiple SO's inheriting from the base one?
wdym storing into a SO?
typically is the other way around
item data, IE(damage, animations, etc.)
atm when something is added to the inventory the game object is destroyed, thus the class instance that stores all of that information is as well
I need to store that data so it can be reinstantiated into the game when equiped
do the stats change ?
I would like to give them the ability to, for scalability
I would use regular class for that , If you change 1 SO all the gameobjects that use that SO will change with those stats
you pretty much already have the object template
so if both player and enemy use same Sword SO , if you increase stats on your player SO sword it will change enemy sword
best to make a copy of base stats of a sword into a POCO then mutate that
sorry could you elaborate on that, im not familiar with POCO
Plain Old C# Object
As in, doesn't inherit from MonoBehaviour or ScriptableObject or anything at all
A container for data with some methods on it
You can store the POCO that is already on the object to have a blueprint for later what to recreate
I've implemented the Vector3, however the ship now no longer aligns to the surface, although the Y is still modified / aligned with the surface.
Vector3 target = Vector3.up - hit.normal;
target.y = transform.localRotation.y;
transform.localRotation = Quaternion.Lerp(transform.localRotation, Quaternion.Euler(target), settings.AlignSpeed);
I'm assuming that this has to do with my target calculation not being the equivalent of whatever FromToRotation() does
how do you go about storing a class?
Guys there is something I dont understand. If we can not inherit more than one base class. Why not just use interfaces? What is the point of inheritance then?
As I understand interfaces act as 'contracts', wherein you have to explicitly implement all the members of the interface for each class, whereas with inheritance you can inherit base members (e.g. default methods)
you cannot inherit data from interfaces.
nor behavior
it's merely a contract that guarantees you have certain methods
I'm kinda lost on this one tbh, I have rigidbody with Dynamic active. Basically each raycast on the corner of my hoverboard keeps the board level with ground
basically a template
Hmm all right. Thanks
@brittle sandal :\
did it completely different :\
Thought i leveled the board rotation but I just let dynamic rigidbody take care of it basically
hmm
so you are using a physics-based approach wherein you apply forces depending on the surface
mine is basically non-physics related and the surface height correction is done via lerping
iirc when i did the first option it felt to stiff for what I was after since mine needs a springy feel to it with suspensions
yea
you only need X rotation or both X and Z?
I want to align the x and z so that the ship and camera rotates to face the surface (done)
but without affecting the y, so I can still turn the ship
I will try post a video of what's happening
EDIT: Found a solution thanks to Sebastian Lague's planetary FPS controller video, I simply needed to multiply my Quaternion.FromToRotation() result by my ship's transform.rotation.
I also changed it from modifying the ship's localRotation to it's standard rotation.
Hey everyone, I'm making a top-down game and I'm using Blend Trees to set the player's movement animations based on x & z input vectors.
However, the player rotates to look in the mouseWorldPosition, and so the values passed to the animator blend tree should be relative to the position the player is looking (i.e. if the player is pressing right and looking to the right, it should play the forward animation). Does anyone have any idea on how I could solve this problem?
you can rotate your player towards your player velocity vector
The player rotates to where the mouse is, I can't rotate it to the vector direction.
well what u want exactly
Been long since I did that, but out of my head:
You multiply the quaternion you are looking at by the input vector3 you create from your x & z input.
That should give you a vector that you can use in your blend tree.
Do note that it needs to be Quaternion * Vector3, and not the other way around, that's not supported.
Also, quaternion math is not really #💻┃code-beginner anymore 
anyone know how to fix this line of code, its saying that the object reference is not said to an instance of an object. playerPanels[0] has a TextMeshProUGUI component, and im trying to edit the text of ClueText
try checking for angle between ur input for example (0,1,0) and ur current rotation, so if its less then something, ur facing towards it and when u press w while under some rotation angle, then u move forward with animation, for example
I have an issue with reference frames again. I have a dynamic rigidbody parented to a kinematic rigidbody. Kinematic rigidbody moves using MovePosition, but dynamic rigidbody does NOT move with it.If I move the kinematic rigidbody in editor, dynamic rigidbody moves along with it.
and I made a test dynamic rigidbody with no other scripts. Just collider, rigidbody, and spriterenderer to see. Still same issue.
either playerPanels is null or playerPanels[0] is null
the screenshot on the right doesn't really tell us anything
this is playerPanels, the Player0 is the same Player0 as in the right screenshot
Oh my bad! I'll try it out and post the question on #archived-code-advanced if it doesn't work out! Thanks for all the answers
wwhich line is actually throwing the exception?
107 where i try to use clueTMP
I would try #archived-code-general first 😉
oh then Player0 just doesn't have that component on it
TextMeshProUGUI
Anyhow, did my solution not work?
You can even see in your screenshot - the text is probably on one of these child objects
ClueText is seperate to Name Button if thats what you're meaning
I mean you are trying to get a text component from Player0
which doesn't have a text component
how would i access it then
The right way to do this is that Player0 should have a script on it
getComponentInChildren?
like PlayerPanel or something
this way is horrible/fragile
put a script on Player0
call it PlayerPanel
give it a function called SetName() or whatever it is you're trying to do
let PlayerPanel internally handle its references to text elements etc
and this PlayerPanels list should be List<PlayerPanel>
so you don't need to deal with GetComponent
okay ill try that thanks
I think I figured out my reference frame issue kind of? If I change transform.position and NOT rigidbody.MovePosition, the parenting works perfectly
but it's my understanding that I really should not do that
sort of! It works exactly as it should when the player is looking up or down, but get inverted if the player is looking to the right or left.
Strange 
Are you working in 2D or 3D?
3D, i could post some ss if that'd help
Yeah, and can you post the !code snippit too
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
I just got it to work!! Although i'm not entirely sure how, lol.
Vector3 inputDirection = new Vector3(-inputVector.x, 0, inputVector.y);
Vector3 animationDirection = transform.rotation * inputDirection;
playerAnimator.SetFloat("InputX", -animationDirection.x);
playerAnimator.SetFloat("InputZ", animationDirection.z);
What corrected the strange behaviour I described was inverting inputVector.x and also animationDirection.x
Not exactly sure where I messed up so that I needed to inverse these values, will need to dig into it later...
That's strange indeed.
My guess is that you have your InputX on 1 to be Left, instead of Right.
Anyhow, glad it works, but it shouldn't need the double negative. Good luck 
ChessPiece CreatePiece(int file, int rank, char type)
{
ChessPiece piece = new()
{
//stuff here
};
Instantiate(piece, new(file, rank), Quaternion.identity);
return piece;
}
im getting a message in the console saying "You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent()." what does this mean i dont rly understand
Yeah, maybe I did that somewhere... Thanks a lot for the help! :)
You cannot create a MonoBehaviour with new
They do not exist unless they're on a game object
Well, constructors and MonoBehaviours don't work well together.
You just need the Instantiate with a piece. You could just add a public Transform yourPiece and add your piece there. That should fix it.
so you create them by adding the component to a game object
Hey there I’m coding for a game for a school project rn, I’m able to make something in a few days but then realised I might need to account for ECB documentation.
Can anyone give me a brief idea of how entity control boundary works in video games?
Never heard of the concept.
The entity-control-boundary (ECB), or entity-boundary-control (EBC), or boundary-control-entity (BCE) is an architectural pattern used in use-case driven object-oriented programming that structures the classes composing high-level object-oriented source code according to their responsibilities in the use-case realization.
this sounds like what you do when you don't want to actually do any programming
:p
HAHHAHAH welcome to my Uni life 🫠
It was so much easier to understand it when it was just websites
i have several books on the shelf that i never actually read
Oooo online courses?
Self taught, I respect that
nah, this was at college. I did self-teach most of gamedev-related stuff though
Ahhhh same here
I guess you need to figure out how to map actors, entities, boundaries, and controls to concepts you'd find in a Unity game.
Yeah I also don’t really need textbooks too, I just use notes and official documentation
Oh from I heard ECB is very similar to MVC
Well I mean I guess it’s a start, maybe I can start plotting some use case diagrams down. Thanks for the tip
Damn I just hope that my prototype game isn’t too hard to refactor though
It’s a simple game but I still worry hahahah
https://www.youtube.com/watch?v=-DMkTRdOoro how did bro do this thing looking to fire up another project to make some destructible tanks but tracks scare me 
After the build, triggers on android do not work. objects don't have Rigidbody
can someone help, this is a bit complicated, so for GetAmount and Remove i have to exclude the current cell, how do i do it?
this bit of code is on the inventory cell
https://hastebin.skyra.pw/usifufusut.pgsql
this is the inventory
https://hastebin.skyra.pw/eqocotojel.pgsql
i cant stack items which are in cells that are behind the current one
thats how the slots go
when i click on this, its wont quick stack
but here it will
because there is the same item BEFORE it
can try get component fail even if it gets a component? I have a weird scenario where it keeps bypassing the first check.
I even tried a if (!other.TryGetComponent(out HealthComponent iHealth))) but its bypassing the false check (even when returned?)
Tried putting the return in the InterfaceDamage -> Take Damage as well, so that it would check at the moment of applying damage on the living object, but that also failed.
The failure point seems to be on try get, but the component exists on all objects that can take damage...
I even saw some weirdness where it "failed" then "succeeded", but somehow called the !other.TryGet before the other.TryGet though the fail check is AFTER the try get true. It's not making any sense. order of operations seems to be out of whack
private void OnTriggerEnter(Collider other)
{
// GOD MODE CHECK
if (other.TryGetComponent(out HealthComponent iHealth))
{
if (iHealth.isGodMode)
{
Debug.Log($"Object [{other.gameObject.name}]: isGodMode, ignored Projectile!");
// IF HITS PLAYER, EVADE
if (other.CompareTag("Player"))
{
PlayerObject.Instance.onEvade.Invoke();
}
return;
}
}
if (other.TryGetComponent(out IDamageable iDamage))
{
Debug.Log("Dealing Damage");
iDamage.InterfaceDamage(1);
}
}
What do you mean by "fail"? Is it giving you an error somewhere?
i put an else/else if and tried the !other.TryGet and it returned the debug "Failed to get component" (custom debug)
but it's failing to get it at random intervals. It'll work for alot of hits, then out of nowhere it starts skipping the try get healthComponent and goes right to iDamage.
No errors, just returning "false" on tryget when it should always be "True"
You should show that code
ok, what would be the correct "inverse" of the other.Tryget? would "Else" work or do i need else if !other?
tryget just returns a boolean
true if the component exists
false if not
So, else
so else { return }? would that protect the damage from running if component not found? wouldn't make sense to deal damage to something that doesn't have a damage receiver
That would rerurn from the method if you didn't get the component
i think that would make sense logically
if the health class doesn't exist, dont bother running the damage check
if it does, try and check for god mode
think i would make god mode or not up to the thing that is taking the damage
from the looks of it, it was failing (doing nothing) then skipping to deal damage (which applies no matter what)
the thing doing the damage just looks for the interface to do damage and calls it
yea, its grabbing that off the health component, but the TakeDamage also has a check inside
public void InterfaceDamage(int amount)
{
TakeDamage(amount);
}
snippet of takeDamage
public void TakeDamage(int damage, bool isPureDamage = false)
{
Debug.Log("Dealt Damage");
if (health.isGodMode)
{
Debug.Log("Damage Negated: GodMode Active");
return;
}
damage = Mathf.Abs(damage);
take damage is within the living object class, so it can see the health class, so it shouldn't fail ever
this feels like more indirection then needed
why would the health component not just implement the interface directly
hmm good point
so its more like health.TakeDamage. trying to see if there's scenarios where thats unecessary
do your items have some sort of ids? or just show InventoryCell class
i mean they have id's
but i dont use them
like i just compare item data
the SO
like here for example
ah figured out why, so i had two components registering the ontrigger enter. It was hitting some other gameObject on the player first, then the player. makes sense, easy fix
in the Add method
Hey i need some help i wanna change the alpha of a panel but it doesnt work rn, heres the code part: https://paste.ofcode.org/UdvaKELNePjz5LnXTefJjr
this was just my thoughts when i was in college```
make a list of cells in the inventory
and in the Add method in inventory specify which list you are adding to
on the players inventory have cells for the inventory slots which you can add items to, so all inventory slots + hotbar slots
and also equipment slots
when quick stacking items specify check all of the cells list, and if the cell type matches the one on the item, quick stack
and on a furnace have like the fuel slots cells, input slots cells, and output slots cells
think about the remove if you should pass the cells array in, and same for GetAmount```
I know whats the issue but I cant figure out a good solution to fit in ur code lmao
like make this
and in add, remove and getamount
add this parameter
if its not null, make it add the items to the specific cells
like a specific cell group
and in my Quick Stacking i could make a new cell group with every cell in the inventory excluding the one
to double check you want double clicked item to stack to the most top left slot with same item type? Like opposite of what currently happens?
like
hold on
when i double click the blue
here
i want red to stack to blue
but at the moment its not happening
it only works when i double click the red item
then the blue gets correctly stacked to red
its because GetAmount and Remove is also checking the blue item
and here i have to somehow not check the cell clicked
nah too much thinking what Ive got to say is make method in inventory manager QuickStack(Item item, int amount) and make double clicked item send itself to that method then start looping through inventory and if you find same type item add to it you can skip double clicked item just comparing class instances
i dont understand
im thinking the best way would be this
in each method like Add Remove and GetAmount have a parameter passing through
and if its not set then do all cells
and if its set do the specific cells
you definitely want QuickStack method specifically created for this action alone dont confuse urself
u sure?
also you kinda control inventory from item tiself https://hastebin.skyra.pw/usifufusut.pgsql here
items shouldnt edit inventory thats what inventory manager is for anyways maybe someone else will take over cause I cant really say something very specific to fix here 
HI, i have these two codes and when bullet hits the bear i want it to trigger the ragdoll, but in game the bullet passes right on through and it doesnt ragdoll
If it passes through sounds like you don't have a collider or it's a trigger collider
hmm i dont think its got a colider, is there a way to make the model the hitbox?
Also it seems like OnCollisionEnter is on the wrong script? This looks like the script that fires the bullets
You need it to go on a script on the bullet itself
Sure you can use a mesh collider but it's usually fine and more performant just to use a Sphere or Capsule or Box
i would but i intend to make it accurate for the hitboxes
For some reason I'm getting a big frame drop when using an event for enabling UI text when the game ends. Anyone knows why? If I disable the event specifically for activating the text there's no lag
even them, shouldn't my ragdoll script for bear use the ragdoll hitboxes it made?
I'm talking about a collider for the bullet
it bounces of the ground and cubes
Show the bears collider
ye it has a box collider
run profiler and look there what happens at the spike but I guess its redraw canvases thing
weird
i did the ragdoll last night and added an idol animation
but now its not showing the coliders and joints in the parts list for the bear like it did yesterday
but it still does the idol animation so it should be there?
I wanted to see the collider(s) not whatever this is
Animations aren't related to colliders
id show you but they dont seem to be there, but i cant see anything, cant see the coliders or joints but saw them there yesterday after i ragdolled it??? im confused
If you don't have colliders the bullets will have nothing to collide with
You're problem just looking in the wrong place? Why not search the hierarchy
t: Collider
I used something else to enable the text and it still framedrops so the cause does seem to be the text. Is 'SetActive(true)' on UI text very performance heavy or something?
bear didnt come up so it doesnt have any
weird
I used SetActive(false) in the start void function of the UI text to disable the text when the game begins and that also causes a major framedrop
look up what is profiler u need to work with that to see wtf is going on
tho yeah sounds weird idk
i re ragdolled it and now it has colliders and joints, idk why it didnt save that was weird but now they are here
Halo, I'm back with more inventory questions... Since last I have taken a step back and thought about my current system, and think that it would be a good Idea to get a fresh start. (not that I'm totally against my old system, I just feel like starting fresh will open some new avenues that were not there before).
Bascially,
I want to make a player inventory, that inventory will contain all types of items in (currently) 4 categories, weapons, spells, armor and generic. For UI purpouses I still think it would be good to keep these types in separate containers...
ATM I am thinking of switching to using dictionaries instead of Lists (for the main inventories), and arrays for the equipment slots.
I want to be able to have the potential to have multiple of the "same item" but with different stats, especially for weapons and armor.
I also want to be able to destroy the gameObject on pickup of items, this means that any components of said items will be destroyed...
I know I've asked this before but I think I need some further expansion, how should, or in what ways can I save item data (for various types of items) so I can later initialize the item back into the scene from the inventory?
Ive seen a lot of good tutorials out there, but none really answer that last question, or rather they all use a system which is not scalable whatsoever and disallows for things like weapon leveling / armor modifications... any thoughts?
@wintry quarry the bullet hits and bounces off the bear but now the animation doesnt play and the ragdoll doesnt trigger
Well... #💻┃code-beginner message
ATM I am thinking of switching to using dictionaries instead of Lists (for the main inventories), and arrays for the equipment slots.
That's fine.
I want to be able to have the potential to have multiple of the "same item" but with different stats, especially for weapons and armor.
Doable, but the more complex you make an item, the more you have to break down your serialization.
I also want to be able to destroy the gameObject on pickup of items, this means that any components of said items will be destroyed...
That's as easy as making a temporary wrapper which you can add and remove without affecting the actual item reference.
I know I've asked this before but I think I need some further expansion, how should, or in what ways can I save item data (for various types of items) so I can later initialize the item back into the scene from the inventory?
Keep data very specific early on where you can simply apply IDs for serialization and deserialization if that's what you're asking.
thank you so much for the answers!
would you mind expanding a bit on #3, do you mean to have a script component that just runs the constructor of another detached script?
And the result? Make sure the code is running with Debug.Log and also watch the console for any errors
Well, it depends on how you're doing your items. If they derive from a mono, then you can pretty much keep all the functionality on the item itself. But, if you are using plain data objects then you need some wrapper that inherits the mono for a scene presence.
Also note this assumes the same object with the collider has the bear script, and not a parent object for example
I designed an inventory system where the inventory items are distinct from the actual in-world items
They both reference an "ItemSpec" object that actually contains the item's stats
Not using textmeshpro and using a different canvas seems to have fixed the issue
I don't think the overhead for them all being mono's is a bad thing, but I've not really took the effort to compare it all, but preferably you do want your item data disconnected from the scene when it's not being used.
nothing, the caode is fine but it doesnt do anything so i think im just missing something, and just have a code that doesnt do anything
sorry what does this mean? i need to find a way to link both scripts?
yeah the inventory system I had, the data was connected to the actual object but not the inventory, so the only thing that was really being stored was its name and icon.
I guess making that relationship go both ways using a generic class pointing to a "data" class would make things a bit easier
and allow for some for varried functionality across item types
No, just that the bear script must be on the same object as the object you run trygetcomponent on. It has the be the same object as c.collider. You can't, for example, have it on a parent or child object as is
so i put the bear script on the bullet script?
Im so sorry I dont want to keep pressing too much, but could you just break down a way to preserve a monobehavior off of an item that has been destroyed?
No, I don't think so. Is the bullet script attached to the same object as BulletRagdoll? You want the bear script on the object that the one with BulletRagdoll HITS
arent u supposed to save what u need as poco class and assemble ur monobehaviour from that class
or, would it just be advisable to instead of having a bunch of inherited classes for item types, just having a bunch of inherited SO's
no bullet attache to the gun, the radoll is a seperate thing its an npc
Any idea what's causing this issue? I can't work it out.
[SerializeField]
private int _itemID;
public int ItemID { get { return _itemID; } set { _itemID = value; } }
Whatever BulletRagdoll is attached to needs to be a different object than what Bear is attached to. And bear script must be on the same object as the collider
Edit: wait... bullet is attached to the gun?
so, the script in the chat is in ItemReference
i should have clarified
You don't necessarily need to preserve any monos is the idea. If you are to create an inventory of data objects and want to drop them, you'd temporarily place them into a wrapper that derives from mono and add some visual display to the GO. Similarly if you want to display a weapon on your character.
which one? you posted two pieces of code
or are they both in the ItemReference definition?
the chat one, the image is from something different
it is
well, you need an instance of ItemReference to get the ItemID from
you can't just ask the ItemReference type itself for an item ID. which item are you getting the ID of?
ill try that, just need to put bear script on the bullet, do i keep the bear script on the bear too?
public class ItemPickup : MonoBehaviour
{
private void OnTriggerEnter2D(Collider2D col)
{
ItemReference item = col.GetComponent<ItemReference>();
if (item != null)
{
ItemData itemData = InventoryManager.instance.GetItemData(ItemReference.ItemID);
string debug = (itemData != null) ? "Player has picked up " + itemData.itemName + "." : "ItemDetails is null!";
Debug.Log("msg");
}
}
}
okay, then just do item.ItemID
Why would bear script be on the bullet? Why would it NOT be on the bear?
you can't ask ItemReference for an ID because that's not a specific item
that's just...the concept of an item
that's why you got the error. ItemID is non-static, so you can only access it from an instance of ItemReference
sorry Im still super new to all of this, are you basically saying that instead of turning the item into data, you turn the data stored in a SO, or other to create a new GO. (instead of storing a refrence to data in the GO store a refrence to its prefab in the data?)
would you happen to have a doc explaining how to do that?
imo u gotta walk through simple json tutorial/example online to get the gist
bullet is a solo object, there is a script on the gun that fires it from the gun barrel. the bear is another seperate object
Yeah... so don't put bear on the bullet
How do I make this match rotation of parent instead of world Axis?
The data is just a plain data object which you have a specific instance of as opposed to an SO where you have only one instance of. A GO is an object that derives from monobehavior and isn't required when you want to store something as data without having a scene presence.
then whats my problem, i think i confused myself
You are confusing me too lol. I'll break it down though. No worries
-
Bear object has a bear script
-
Bullet object has a bullet script and bulletragdoll script
-
Gun has whatever script shoots the bullet
-
Bullet hits bear object. Collider of bear AND bear script must be on same object.
Done
ohh i see
transform.rotation would give you the rotation of transform
Then you gotta get the bear script through their parent. c.transform.parent.TryGet or whatever the syntax for that would be
Is it ONE level up?
Alternatively, you could have scripts on the sub limbs that respond to ragdoll as well. And the bulletragdoll script would check for those (or an interface for them)
would you happen to have an example and/or article? Sorry, I understand what you are saying from a "coding" standpoint, just not a "coding in unity" one. (if that makes any sense)
I just need to see it
https://www.youtube.com/watch?v=aSNj2nvSyD4 I watched this like month ago on how to work with json not cherry picked one just what I watched since I know the dude from udemy so of course chinese spies showed this as top result 10min clip and u can save whatever
the main body bear script has a line of code to find the sublimb coliders from ragdoll tho
But the bulletragdoll can't get to the bear script as you've written it. Because the colliders are only on the limbs, right?
It will only act on the objects with colliders
ohhhh
I'm just explaining runtime concepts, but if you're looking for deserialization methods to reload the data then that's something else
so how do i do that?
I'm adding a 3D object to my Unity 2D project with URP. I want to show this dice on top of the UI canvas elements. Would the best way be to just add a new camera for the 3D object separately?
I explained here
#💻┃code-beginner message
Which part can I help with more?
Which route do you wanna take?
are you basically saying that instead of turning the item into data, you turn the data stored in a SO, or other to create a new GO
No, you start from an SO and create a plain data object from that specific SO. But, when it's created, there's no point of it being a monobehavior unless it's on the scene is my point. When you drop an item in the scene, you will take that plain data object, create a new GO with a wrapper script, and stick that plain data object inside of it. When you pick up that item, you remove it from the GO and then destroy the GO while placing the item reference (which is still a plain data object) back into your inventory.
ok, and to make sure we are on the same page, by plain data object you mean a non derived script/class?
Right just a c# script
they don't need to derive from a mono to be used in unity
only if you want it to have some scene presentation
yooo hi is this like the correct channel to ask questions i just joined cause ive been stuck on this for like the past 4 hours and im going insane
nah u go to #archived-art-asset-showcase for that

what sorted collection would you use to store a history of player scores in descending order? does C# have anything like that? ive tried googling, but theres only SortedList which is more like a sorted dictionary requiring keys, and SortedSet which would not work
You could just use a list and sort it when you add something
Hey everyone, I've been having this issue with jittering in my 2d game. As you can see in the video whenever I move the player vertically and have the mouse cursor horizontally the cannon part of the player starts to jitter. Same happens if I'm moving horizontally and holding the mouse cursor vertically (it gets worse the closer the mouse cursor is to the pivot point of the player)
Here is the code for the player movement and camera tracking:
https://pastebin.com/SVkfmPhf
So far I have tried putting the camera tracking in update and fixedupdate but it doesn't make it better.
The player's rigidbody is also set to "Interpolate".
Would appreciate any help
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Hey, out of curiosity, why can't you use a function that takes a bool parameter in animation events?
Are you moving in the video? Either way, the input should be set in your update loop while rigidbody stuff is done in fixedupdate. As for the wonkyness for centering your mouse, you'll need to add a deadzone to ignore that input in your logic.
I guess it was just decided that there's already enough options
can someone have a look at this and try and help me, i've made comments of how i would want it to work
The one i need help with
https://hastebin.skyra.pw/esohuluray.csharp
The inventory script which handles Add function
https://hastebin.skyra.pw/gevutojaci.pgsql
Looks pretty good, what's the problem?
can anyone tell me what this means?
you need to configure your !IDE so that it shows you errors
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
you know how in minecraft it works like this
You seem to have it working here, no? You just need to delete the original item after stacking.
what does that mean?
maybe take a look at the bot message
i would also have this in the inventory
wait it broke completly
i wanted to send a video
After stacking, check the original item's value and if it's 0 then remove it
i dont understand what it means
how do i download it
you need to configure your ide so that it will show you your errors. click the relevant link in the bot message and follow the instructions
you see when i stacked it, it gets added to the hotbar slots again
which i dont want
i want it to stay in the same slot
Why are you readding it to the slot then?
this is what causes it
what do you mean
is this what its supposed to look like?
but i have to add the rest because i Remove the item from the slot
that's one part of it, yes. please read all of the instructions and actually follow them
Yea
You left click on item, check if your inventory has already a similar item, otherwise find first available slot. If you find a similar item, deduct from your current item onto the item already there. If the original item is now of value 0, then you just delete it.
i need stacking from hotbar cells to the inventory cells
Exactly
and from inventory cells to hotbar cells
So that's the 2nd problem
Ok, so that was hotbar to inventory
^
Usually you want to scan it first for an item already available, at least that's how most games do it. If not found, then you just put it into the most first available slot (which you can minimize scanning by marking it on the first scan)
You shouldnt remove the item from the slot unless it fully stacks* into another cell
i followed all the steps but there's still the error
yeah
thats what i want
You want to fix the error or what
yeah those steps don't fix the error. they just help make them visible in your ide so that you can fix the obvious errors
but i dont know how to check if it fully stacks into the the vice versa cells
ye i want to fix it
Could u send the jump function
Like the whole script
Bc there's a flipped or a curly brackets placed in the wrong place
XD
I'm trying to figure out in your code where you're readding the item
did you already see their code that they posted above? there's a lot wrong with it. they need to configure their ide before attempting to fix any of it
whole scripts
if it helps
Here, you seem to stack it fine, so why don't you check after if the original item is 0 or not, and if so leave it alone, otherwise remove it, or is there something else im not seeing here.
You should only remove it if it's 0
unless you're trying to stack it and place the remainder into the inventory as well
that's another step then
im trying achieve this
like stack it, and then leave the rest alone