#💻┃code-beginner

1 messages · Page 14 of 1

wary sable
#

and heres what an item in game might look like:

shell sorrel
#

type switch or is statement

#

if (item is Armor) { or if you need to access stuff on Armor
if (item is Armor armor) {

cosmic dagger
#

what Passerby said, but why are you adding them to separate lists?

shell sorrel
#

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

wary sable
# cosmic dagger what Passerby said, but why are you adding them to separate lists?

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

shell sorrel
#

so might also just model this all in data not in inheritance

wary sable
#

and some are literally just there to define a type, like with armor.

shell sorrel
#

either way the type checking via if or switch like i showed will work

wary sable
#

yeah I switched the method to is already, but I am Definity considering switch especially if we end up adding more

shell sorrel
#

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

wary sable
#

gotcha

#

id assume you have to provide an argument for the switch beyond 'Type'?

hearty ivy
#

anyone know how to fix lines in tiles glitch

shell sorrel
hearty ivy
#

nvm

#

my atlas was being dumb

twilit trail
#

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```
teal viper
#

Check your volume components for any diffusion profile lists that might be culprits.

twilit trail
#

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

fickle plume
#

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.

faint osprey
#

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?

cosmic dagger
#

need to see code . . .

faint osprey
#
            {
                Instantiate(genTube, cylinder.transform.position, cylinder.transform.rotation, instanHolder.transform);
            }```
#

thats in the update loop

cosmic dagger
#

is this the only code?

faint osprey
#

no the only code that mention instantiate

cosmic dagger
#

place a log before Instantiate and see if it appears twice from the console . . .

faint osprey
#

oki

fickle plume
faint osprey
#

cause as soon as thats activated it will call it every frame

true surge
#

I need some assistance for a game jam due tomorrow

cosmic dagger
#

!code

eternal falconBOT
#
Posting 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.

cosmic dagger
#

use a paste or bin site to share your code . . .

true surge
#

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

wary sable
#

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?

true surge
cosmic dagger
#

where does the bullet shoot out from?

#

the spawn position used for the bullet should be at the tip of the cannon . . .

true surge
true surge
#

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

true surge
distant horizon
#

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?

summer stump
#

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

distant horizon
#

idk where the dependancies tab is but i do have the engineering package, if thats what this is

#

wait really?

#

oh

summer stump
#

On the right

distant horizon
#

i thought vscode and vs editor were two different things

#

oh

summer stump
distant horizon
summer stump
#

Remove the engineering package to unlock those packages

distant horizon
#

okie

silent valley
#

!code

eternal falconBOT
#
Posting 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.

silent valley
#

Hi

#

How can I have it so I can edit my update text in the inspector itself?

distant horizon
#

i still dont see the dropdown directory (and im only screenshoting cuz its a vscode thing)

#

(in the middle of typing TransformDirection)

distant horizon
#

alrighty

#

couldve sworn i enabled the vscode option

summer stump
#

public string textIWant;

silent valley
#

like this. I did think that. Just didn't know how to implement it into my script

summer stump
#

Do you mean like that?

#

Just setting the text?

silent valley
#

omg. I think I have having a stupid moment. I should of known that. Thank you.

summer stump
silent valley
#

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

faint osprey
#

if i disable a camera

#

will it automatically display the other one in scene

rancid scroll
faint osprey
#

ok great thank u

faint osprey
#

when i set it to active = false;

#

i just get no display rendering

lofty vault
#

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?

keen dew
#

Color values are between 0 and 1

lofty vault
#

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!

keen dew
#

If you want to use 0-255 there's Color32

compact ibex
#

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

daring sinew
#

how do i reference script's float value from another script?

timber tide
lavish fractal
#

does anyone know what is wrong with line 70

fringe pollen
lavish fractal
fringe pollen
spark ember
#

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:

fossil drum
spark ember
#

its at 5, do i increase it?

#

billboard start

fossil drum
spark ember
#

thanks

#

ill try find it

solemn dagger
#

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

fossil drum
solemn dagger
#

ohk

#

ty

solemn dagger
fossil drum
#

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

fossil drum
spark ember
#

is there a specific style that this has

fossil drum
spark ember
#

ahh yeah

#

sorry

wooden minnow
#

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

cosmic dagger
#

what have you tried or searched?

wooden minnow
#

Same with resetting it's position

wooden minnow
#

I think I have before and just decided to fix other bugs before that

cosmic dagger
wooden minnow
#

I was sure that returned a read-only error

cosmic dagger
#

sure, as in, you tried it or just guessed?

wooden minnow
#

Pretty sure I tried it but as I said it was a while ago and I don't remember

queen adder
#

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?

buoyant knot
#

do you need saving between play sessions (ie application closing)? or just within a play session (ie respawning)?

verbal dome
buoyant knot
#

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

verbal dome
#

Is playerprefs a package now?

buoyant knot
#

i got it off openupm

#

idk if we have a built in playerprefs. I just saw it on openupm and snagged it

verbal dome
#

PlayerPrefs is in the UnityEngine namespace builtin

slender nymph
#

yeah PlayerPrefs is built in. not really suitable for save data though

verbal dome
#

I use it for debug settings, thats pretty much it

buoyant knot
#

from what I understand, PlayerPrefs is best for one off tiny little things

cosmic dagger
#

PlayerPrefs was the original way for saving stuff. it's been there since the beginning . . .

slender nymph
buoyant knot
#

🤷‍♂️

#

that’s what it’s marketted for

#

and it’s ridiculously popular

slender nymph
#

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

buoyant knot
slender nymph
#

this is not unity's player prefs

buoyant knot
#

because “score” is a preference to be saved

verbal dome
#

What is the name of that package

buoyant knot
#

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?

cosmic dagger
#

☝️ oh, you never said the before . . .

rancid scroll
#

ew PlayerPrefs.

buoyant knot
#

i said it was an openupm package

#

which is by definition, not unity built in

verbal dome
buoyant knot
#

i didn’t know playerprefs was a built in unity thing tbh

slender nymph
#

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

rancid scroll
buoyant knot
#

i only save things to JSONs right now

rancid scroll
#

that's all you need

buoyant knot
#

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

rancid scroll
#

You're gonna have a bunch of random strings in your registry for bools?

buoyant knot
#

that’s what it’s marketted for

rancid scroll
#

yuck

slender nymph
#

"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

rancid scroll
#

lmao i just pictured someone walking with shoes made out of tissue boxes

#

ty

buoyant knot
#

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

polar acorn
# buoyant knot and it’s ridiculously popular

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

cosmic dagger
rancid scroll
buoyant knot
#

was KSP saving like a whole level’s of data to playerprefs?

slender nymph
buoyant knot
#

i’m talking about something like maybe 300 bools/ints max for a gigantic AAA project.

rancid scroll
#

that makes more sense. Per key, but still why would they do that (KSP) lmao

rancid scroll
#

good point

#

lol

polar acorn
#

Doing things the right way is harder

buoyant knot
#

there’s nuance that got lost in translation lol

polar acorn
#

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

rancid scroll
#

yeah really wouldn't even take much..

polar acorn
#

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

north kiln
#

That would be wonderful, if they actually worked with console manufacturers to make it a shared API there, 🤤

polar acorn
#

Make that the keystone feature for unity 2024 and I'm sure people would reconsider sitting on their current version

north kiln
#

People who are considering sitting are already missing out on a lot

cosmic dagger
cosmic dagger
#

@languid spire don't you already have smth like this?

languid spire
cosmic dagger
#

aye!

swift crag
#

store allllllllll of the game data in there

rancid scroll
#

cries in MacOs

languid spire
swift crag
languid spire
#

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

twilit pilot
silent valley
#

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?

silent valley
swift crag
#

well, there you go

#

sanitybar is presumably a GameObject variable

languid spire
swift crag
#

you can't put a SanityManager into a GameObject

#

round peg, square hole

silent valley
#

I'm assuming cause it's a UI? it's a slider

swift crag
#

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

twilit pilot
languid spire
languid spire
silent valley
swift crag
#

I don't know what you mean by that.

#

Did something similar work before?

twilit pilot
languid spire
twilit pilot
#

haha, fair

silent valley
# swift crag Did something similar work before?

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?

swift crag
#

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

languid spire
#

@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

silent valley
twilit pilot
languid spire
stoic spear
#

hey, im trying to make a security camera rotate within set limits, but im not sure how to do it really

radiant nimbus
#

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?

stoic spear
#

so theres a v2 with the limits, and a float for the rotation speed

radiant nimbus
rancid scroll
#

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.

radiant nimbus
#

ah okay and if you update unity, will you just be able to open the older projects in another version?

rain grail
#

What do you guys use for a c# script???

cosmic quail
cosmic quail
rain grail
#

like you can use note pad but what third party software should i use

rain grail
eternal falconBOT
#
💡 IDE Configuration

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.

rain grail
#

thanks!

rancid scroll
#

anyway you should alwasy be using Git / Version control anyway before any updates

cosmic quail
rancid scroll
cosmic quail
rancid scroll
#

you're probably also copying the Library folder

cosmic dagger
#

that's old school, for sure . . .

rancid scroll
#

so your backups must be gigabytes

rancid scroll
sand glen
cosmic quail
sand glen
cosmic quail
#

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

rancid scroll
#

how else they will train github pilot 😛

#

they need free code

#

i mean repos

cosmic quail
swift crag
#

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

rancid scroll
rancid scroll
#

github is just a host

#

like bitbucket

#

etc

swift crag
#

i think my point is making itself here.

polar acorn
cosmic dagger
#

guess who? yes you
wait me? couldn't be . . .

polar acorn
#

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

swift crag
#

I use git entirely locally for a number of small projects

polar acorn
swift crag
#

I self-host a server

polar acorn
#

Doesn't have to be online, doesn't have to be code

swift crag
#

i need to redo that webserver. it is uh

#

aging

swift crag
#

i could use something that's not a full GitHub clone

polar acorn
# swift crag what're you using for the server, btw?

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

swift crag
#

Ah right.

#

I've done that occasionally: clone from a local repository

#

it's distributed!

rancid scroll
polar acorn
#

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

swift crag
#

put the hard drive in a lead-lined fridge

unborn veldt
#

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?

swift crag
#

not really. the internal structure of a dictionary is not a neatly packed array

#

maybe the keys are

cosmic dagger
unborn veldt
#

It hasn't, it can be turned into list

#

but it iterates

unborn veldt
wintry quarry
#

can you not just use myDict.Values directly?

unborn veldt
wintry quarry
#

what are you trying to do with it

wintry quarry
swift crag
#

I guess you could reach into the dictionary and steal its Entry[], but that sounds abysmal

#

explain your actual problem

unborn veldt
unborn veldt
#

i'll try..

wintry quarry
swift crag
#

if you can't explain your problem to us, then you probably haven't given it enough thought yet to be implementing a solution

cosmic dagger
unborn veldt
wintry quarry
#

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

unborn veldt
#

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

wintry quarry
#

Yes I was helping you the other day with that issue

unborn veldt
#

I'll try

unborn veldt
#

tysm for some days ago

cosmic dagger
#

dealing with references across threads?

unborn veldt
#

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.

queen adder
#

dude what?

#

updatetext is for a string what would i put a debug.log inside of it

polar acorn
# queen adder dude what?

Put a debug log inside the updatetext function. If it prints then this code is working and the issue is in playerui

unborn veldt
queen adder
unborn veldt
#

can I paste my class in pastebin?

#

so you can better understand the code

#

explaining it it's pretty hard 😛

amber nimbus
#

LookRotation on a child object

buoyant knot
#

if you need to iterate fast and frequently, dictionary isn’t the best data structure

unborn veldt
#

Yeah but changing it would make all the adding/removing navMeshBuildSources extremely hard to code

#

I mean it does its work

queen adder
#

@polar acorn dm please

unborn veldt
#

I can add and remove objects easily, the only problem is when I need to create a list from its values 😦

buoyant knot
#

let’s start from a simpler position

#
  1. how many entries usually go in the data structure (non-empty things)
polar acorn
buoyant knot
#
  1. What features need to be called most
#

ie add, remove, call by key, index, iterate, sort…

queen adder
unborn veldt
#

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)

buoyant knot
#

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

unborn veldt
#

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

buoyant knot
#

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?

unborn veldt
#

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

buoyant knot
#

what is the most reasonably forseeable worst case

#

of how frequently we call

unborn veldt
#

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

buoyant knot
#

first, we probably should never call more than once a frame. your navmesh should probably wait for changes that frame to finish before baking

unborn veldt
#

so in this precise moment worst case scenario is once every 100ms

cosmic dagger
unborn veldt
buoyant knot
#

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

unborn veldt
buoyant knot
#

not that you are using a specific data structure

unborn veldt
# buoyant knot it seems to me like part of the issue is that you have so many things in your di...

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.

late burrow
#

is !false is true and !true is false?

buoyant knot
#

i’m not talking about reducing your count

#

i’m talking about reducing the amount you need to count at once

polar acorn
unborn veldt
#

Maybe reading, idk, 100 objects per frame?

late burrow
#

yes but thought it only works in ifs not that i can for example setactive(!false)

polar acorn
unborn veldt
#

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

buoyant knot
#

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?

unborn veldt
#

Dictionary has everything but the chunks, which are added manually every time I try to build the navmesh

buoyant knot
#

is that why you merge and unmerge? like, what is going on

unborn veldt
#

That's an example of the completely built navmesh

buoyant knot
#

like the dict has everything really loaded, and the list has things loaded out of range which are relevant?

unborn veldt
#

Row 202 is where I add both the terrainSources (the "base" of the navMesh) and the objectSources.keys (currently in an array format).

unborn veldt
#

the dict is updated at runtime by other scritps

unborn veldt
# unborn veldt

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

unborn veldt
# unborn veldt

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

buoyant knot
#

i’m feeling like this merging might be the problem

unborn veldt
#

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

buoyant knot
#

is the final output you need a list of navmesh build sources?

unborn veldt
#

yes

buoyant knot
#

i’m wondering if it would be possible to make the final output an enumerator instead

unborn veldt
#

that doesn't depend on me, the UpdateNavMeshData takes it as an input

buoyant knot
#

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

unborn veldt
#

I think not

#

right?

wintry quarry
#

it's so unfortunate they used List here and not IList or IEnumerable

buoyant knot
#

do we have the source code?

#

like, could we make an extension method to fix that

unborn veldt
#

I think not..

#

can't find any

swift crag
#

so is the problem that it takes too long to create this list?

buoyant knot
#

see if Visual studio can lead you to the source

unborn veldt
buoyant knot
#

and UpdateNavMeshDataAsync (the built in function he needs) takes in a list, and not an IList or IEnumerable

#

understand the problem?

swift crag
#

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)

buoyant knot
#

i’m thinking that there’s gotta be a way to avoid the needless and expensive operation in the first place

swift crag
#

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)

buoyant knot
#

that might be the way. A very shitty but necessary way, if we can’t get the source code

swift crag
#

I've done things like this before.

buoyant knot
#

we probably can

swift crag
#

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

buoyant knot
#

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

swift crag
#

IEnumerator (non-generic version)

#

💥

buoyant knot
#

i have yet to use IEnumerator<T>, but I want to

#

can’t find the best guides for it tho

swift crag
#

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

buoyant knot
#

it sucks that some of unity’s code gets injected from C++ behind a black box

merry spade
#

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?

buoyant knot
#

what do you mean? platform effectors normally get rid of side friction

merry spade
#

yeah but this one doesnt

buoyant knot
#

check the dropdown on the platform effector under “Sides”

#

does it have removing side friction enabled?

merry spade
#

"Use Side Friction" no checkmark
"Use Side Bounce" no checkmark

buoyant knot
#

i forget which way that reads, but i’d first try flipping the checkmark

merry spade
#

didnt work

buoyant knot
#

and on side walls, you’re seeing the player get stuck (0 speed) or slow down (falling slower, but not zero speed)?

merry spade
#

0 speed

buoyant knot
#

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?

merry spade
#

yeah i started unity like yesterday but i will try

queen adder
#

will help you alot

merry spade
#

just examples

queen adder
#

eh still

merry spade
#

no explanations

queen adder
#

i started unity 6 years ago

#

and it did help

merry spade
#

I will look into it after i solved this bug

buoyant knot
#

the documentation is vital to your success

merry spade
#

ok i did this circle

#

now its just stuck

cosmic dagger
#

i'm making documentation right now. i think i went a bit overboard though . . .

merry spade
wet trench
#

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

wintry quarry
#

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;
}```
wet trench
#
    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");
        }
    }```
wintry quarry
unborn veldt
wintry quarry
unborn veldt
#

I can do some checks in the update to be sure it stays sinched and correctly debug if it gets unsynced

wet trench
unborn veldt
unborn veldt
swift crag
#

What if you just update more regions than are strictly necessary?

#

so that you never remove single items

unborn veldt
unborn veldt
wet trench
#

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

wintry quarry
#

You have a DDOL script I guess?

wet trench
#

whats that 😃

wintry quarry
#

dont destroy on load

#

usually used in the context of a singleton

wet trench
#

how do I check?

wintry quarry
#

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

wet trench
#

sure, i didnt because its long. i will return with a pastebin

#

https://pastebin.com/ATp81CXJ

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

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
wintry quarry
wet trench
#
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();
        }

    }
}```
wintry quarry
#

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;
}```
wet trench
#

ohh okay

wary sable
#

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?

wintry quarry
#

then just... make a type that captures that data and store it in your inventory

wary sable
rich adder
#

blinded

#

SO is good too

wet trench
wintry quarry
#

it will not disable anything

#

this will only unsubscribe when the gun is destroyed

rich adder
wet trench
# wintry quarry I would guess you copied it incorrectly
        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;
        }```
wintry quarry
#

yeah that looks fine. What do you mean by "disabled the gun" then?

wet trench
#

when i added that, it seemed to disable the event subscriptions. making the gun do nothing

wintry quarry
#

like it's not working in the first place now? Or perhaps it's not working after the scene reload?

wary sable
wet trench
#

i commented that code out, and things went back to normal

wintry quarry
wet trench
#

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

rich adder
wintry quarry
#

no

wintry quarry
amber nimbus
#

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

wintry quarry
#

which code is running when, etc.

wary sable
amber nimbus
rich adder
#

Ohh thought you said you had problem with lerp

#

I can see code well, can you send codeblock

amber nimbus
#

But yes the problem is the same one as the lerp it approaches, doesnt reach the target

wet trench
amber nimbus
rich adder
polar acorn
eternal falconBOT
#
Posting 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.

rich adder
#

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

brittle sandal
#

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?

wary sable
amber nimbus
brittle sandal
#

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);
        }
    }
rich adder
#

the one you did for rotwatetowards doesn't work well

wary sable
#

drag?

rich adder
#

I'm trying to remember how I did my hoverboard year ago

wary sable
rich adder
#

typically is the other way around

wary sable
#

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

wary sable
rich adder
#

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

wary sable
rich adder
#

is just a class

#

plain ol object

polar acorn
#

As in, doesn't inherit from MonoBehaviour or ScriptableObject or anything at all

#

A container for data with some methods on it

wary sable
#

gotca

#

so before destroying the object just create a new (POCO) class instance...

rich adder
brittle sandal
# rich adder hmm I think create a vector3 as target and add the ships rotation as the Y inste...

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

wary sable
final kestrel
#

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?

brittle sandal
wintry quarry
#

nor behavior

#

it's merely a contract that guarantees you have certain methods

rich adder
wary sable
#

basically a template

final kestrel
#

Hmm all right. Thanks

rich adder
#

@brittle sandal :\

#

did it completely different :\
Thought i leveled the board rotation but I just let dynamic rigidbody take care of it basically

brittle sandal
#

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

rich adder
#

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

brittle sandal
#

yea

rich adder
#

you only need X rotation or both X and Z?

brittle sandal
#

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.

rich adder
#

yeah post video if possible

#

im gonna try some code rq too

honest prawn
#

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?

queen adder
honest prawn
queen adder
#

well what u want exactly

fossil drum
solar arch
#

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

queen adder
buoyant knot
#

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.

wintry quarry
solar arch
honest prawn
wintry quarry
solar arch
#

107 where i try to use clueTMP

wintry quarry
#

TextMeshProUGUI

fossil drum
wintry quarry
solar arch
#

ClueText is seperate to Name Button if thats what you're meaning

wintry quarry
#

which doesn't have a text component

solar arch
#

how would i access it then

wintry quarry
solar arch
#

getComponentInChildren?

wintry quarry
#

like PlayerPanel or something

wintry quarry
#

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

wintry quarry
#

so you don't need to deal with GetComponent

solar arch
#

okay ill try that thanks

buoyant knot
#

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

honest prawn
fossil drum
honest prawn
fossil drum
eternal falconBOT
#
Posting 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.

honest prawn
# fossil drum Yeah, and can you post the !code snippit too

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

fossil drum
oblique torrent
#
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

honest prawn
polar acorn
#

They do not exist unless they're on a game object

fossil drum
polar acorn
#

so you create them by adding the component to a game object

cosmic rapids
#

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?

oblique torrent
#

yeah just did that thanks

#

guys

swift crag
#

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

cosmic rapids
swift crag
#

reminds me of my software engineering courses

#

i only did a few

cosmic rapids
#

It was so much easier to understand it when it was just websites

swift crag
#

i have several books on the shelf that i never actually read

cosmic rapids
#

Self taught, I respect that

swift crag
#

nah, this was at college. I did self-teach most of gamedev-related stuff though

gaunt ice
#

my software engineering doesnt even provide a text book

#

we dont need textbook....

swift crag
#

I guess you need to figure out how to map actors, entities, boundaries, and controls to concepts you'd find in a Unity game.

cosmic rapids
swift crag
#

This reminds me of MVC

#

which I also don't really think about much

cosmic rapids
cosmic rapids
#

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

ashen ferry
solid coral
#

After the build, triggers on android do not work. objects don't have Rigidbody

tender stag
#

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

hidden citrus
#

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

        }

polar acorn
hidden citrus
#

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"

hidden citrus
#

ok, what would be the correct "inverse" of the other.Tryget? would "Else" work or do i need else if !other?

polar acorn
#

true if the component exists

#

false if not

hidden citrus
#

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

summer stump
hidden citrus
#

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

shell sorrel
#

think i would make god mode or not up to the thing that is taking the damage

hidden citrus
#

from the looks of it, it was failing (doing nothing) then skipping to deal damage (which applies no matter what)

shell sorrel
#

the thing doing the damage just looks for the interface to do damage and calls it

hidden citrus
#

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

shell sorrel
#

this feels like more indirection then needed

#

why would the health component not just implement the interface directly

hidden citrus
#

hmm good point

#

so its more like health.TakeDamage. trying to see if there's scenarios where thats unecessary

ashen ferry
tender stag
#

i mean they have id's

#

but i dont use them

#

like i just compare item data

#

the SO

#

like here for example

hidden citrus
#

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

tender stag
#

in the Add method

dusk minnow
tender stag
# ashen ferry do your items have some sort of ids? or just show InventoryCell class

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

ashen ferry
#

I know whats the issue but I cant figure out a good solution to fit in ur code lmao

tender stag
#

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

ashen ferry
#

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?

tender stag
#

like

#

hold on

#

when i double click the blue

#

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

ashen ferry
#

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

tender stag
#

i dont understand

tender stag
#

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

ashen ferry
#

you definitely want QuickStack method specifically created for this action alone dont confuse urself

tender stag
#

u sure?

ashen ferry
#

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 kekW

tepid cove
#

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

wintry quarry
tepid cove
#

hmm i dont think its got a colider, is there a way to make the model the hitbox?

wintry quarry
#

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

wintry quarry
tepid cove
daring tundra
#

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

tepid cove
wintry quarry
tepid cove
wintry quarry
tepid cove
ashen ferry
tepid cove
#

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?

wintry quarry
# tepid cove

I wanted to see the collider(s) not whatever this is

#

Animations aren't related to colliders

tepid cove
wintry quarry
#

If you don't have colliders the bullets will have nothing to collide with

tepid cove
#

yeah

#

idk where the colliders went?

#

do i just re ragdoll it

wintry quarry
#

You're problem just looking in the wrong place? Why not search the hierarchy

#

t: Collider

daring tundra
tepid cove
#

bear didnt come up so it doesnt have any

#

weird

daring tundra
ashen ferry
#

look up what is profiler u need to work with that to see wtf is going on

#

tho yeah sounds weird idk

tepid cove
wary sable
#

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?

tepid cove
timber tide
# wary sable Halo, I'm back with more inventory questions... Since last I have taken a step b...

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.

tepid cove
#

i made a new script and put the code on the bullet @wintry quarry

wary sable
wintry quarry
timber tide
#

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.

wintry quarry
swift crag
#

They both reference an "ItemSpec" object that actually contains the item's stats

daring tundra
timber tide
#

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.

tepid cove
tepid cove
wary sable
#

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

summer stump
tepid cove
#

so i put the bear script on the bullet script?

wary sable
summer stump
ashen ferry
#

arent u supposed to save what u need as poco class and assemble ur monobehaviour from that class

wary sable
tepid cove
late yew
#

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; } }
swift crag
#

ItemReference is a type

#

did you mean to do this.ItemID or something?

summer stump
late yew
#

i should have clarified

timber tide
swift crag
#

or are they both in the ItemReference definition?

late yew
#

the chat one, the image is from something different

swift crag
#

you can't just ask the ItemReference type itself for an item ID. which item are you getting the ID of?

tepid cove
late yew
#
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");
        }
    }
}
swift crag
summer stump
swift crag
#

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

late yew
#

ah right, obviously

#

my brain is fried TT

wary sable
wary sable
ashen ferry
#

imo u gotta walk through simple json tutorial/example online to get the gist

tepid cove
summer stump
green copper
#

How do I make this match rotation of parent instead of world Axis?

timber tide
tepid cove
summer stump
# tepid cove then whats my problem, i think i confused myself

You are confusing me too lol. I'll break it down though. No worries

  1. Bear object has a bear script

  2. Bullet object has a bullet script and bulletragdoll script

  3. Gun has whatever script shoots the bullet

  4. Bullet hits bear object. Collider of bear AND bear script must be on same object.

Done

swift crag
tepid cove
#

the script is on the main body

#

and the colliders are the sub limbs ragdoll

summer stump
# tepid cove and the colliders are the sub limbs ragdoll

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)

wary sable
#

I just need to see it

ashen ferry
tepid cove
summer stump
timber tide
polar niche
#

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?

summer stump
timber tide
# wary sable sorry Im still super new to all of this, are you basically saying that instead o...

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.

wary sable
timber tide
#

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

autumn crypt
#

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

ashen ferry
autumn crypt
wet trench
#

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

polar acorn
dull eagle
#

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

fair steeple
#

Hey, out of curiosity, why can't you use a function that takes a bool parameter in animation events?

timber tide
swift crag
tender stag
timber tide
#

Looks pretty good, what's the problem?

neon wedge
#

can anyone tell me what this means?

tender stag
#

quick stacking

slender nymph
eternal falconBOT
#
💡 IDE Configuration

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.

tender stag
timber tide
# tender stag

You seem to have it working here, no? You just need to delete the original item after stacking.

tender stag
#

i would have this before

#

and it worked like this

neon wedge
slender nymph
#

maybe take a look at the bot message

tender stag
#

i would also have this in the inventory

#

wait it broke completly

#

i wanted to send a video

timber tide
#

After stacking, check the original item's value and if it's 0 then remove it

neon wedge
#

how do i download it

slender nymph
#

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

tender stag
#

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

timber tide
#

Why are you readding it to the slot then?

tender stag
#

this is what causes it

tender stag
neon wedge
tender stag
# tender stag

but i have to add the rest because i Remove the item from the slot

slender nymph
wide silo
timber tide
# tender stag what do you mean

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.

tender stag
#

i need stacking from hotbar cells to the inventory cells

wide silo
#

Exactly

tender stag
#

and from inventory cells to hotbar cells

wide silo
#

So that's the 2nd problem

timber tide
#

Ok, so that was hotbar to inventory

tender stag
#

i need to keep this quick stack behaviour

timber tide
#

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)

tender stag
#

thats what i do in my add function

timber tide
#

You shouldnt remove the item from the slot unless it fully stacks* into another cell

neon wedge
wide silo
slender nymph
tender stag
#

but i dont know how to check if it fully stacks into the the vice versa cells

neon wedge
wide silo
#

Could u send the jump function

#

Like the whole script

#

Bc there's a flipped or a curly brackets placed in the wrong place

tender stag
#

Mao brother please help

#

i wanna go to sleep man

#

lmao

wide silo
#

XD

timber tide
#

I'm trying to figure out in your code where you're readding the item

slender nymph
timber tide
tender stag
#

because i call Remove()

#

which gets rid of the item in the cell

timber tide
#

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

tender stag
#

like stack it, and then leave the rest alone