#archived-code-general

1 messages · Page 436 of 1

zinc flax
#

why? I said that when I checked the player move, it's going smoothly. I'm going to share the player movement anyways but I want to know why.

leaden ice
#

I'm basically looking for whether you're using a Rigidbody without interpolation here

zinc flax
leaden ice
#

can you show the inspector for the Rigidbody2D on your player

zinc flax
leaden ice
zinc flax
tardy tendon
#

Would it be better to add an onclick listener and pass the ID that way?

leaden ice
tardy tendon
#

I'm using lamda

leaden ice
#

to add a click listener

tardy tendon
#

Ah...

leaden ice
#

Did you try adding those additional log statements?

tardy tendon
#

I forgot what I was going to add when I started posting the code lol

#

However

#

I undid all my edits and tried again with is and now it works

#

Thanks for the help

zinc flax
#

I noticed that when I set my camera lans further away from the player, the player sprite has less pixel. When zooming in, we can clearly see a differance. Is there a way to fix this?

cosmic rain
zinc flax
#

when I set to orthographic, the same problem happen.

#

Camera Inspector:

#

Cinemachine camera inspector:

leaden ice
#

your monitor only has so many pixels

#

if you zoom out or in we will see more or fewer pixels representing the same number of pixels in the sprite

#

leading to more or less detail

zinc flax
#

ok so the best thing to do is simply reduce the size of the original sprite as my camera at my default distance is too far to see all the pixel of my sprite

leaden ice
#

I don't know what your goal here is so it's hard to say what the best thing to do is.

zinc flax
leaden ice
#

keep it at 1x to see what it actually looks like

shadow wagon
#

What's the purpose of that scale slider?

leaden ice
#

the game is not going to render extra pixels due to you zooming in on the game view

leaden ice
shadow wagon
#

I've never found it to be of any use, more of an annoyance if I accidentally zpom in

zinc flax
#

lol

shadow wagon
#

smells like a legacy feature that they never got rid of

leaden ice
#

the best use is to allow you to see the full game view when your game view is smaller than the resolution it's set to.

#

you could set game view to 4k and it will render at that resolution even if the game view window itself is smaller

#

which is useful for testing ui layouts and stuff

shadow wagon
#

a very niche case, but I get it

edgy ether
#

alrighty so in the middle of my changing from 2d raycasts to 3d, i noticed that Raycasts dont have a fraction method like Raycast2d.

i'm wondering what is the alternative to it?
or other than that what would be the math to recreate this?
i considered Raycast.distance would be close, but im thinking it doesn't result similar to fraction

hexed pecan
#

The scale can be useful when developing some shaders for example, and you need to inspect individual pixels

leaden ice
shadow wagon
#

yeah that's the only time it's been any use to me

latent latch
leaden ice
#

I'm actually blown awaay someone is using RaycastHit2D.fraction lol

shadow wagon
#

I really seems like it's a feature that doesn't really have any need to be so easy to accidentally zoom in with

edgy ether
#

thank you very much 🙂

shadow wagon
#

huh

#

I think I see the use, honestly if I needed that kind of thing it's something I'd probably write myself

#

I wouldn't have thought such a thing exists

rocky oriole
#

is there a way to change an animation clip's speed in runtime? assuming no multiplier parameter

leaden ice
rocky oriole
#

yeah but assuming i cant do it that way (because i cant in my specific context of modding), is there any other way?

leaden ice
#

well we're not even really supposed to discuss modding here

rocky oriole
#

huh, didn't know modding was considered forbidden/bad-to-talk-about here, my b

leaden ice
rocky oriole
#

ic, well atleast my question doesnt really relate to modding, im just trying to work with the limitations of it lol, but ill stop talking about it thanks

rocky oriole
barren sedge
#

I am trying to make it so that a light lights up everything on the players screen, then eventually is pitch black as the player gets lower. To do this I am changing the inner radius from 11 to 0, then outer radius from 11 to 0. However, when I try to lerp, it doesn't work, but setting to a constant value, such as 0 does. Anyone know why this is happening?

Code that updates light: https://hst.sh/abotutabum.cs (method is run on Update)

leaden ice
#

this looks super suspicious

barren sedge
#

Why?

leaden ice
#

several reasons

cosmic rain
#

Log it

leaden ice
#

one: magic numbers

barren sedge
#

so I'll explain it

leaden ice
#

two: transform.position.y + 20 / -50 order of operations means this is y + two fifths

#

every time

#

which is almost certainly not what you want

barren sedge
#

oh, do I need to add brackets?

leaden ice
#

parentheses

#

same here transform.position.y + 10 / -10

barren sedge
#

yes

leaden ice
#

this is transform.position.y -1

barren sedge
#

I get it

#

Forgot how bedmas works mb

leaden ice
#
        if(transform.position.y < -10)
        {
            if(transform.position.y < -20)```
this is also odd
#

oh I see

barren sedge
#

Yeah

#

I could remove that else statement though and just use Mathf.Min again

#

Ok, it works now!

latent latch
#

The secret is to just put everything in paratheses

#

I hate how vs tells you to remove them. Like no?

edgy ether
#

so in the middle of me working on changing from 2d to 3d. i think i can keep my 2d rigid body since im not really using it much, but change the colliders and the raycasts mainly and that should be enough to make it interact with 3d colliders.

leaden ice
edgy ether
#

well i guess i can make a script to swap them out and pray it doesn't break much lol

#

almost thinking of just forking this and using it to be a whole new project instead of redoing all of the colliders and everything else

#

and just have 2 projects instead of 1 huge one

leaden ice
#

Sounds like a nightmare

edgy ether
#

yeah, i already knew i might end upcrying when i decided to tackle this XD

leaden ice
#

I mean having two projects sounds like a nightmare

edgy ether
#

oh, yeah that too

flint dagger
#

Ok so I got some good advice and started taking on shadow volumes through the CPU rather than compute shaders. And it's sorta kinda working but the detection of silhouette edges (which is outlined with a blue debug line) where a lit face (which has a green line) and an unlit face (which has a red line) meet is proving to be a massive headache and I'm sure that I'm doing something wrong. Any help would be greatly appreciated. furipray2
https://paste.mod.gg/lqwmvryhvuhy/0

wintry crescent
#

possibly cured code warning!! Is there a way to get a name of a variable that was passed in via ref, from code?

I have something like the code attached, and I want to swap my newGO.name = comp.GetType().Name;to use the name of the variable instead, without passing in the name of the variable every time. Is this easily achieavable without a lot of really ugly reflection?

steady bobcat
#

maybe you want to use FieldInfo to start 🤔

wintry crescent
steady bobcat
#

you cant have it both ways 🤷‍♂️

wintry crescent
#

true

chilly surge
#

There's a caller attribute that does it for you, not sure if it's available in Unity's C# version though.

wintry crescent
mossy snow
#

you know that code, as written, will blow up if the T script is missing, right? I assume you meant to create a new GameObject child and use AddComponent

wintry crescent
mossy snow
#

this is a super dangerous snippet btw, if you ever have A with a serialized ref of B and B with a serialized ref of A, then a missing A will probably result in the editor crashing

chilly surge
mossy snow
#

likewise with any self-reference or reference to same type which is unassigned

chilly surge
#

I'd say just do the optional argument, it's not worth the magic even if it's possible.

steady bobcat
#

nameof() and its all good

chilly surge
#

Name of will always return comp

steady bobcat
#

nah i mean when they pass it as an arg

#

DoThing(a, nameof(a))

chilly surge
#

Yeah, and caller expression basically does that for you

#

But it's not available in Unity and probably not a good idea anyways.

twilit scaffold
#

what is this quickview window called, in VS? i am trying to find a way to change the size, but i cannot recall the name to do a search

inner bluff
#

its only me or others also have problems with SerializedDictionary ?
Im using Unity 6000.0.41f1 and every time when i look to script that have SerializedDictionary it looks like this (1 pic.)
When i reset this script it back to normal (2 pic)
and then i can use crtl+z and it back to how it should looks like in first place.

wintry crescent
vestal arch
#

more like there's one for unity

shadow wagon
#

never got much use out of it as shortly after using it, I figured a Dictionary wasnt actually something I needed to use at the time

#

for the 5 minutes it was in use, it worked very well!

inner bluff
#

i use it for randomize sounds before moving to free wise

#

ah ok this is Audune.Utils.Dictionary; and im using AYellowpaper.SerializedCollections; so this is something on my side, okay! 😄

prisma helm
#

hey does anyone know what code to use to force quit a vr game on a meta headset? (android)

#

I already have some code from the unity website thing but idk if it works, and I cant go on vr to check anytime soon

true heart
#

I want to stream live the android's camera over an API, anyone knows how?

hasty stream
#

Hello all! I am currently making an angrybirds-esque game and I have this code set up. I am trying to make it such that there cannot be more than 1 ball on screen at any time AND ensure that all balls are despawned before initiating the Game Over. I am having trouble because of a specific sequence:

  • I shoot 1 ball from the launcher, all is well, except for the fact that IsBallInAir is stuck as being true
  • I attempt to shoot a second ball, but nothing spawns.

I have it set such that, when a ball is destroyed, the projectile handler is listening and sets IsBallInAir to false when it receves that Unity Event. So I have no idea why the boolean IsBallInAir is stuck being true.

The only place in the script that sets IsBallInAir to be true is LaunchBall(), which is called by OnRelease(), a method that listens to when the user lifts their finger off of the touch screen. OnRelease() is definitely only being called once.

https://paste.mod.gg/amvrizxbyzit/0 - Ball.cs
https://paste.mod.gg/jkrdneaadeco/0 - Projectile Instance Handler.cs

lean sail
tawny elkBOT
hasty stream
storm wolf
#

Do you even do anything with OnBallDestroyed??

hasty stream
#

The crux of the problem isn't that IsBallInAir isn't being set, it's that IsBallInAir is being set to true somehow even after OnBallDestroyed() is called

lean sail
#

and read the bot message, that code is really hard to read in discord

hasty stream
#

I'm thinking I might just overhaul the ball class to work using a state machine

#

I am not very good at writing those so this'll be fun

storm wolf
#

I am pretty sure the destroyed event never gets fired also, the object will have been destroyed by then, should be firing right before destroying

lean sail
#

you're making very simple logic into extremely complex code, and seemingly not even using most of it. i thought AI wrote it because you have generic classes and events that seemingly arent used

steady bobcat
lean sail
#

You dont need a state machine here, it will just complicate things more. your only "state" is really a bool, if the object exists or not. You could even just store the last launched projectile, and check if its null because you're destroying it anyways. no real need for events but it is cleaner if you want to change functionality later

steady bobcat
storm wolf
#

weird to begin with imo

steady bobcat
#
Destroy(gameObject);
gameObject == null; //true!
ReferenceEquals(gameObject, null); //false
lean sail
storm wolf
hasty stream
lean sail
storm wolf
#

yea not that we can see anyway

hasty stream
storm wolf
#

What are you subscribing to it?

lean sail
#

its not a compile issue, but i dont know how unity events actually work since i dont use them. i dont know how you've assigned it in inspector is all

hasty stream
#

Posting code

lean sail
#

still, please just rewrite that code lol. consider this #archived-code-general message
this type of problem id honestly say is #💻┃code-beginner . i just didnt suggest it initially because your code had generic classes so i assumed more complex stuff was going on

#

we can also just keep the rest in the thread since this probably wont be quick

summer heart
# hasty stream that is correct

if you're only subbing to the ball's destroyed event in the inspector, when you create a new ball it will have a new event that's not subbed to. You need to sub to it programmatically

ball.destroyed.AddListener(BallDestroyed);
hasty stream
summer heart
#

going to the thread 👉

hasty stream
#

lets

stuck dirge
#

It is normal that when creating a shader it comes by default with 20 or 19 errors ?

lilac frigate
#

are there any discords to higher 3d modellers and animators etc? for commission

edgy ether
#

ok final question regarding converting from 2d physics to 3d.
lets say i just switch everything to 3d, but i still have my 2d colliders on stuff, is it possible for 3d colliders to detect 2d colliers in some shape or form or even detect them the same way that 2d colliders detect (like when they ignore z axis)
if i can at least make 3d colliders detect eachother the same way 2d does, i can possibly make a tool to convert 2d collider points to 3d

#

i seemed to have an idea how i can keep both things within the game though

mighty rampart
#

hey im sorry to ask such a generic question but im having issues rigging avatars to users in XR. They keep t-posing at the origin

#

is there a trick to it?

edgy ether
mighty rampart
#

im using building blocks networked avatar - as far as i can tell it should work but no idea where to start

edgy ether
# rigid island same here where is code question ? <#497872424281440267>

that's why im asking the question relating to "general coding concepts" lol

like you know how using Physics.Raycast can detect 3d colliders
and Physics2d.Raycast can detect 2d colliders. (well in my case i used Physics2D.LinecastNonAlloc)

i was wondering if it's possible in code to treat a 3d raycast to ignore the z axis the same way a physics2d.raycast would?

vestal arch
#

not really, that's just not how they work

#

physics2d raycast "ignores z" because it doesn't even have a z component

rigid island
#

physics2d is strictly working with X,Y

vestal arch
#

strcitrl

rigid island
#

lol

vestal arch
#

new string function unlocked

edgy ether
#

ah yeah, that's understandable... the only thing i can think of (and it's not a great idea) is to simply do a really long linecast across the z to fake it lol.

rigid island
#

what exactly is the usecase here

edgy ether
#

switching from 2d physics to 3d.

rigid island
#

yeah but whats the problem

#

why did you want to mix 2d colliders and 3D

#

most 2D / Vector2 positions are compatbile with Vector3

#

Unity is a 3D engine no matter what you do anyway, its just the Physics that changes

lucid relic
#

I'm working on a Unity player selection system where players can create a new profile with a name and age, and their level is assigned based on the age. The data is stored in a JSON file and loaded when the game starts. At the end of each level, if the player has accumulated enough points their level should be updated, the level updates in the JSON folder but when the user goes back to the main menu 2 things happen.

a) All of the players from the players list are gone
b) Once restarting the game the players do appear but whilst in the JSON file their level has updated, inside the game their level has increased to 4 for some reason.

See video and code below.

https://pastebin.com/KyAhfYSM
https://pastebin.com/EFjZKCzg

edgy ether
# rigid island why did you want to mix 2d colliders and 3D

well at first the game was mainly a 2d platformer, but i had an idea to start giving it 3d movement for some parts of the game, but i want to switch to it seamlessly. while it's going to be on a railed path, i can't simply place 2d colliders on the z-axis and expect the 2d rigid body to pick it up. so im using 3d colliders

the problem is this idea is pretty late into the project and i have like guesstimated like 4000 2d colliders as prefabs. and changing all of them to 3d would be tedious (unless i get some sort of epiphany and is able to make a tool to switch them)

but yeah, seeing as i cant treat 3d colliders the same way as 2d, i'll just approach this differently

vestal arch
#

i can't simply place 2d colliders on the z-axis and expect the 2d rigid body to pick it up
can you elaborate on this?

#

specifically, what do you mean by placing them on the z axis

rigid island
edgy ether
rigid island
#

so if they move on Z they cant interact with 2D

edgy ether
#

yea

#

im terrible at explaining

vestal arch
#

they wouldn't have rb collision though as you said

rigid island
#

even so

#

3d raycasts dont detect 2D colliders

vestal arch
#

(not saying it's a good idea though)

rigid island
#

you have to switch everything to 3D colliders and physics.ray funcs

vestal arch
#

im confused what the issue is right now

#

what im saying is you could have the 2d stuff (as in, objects that present 2d rbs and colliders) use 3d raycasts (and i guess vice versa)

rigid island
#

they just want to mix 2D and 3D and that wont happpen, the next best thing is converting to 3D colliders

rigid island
vestal arch
#

that's not what im saying

edgy ether
#

yeah i was thinking of keeping the 2d rigid bodies and use 3d raycasts to pick up the 3d colliders since i dont really use the 2d rigid body for much. i was planning to explore it, but im already preset to swap in a 3d rigid body.

rigid island
#

what would 3D raycasts be for though

vestal arch
#

object, in 2d, with 2d colliders and rb, has script that uses 3d raycasts to understand the 3d colliders and rbs

rigid island
#

Ohh I see what you mean

#

but they want to move some 2D object on the Z axis from what I gatheer

vestal arch
#

i don't know if that's a good idea though; all im trying to say is that that seems possible

edgy ether
#

im going to expiriment with this

#

tyvm

rigid island
#

yeah since physics3d is pretty much same as 2D, I would just get rid of 2D altogether and stick to 3d imo

edgy ether
#

yeah, i definitely thought of that but. when you got like 4000+ already made 2d colliders (for prefabs) it makes me question my sanity a bit lol

vestal arch
#

yeah im still not quite sure what you're trying to do lol

edgy ether
#

if i got no choice i will though... (probably finally pick up watching one piece while i go through converting all of them)

#

at the same time, i considered just making it a new project. but i'll update on what i manage to do

toxic stag
#

guys am new to unity and i got a probleme really annoying , like my mouse get of the scene like the cursor go right and he came of the other side of my screen and The W D S Q not working i tried to change in Shortcut

toxic stag
leaden ice
#

I mean, I read your sentence and have no idea what you are trying to say.

toxic stag
#

oh

edgy ether
#

thank you very much for the inputs btw

toxic stag
#

lemme explain

fleet gorge
rigid island
#

doubt it

fleet gorge
#

I see

rigid island
#

Unity is just using the box2d engine so whatever they got there

#

its a 2d engine so probably stuck xy defacto

fleet gorge
#

I might have to do it the other way round of attaching 3d models to the 2d objects where Z is up

#

I didn't know unity is on box2d though

rigid island
#

ya
2d = box2d
3d = physx

fleet gorge
#

Also, newest 50 series cards don't support PhysX now right? Is that a problem for unity games

rigid island
#

not sure on this

#

they also have their own physics for ECS so I'm lurking that

fleet gorge
#

I haven't seen unity games as affected but mirrors edge is just unplayable

toxic stag
rigid island
#

Oh also Havok is there if you have a pro license

fleet gorge
#

Oh havok comes with unity too?

fleet gorge
#

I thought I had to download it off somewhere

#

Huge

rigid island
#

just the binary so you don't get the sourcecode but its still an amazing physics engine

lilac frigate
#

any discords to find unity modellers?

vestal arch
#

not this one, !collab

tawny elkBOT
#

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
Collaboration & Jobs

lucid relic
#

I'm working on a Unity player selection system where players can create a new profile with a name and age, and their level is assigned based on the age. The data is stored in a JSON file and loaded when the game starts. At the end of each level, if the player has accumulated enough points their level should be updated, the level updates in the JSON folder but when the user goes back to the main menu 2 things happen.

a) All of the players from the players list are gone
b) Once restarting the game the players do appear but whilst in the JSON file their level has updated, inside the game their level has increased to 4 for some reason.

See video and code below.

https://pastebin.com/KyAhfYSM
https://pastebin.com/EFjZKCzg

edgy ether
# lucid relic I'm working on a Unity player selection system where players can create a new pr...

well the players in the player list goes away when you hit the players.Clear(); when you hit LoadPlayers() on your first pastebin.

also from what im seeing if the age is probably returning a number that makes the game just returns a value of 4. from what i see in the

public int AssignLevelBasedOnAge(int age) ```

is the age not within that numbered variable? what happens if they are younger than 3?
lucid relic
#

the return 4;

#

if they're under 3 then no profile is created

edgy ether
lucid relic
#

theres nothing directly stating that i dont think but that is just what happens when you create a user under 3

edgy ether
#

ah, it looks like it will also just return 4 since nothing was specified for it 🤔

simple egret
#

Yep correct, profiles under 3 will have level 4, since the 3 if statements won't be satisfied it'll hit the very last return instruction

edgy ether
#

OH i see what's going on

#

is it because "return 4;" is not under an "else" ?

#

so despite what is changed prior, it will just go back to 4?

lucid relic
#

I dont think it does because if you enter someone over the age of 9 it will return 4 and assign level 4. when under 3 is added it is not added to the player list nor the json

vestal arch
edgy ether
#

ah ok.. yeah i think i understand, return makes the script stop at that point so that's why that part is fine.

lucid relic
#

the problem is the second time round, when i click on the main menu, the player list dissapeas. However if i restart the game the player is shown (because it was updated in json) as level 4.

#

i think i have an idea why it sets as level 4 but im confused why the player list doesnt appear (maybe the loading of players from json file is not working?)

#

does anyone knoe how to fix?

rigid island
lucid relic
#

on the video

#

when i click to go back to menu the entire player list dissapears and players are loaded , also when the game restarts. eg when i stop and replay the game, the new player has a level of 4 instead of 2

rigid island
tawny elkBOT
lucid relic
rigid island
lucid relic
#

those are debug warning i have put to see if each thing works

rigid island
#

like "No player data found."

lucid relic
#

yeah what i was trying to make the old buttons clear and then reload the new buttons (so that the level displayed is updated) but it says that there are no buttons to clear making it seem that the buttons were cleared by something else before it. also the no player data found was because i deleted the json file to shwo a clean start

safe jay
#

I wrote a progress bar script that does work, but wondering if i could get any help having it change based on the current score variable?
Still new to c# and learning, Thanks!

Progress bar https://paste.myst.rs/yl20e5aw/history/0
Score script https://paste.myst.rs/in87usrg/history/0

rigid island
safe jay
#

That's mainly for when the player reaches for example 100 score it allows them to shoot

#

so the bar will be full after say 100

rigid island
safe jay
#

Yeah so just as the score increases the progress bar moves up until value 100 for example

#

thanks

rigid island
twilit scaffold
thin hull
#

what do you think is the best way to implement cooldowns into a game

leaden ice
#

The question is too vague

thin hull
#

i've seen coroutines, timestamps and quarternion uses

#

would u say any of em is superior to the others

leaden ice
#

Quaternions??

thin hull
leaden ice
#

Yeah I know what a quaternion is I don't have any idea how they are related to cooldowns

#

Quaternions represent rotations

thin hull
#

some snippet i found online

leaden ice
#

The time stuff is the cooldown

#

The quaternion has nothing to do with it

#

That's just the rotation it's spawning the object with

thin hull
#

ye i should reread stuff

jagged plume
#

you could probably get rid of the boolean but I kept it for some reason

#

other than that just set some CONST value for your CD, assign it to your timer on ability use, and remove Time.deltaTime each frame that passes while ability on Cooldown (and make sure ability cannot be used, e.g. why I have a bool here)

#

arguably if jumpCDTimer > 0, MC cannot jump so boolean redundant, but you get the idea

#

Fyi I call JumpLogic() (the method seen above basically in the last two screens), every frame in Update()

thin hull
#

i just have 10 stray if statements floating around

jagged plume
dusk apex
#

How to properly post !code (large code blocks and discord inline)

tawny elkBOT
thin hull
#

i mean it makes sense because if something breaks u know roughly where to go tbf

jagged plume
#

I'd say

jagged plume
thin hull
jagged plume
#

At least that's the way I go about it

#

Sometimes I know from the start so I write the function directly

thin hull
#

3 of these lil guys ```

#

okay idk how to format so the middle one is in a block

thin hull
dusk apex
naive swallow
thin hull
naive swallow
#

float x = 1.5

#

see what it does

dusk apex
jagged plume
#
        if (!canJump) {
            return;
        }
        // Handle Jump CD Timer
        if (!canJumpTimerComplete) {
            jumpCDTimer -= Time.deltaTime;
            if (jumpCDTimer <= 0f) {
                canJumpTimerComplete = true;
            }
        }
        // Handle Jump Input
        if ((Input.GetButtonDown("Jump") || Input.GetKeyDown(KeyCode.W)
                || Input.GetKeyDown(KeyCode.Z) || Input.GetKeyDown(KeyCode.Space)) 
                && isGrounded && canJumpTimerComplete) {
            rb.AddForce(new Vector2(0, jumpForce), ForceMode2D.Impulse);
            canJumpTimerComplete = false;
            jumpCDTimer = JUMP_CD;
        }
    }
``` cs
#

oooooh

#

I feel like this is more readable though

#

The indents gets weird with the backticks

thin hull
dusk apex
thin hull
#

and the pictures get cropped if u send more than one

pastel atlas
#

An illustration; I want to get the closest point to my capsule collider's "foot" region, the center of the bottom circle, within some acceptable range, say an extra 0.1 units.
Physics.OveralapSphere will return the collider i'm touching, but the ClosestPoint method will only work on boxes, spheres, boxes, or convex mesh which mine is not.
If I do a spherecast with radius Capsule.radius + 0.1f, any Raycasthits that return will be zero since they overlap, so I can't iterate through those.
I could spherecast from inside the capsule collider and point it in a given direction with some distance but then you ignore all the parts of the bottom capsule that aren't covered by that spherecast.
Should I do simple raycasts in idk how many, like 32 directions to check hits then find the closest one and only then spherecast along that direction if I want the exact point? Seems a little jank but I guess it wouldn't be expensive to run. No expanding spherecast method sadly.

Are there other possible solutions?

lean sail
#

I dont think there is a spherecast solution here if it can ever start with overlapping the object. Even the all/nonalloc methods
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Physics.SphereCastAll.html

For colliders that overlap the sphere at the start of the sweep, RaycastHit.normal is set opposite to the direction of the sweep, RaycastHit.distance is set to zero, and the zero vector gets returned in RaycastHit.point
im not too sure you'd be able to use it considering .point is assigned the 0 vector.

#

I guess it at least tells you something was hit 🤔

dense pasture
#

Curious if it’s any good for custom abstraction, in lieu of graph foundation or whatever it was. Is there even a release date on that?

worldly vortex
#

Idk if this is the right place to ask this but.

Are banner ads supposed to be super small? For some reason my banner ads are tiny in any portrait mode that is not 16:9

edgy ether
#

so an update. whileim notdone, i have managed to make it work with 3d colliders so far. i havent swapped out the rigidbody2d yet though, but im unsure if i need to do that yet

dense estuary
#

I am attempting to make the player die when their health reaches 0, and I want to teleport them to their original position. For some reason teleporting them to the world origin, without disabling any scripts or anything, is preventing them from being able to walk, the debug shows that the values are being set, but the player isn't moving.

This is my code: cs private void Update() { if (shSystem.healthSys.health == 0) Die(); } void Die() { for (int i = 0; i < inventory.items.Count; i++) { if (inventory.items[i] != null) inventory.Drop(i); } transform.position = origin; }

#

The code that drops all the players items upon death is working fine, but for some reason setting their position to the origin prevents them from moving.

leaden ice
#

Update runs every frame

#

there's no reason to use Update for this

#

The check for health <= 0 should happen at the time that your character loses health

#

instead of just having a public health variable you should use accessor (get and set) methods, or a TakeDamage method, or use a property.

#

This way you can control that whenever the health is reduced, you check if the character has died

#

then you don't need to be checking every frame.

dense estuary
leaden ice
#

by using an accessor method or property you ensure there is only one place in your code where health can decrease

#

and therefore only one place where you need to check if the player died

#

Are you saying that I should just check if the players health is 0 whenever I lower the healt
Yes. Something like this @dense estuary

// private so nothing can touch it.
private int health;

// We only change the health varaible through this property
public int Health {
  get => health;
  set {
    health = value;
    if (health <= 0 {
      health = 0;
      Die();
    }
  }
}

public void TakeDamage(int damage) {
  Health -= damage;
}```
dense estuary
# leaden ice > Are you saying that I should just check if the players health is 0 whenever I ...

So the problem is that my health and stamina are mixed together, similarly to how its set up in LOCKDOWN protocol, when the stamina is empty and the player keeps running, it starts to drain the health. This is my script at the moment: https://hastebin.com/share/geyujaxire.csharp

leaden ice
dense estuary
#

The health mainly drains slowly via a Mathf.MoveTowards() method.

leaden ice
#

that doesn't change anything

#

The code I shared about would live in HealthSystem

dense estuary
#

Oh wait, your right.

#

So the Die method would also lie in the HealthSystem class, so I would need to give the health system access to some of the classes the player class has access to, in order to make dying disable some of the player scripts.

leaden ice
#
public event Action OnDeath;

void Die() {
  OnDeath?.Invoke();
}```
#

then your player script can subscribe to OnDeath

#

and do what it needs to do

#

this way you keep all of the references pointing the same direction

#

the health system won't need to know anything about the other scripts

#

I would probably also use an event for every time healthj changes in general

#

then you can use the Observer Pattern for UI elements etc to show the current health

dense estuary
#

Also the UI uses a custom shader to display the Health and Stamina.

leaden ice
#

it doesn't matter how it displays it

#

doesn't change anything

#

The observer pattern is a pattern where the script responsioble for displaying the health would simply subscribe to an event, like a OnHealthChanged event

#

and update itself whenever the event is fired

#

this way the health script doesn't need a reference to the "displaying health" script

leaden ice
#

in this case you'd put it right in the health proeprty as well:

public event Action<int> OnHealthChanged;
int health;

public int Health {
  get => health;
  set {
    health = value;

    // let observers know the health changed
    OnHealthChanged?.Invoke(health);
    if (health <= 0 {
      health = 0;
      Die();
    }
  }
}```
#

this is the beauty of having the single access point for changing the health variable

#

now we know that whenever we change the health:

  • We always do the death check
  • We always update the UI
#

if you use a public variable it becomes a mess

dense estuary
#

I've never used events before, how would the player class "subscribe" to OnDeath or OnHealthChanged?

leaden ice
#
void OnEnable() {
  shSystem.healthSys.OnDeath += DeathHandler;
}

void OnDisable() {
  shSystem.healthSys.OnDeath -= DeathHandler;
}

void DeathHandler() {
  Debug.Log($"Detected that the player has died");
}```
#

like this

dense estuary
leaden ice
#

yes although I would probably just make a function likecs public void Reset() { this.health = this.baseHealth; } on HealthSystem to reset the health

dense estuary
leaden ice
#

it isn't necessary

#

it was just be explicit about what it's doing

dense estuary
#

That makes sense, thank you, you were very helpful for me, I am going to rewrite a lot of jumbled code with events.

dense estuary
#

Its like the rb is setting the position to a position that was determined just before the player died. Possibly caused by the event being out of sync with the Update method.

sturdy holly
#

has anyone used I2 lately? and if so the google side of it - I cannot get it to install the service to connect to google sheets, it seems it was updated at some point google side and it simply doesnt work now?

trim schooner
sturdy holly
#

ah thanks will look

#

excellent thanks @trim schooner

woeful hamlet
#

How can I change the sprite of a UI Image from another script? I'm trying to access it (from another MonoBehaviour in the same scene) via
GameObject.Find("BG Image").GetComponent<Image>().sprite;
But that gives me the error
ArgumentException: GetComponent requires that the requested component Image' derives from MonoBehaviour or Component or is an interface.
Am I missing something? Is Image not a Component?

west lotus
#

Image is very much a component you are probably using a type from System that happens to be called the same. Do you have using UnityEngine.UI in your script ?

vestal arch
woeful hamlet
#

It's UnityEngine.UIElements.Image

west lotus
#

That is not a component

woeful hamlet
#

Well, that's slightly unintuitive. But using UI.Image did the trick, thanks^^

west lotus
#

You are mixing up the old UI system and the new UIToolkit

woeful hamlet
#

Ah, I see. I'm still kinda new and bad with UI stuff.

west lotus
#

If you are using a Canvas you need to use the things in UnityEngine.UI

#

Just forget about UIElements

#

Or better yet since you are new, forget about the canvas and learn UIToolkit since that is the future

placid edge
#

not really a problem for my project more of a question but im using Random.Range(0, array.Length) and it's showing the random range as an int, which to my understanding excludes the last number as it says MinInclusive,MaxExclusive, but it's outputting the last item on the list at times, i guess my question is does .Length inherently +1s itself in cases like this?
I hope I explained that properly ;v

#

sorry not list, it's an array

vestal arch
#

.Length inherently +1s itself
...what?

#

it would not lie about the length, no

#

in cases like this
the Length getter wouldn't know (nor care) about what kind of case it's used in, it just does its job

#

the last item of the list is supposed to be accessible

#

Length isn't a valid index

#

if you have an array of length 3, you would have 3 elements at indices 0, 1, 2

placid edge
#

right

#

but when i use random.range with ints, it says it's maxExclusive, meaning it excludes the last number, and i know its done this before because i use Random.Range(0,2) as a coin flip. But when I use .Length, it does output the last number, which is where im getting confused.

vestal arch
#

length is 3

#

it's not gonna output 3

#

it outputs at max 2, which is the last element of the array

placid edge
#

but it does for me is what im saying

vestal arch
#

it outputs the value Length?

placid edge
#

wait

#

ohhhhhhhhhhhhhhhhhhhhhhh

#

god i forgot arrays start at 0 thats embarrassing

#

haha

vestal arch
#

do you know how to read sets in range notation? (eg. [0, 5))

#

that might help internalize it

placid edge
#

yea yea, sorry its been a long day

night harness
#

(also heads up that the float random is max inclusive, the int max being exclusive is kind of an outlier likely specifically so you can just easily plug in a collection length into it without worry)

placid edge
#

yeah ive seen float randoms are max inclusive, it was an issue i wasnt aware of for a while

#

so an array of 3 would output 0,1,2 and then exclude 3

#

for ints

night harness
#

your wording might be enabling your downfall

vestal arch
placid edge
#

i am not very good at explaining things 😔

night harness
#

taking that sentence literally an array of 3 would output 3 assuming it's just an array containing 3

vestal arch
vestal arch
night harness
#

an array containing the first three numbers would output 1,2,3 because it's (0,3) for the index where [0] = 1, [1] = 2, [2] = 3

vestal arch
#

smh 0 not being the first number, what is this blasphemy

placid edge
#

yeah, i just forgot it starts at 0, which is crazy considering how many lists im using right now. i think im just tired

vestal arch
night harness
placid edge
#

ah, ah, ah

wintry crescent
#

is there a way to add a static method to a class like Color?

#

I want to create Color.Uniform(myParam) for creating colors with the same rgb values without copying and pasting the same things 3 times

#

I have ColorExtensions for it right now, and I know I can add it when operating on an object (via using a this Color color parameter)

leaden ice
wintry crescent
#

but I want to add it to the Color class directly

leaden ice
#

those are your two options

#

Extension method would look like:

public static class MyExtensions {
  public static Color Uniform(this Color c) {
    return c; // do whatever you need here
  }
}```
And you would use it like:
```cs
Color x = Color.red;
Color y = x.Uniform();```
leaden ice
#

best you get is extension methods

hexed pecan
wintry crescent
#

While I want to use it as a shortened version of the constructor

leaden ice
#

It can't be done

wintry crescent
#

sth like this

        public static Color Uniform(float rgbValue, float alphaValue)
        {
            return new Color(rgbValue, rgbValue, rgbValue, alphaValue);
        }```
wintry crescent
leaden ice
#

you have to make your own static class:"

public static class MyColorStuff {
          public static Color Uniform(float rgbValue, float alphaValue)
        {
            return new Color(rgbValue, rgbValue, rgbValue, alphaValue);
        }
}```
Then call it like `MyColorStuff.Uniform(..)`
wintry crescent
#

yea I have that right now

#

wanted to make it cooler

#

but I guess no luck

leaden ice
#

¯_(ツ)_/¯

jagged plume
#

Does anyone use multi-cursors ???

#

This seems like a crazy feature

chilly surge
#

If by multi cursor you mean the text editing feature, yeah it's essential

vestal arch
#

it's a great feature

chilly surge
#

It takes like maybe 10 minutes to learn, and it easily pays it back in everyday's work. Everyone should learn it.

#

I've seen people who open up Excel to do text editing in cells with formulas and stuffs for repetitive code, then after they are done they copy it back into IDE. Could've just done the same thing with multi cursor directly.

jagged plume
#

why not just use regex?

#

that's what I have been doing so far

vestal arch
#

regex is more flexible, multi-cursor is faster & easier to do directly

jagged plume
#

maybe regex feels faster / easier because I have more exp. doing it

chilly surge
#

Yeah most cases don't need regex's flexibility and can just be done with multi cursor, and done faster.

jagged plume
#

in VSCode, do you have to spam CTRL+D to select all identical wording (?)

chilly surge
#

The only time I still do regex is if I need complex conditional matching/doing it across multiple files which multi cursor doesn't allow.

chilly surge
jagged plume
#

Ok it's good

chilly surge
#

Pretty much for multi cursor you just need to learn and get familiar with (VS Code shortcuts in parentheses, but other IDEs should all have similar shortcuts):

  • Insert a cursor above/below (Ctrl + Alt + Up/Down arrow)
  • Insert a cursor on the next matching word (Ctrl + D)
  • Insert a cursor on every matching word (Ctrl + Shift + L)
  • Insert a cursor on every line (Shift + Alt + I)
  • Navigate by word (Ctrl + Left/Right arrow)
  • Navigate to start/end of line (Home/End)
    For VS Code specifically:
  • The command "Emmet: Evaluate Math Expression"
  • A bit niche, but you can use an extension/a snippet to add the cursor number for every cursor.
#

The first parts are the ones that everyone should know, takes little time to learn and will get use out of them every day. The second parts are a bit niche but very useful in some situations, eg you can use it to generate a sequence of numbers some values apart, open a spritesheet and shift all coordinates by a certain amount, etc.

vestal arch
#

middle click + drag also lets you do multi cursor or select an area

rain wigeon
#

Not sure if this is a "general" issue or an "advanced" issue but
I want a mechanic in a game i'm making for a class where if the ball collides with the player, the player respawns at a certain point
when i test, the game recognizes that the player and ball have made contact, and so the player should respawn...but the player doesn't respawn
both the player and ball have rigidbodies and colliders, but the ball bounces off the player instead of the player respawning
not exactly sure if this is a scripting issue or a physics issue

leaden ice
#

From the logs it looks like... both?

#

also if they're bouncing off it sounds like you're not using a trigger collider, but your logs are logging which implies you are using at least one trigger. Do your objects have multiple colliders?

rain wigeon
leaden ice
#

This implies that some object with the script is interacting with the player

#

in other words, is not the player itself

#

unless PlayerArmature is not the player

#

Can you show how the hierarchy is set up and which objects have which scripts?

rain wigeon
rain wigeon
leaden ice
#

and so maybe the parent object which is empty is getting moved

#

and the armature itself is not getting moved

#

because it's a separate Rigidbody

#

you would need to show screenshots of how everything is set up to confirm

rain wigeon
#

here's the inspector and hierarchies

leaden ice
#

anyway you should type this into the search field in the hierarchy:
t:PlayerRespawn to make sure there aren't extra copies

barren glade
#
 private void tween_camera(Vector3 axis) {
        System.Action<ITween<float>> circleRotate = (t) =>
            {
                transform.rotation = Quaternion.identity;
                transform.Rotate(axis, t.CurrentValue);
            };

            float startAngle = transform.transform.rotation.eulerAngles.x;
            float endAngle = startAngle + 90;

            // completion defaults to null if not passed in
            transform.gameObject.Tween("RotateCircle", startAngle, endAngle, 0.35f, TweenScaleFunctions.CubicEaseInOut, circleRotate);
    } 
```Heyo, I have a tween library, but I can't seem to figure out why it doesn't work properly if i remove the```c#
transform.rotation = Quaternion.Identity```I'm trying to rotate on top of the current rotation, but the identity resets the rotation that's why I tried removing it, but it breaks the tween completely
leaden ice
rain wigeon
leaden ice
#

you can't teleport a CC with transform.position without disabling it first

barren glade
leaden ice
#

that are ultimately going to make things worse

rain wigeon
#

I don't, you're right
I assumed that the CharacterController wasn't enough
because the player wouldn't respawn and I added a rigidbody, which didn't fix the issue either

leaden ice
#

yopur main issue is this

#

your secondary issue is that your object is all kinds of messed up with a bunch of competing components that do the same thing in different ways and will conflict with each other

rain wigeon
leaden ice
#
cc.enabled = false;
transform.position = whatever;
cc.enabled = true;```
rain wigeon
rain wigeon
hexed oak
#

I have a weird issue where I'm doing a null check on an interface and instead of returning null, it's returning "null"

rain wigeon
#

thank you very much

leaden ice
hexed oak
#

ah I found why. The reference is in another scene, and the scene is unloaded

glossy valley
lean sail
glossy valley
#

I've heard that often, what is so appealing about the new input system compared to the old one? I think the old one is much easier to implement.

lean sail
glossy valley
#

I suppose you're right if I'd ever need to make changable input settings, it would be easier, and that double tap function would also save me time

#

I'll definitely look into it, buut what about no alloc versions? I don't follow

lean sail
#

i linked the non alloc version, you simply dont allocate an array every single frame

glossy valley
#

I see, I'll have a look at it

#

So it's pretty much the same to the eyes, but it's more performant?

lean sail
#

if you do also use the legacy input system, one thing im not a fan of is having the actual Input.Get... stuff randomly throughout the code.
if you look at HandleInteraction, it doesnt do anything if Input.GetKeyDown(KeyCode.E) is false. So you could keep this purely in Update, where you dont even call HandleInteraction if they weren't pressing E

lean sail
#

Its not gonna change your life here but its just something you should get used to using. I wouldnt call it a micro optimization either

glossy valley
#

Yeah as I said, I just want to get rid of bad practice in the beggining

#

It's better to do it now than later, I had a hard time when doing js cause I made the same mistake when I was younger, so I pretty much ended up with a ton of bad habits that made everything harder

night storm
#

using the keyword "new" in update or code that is called often is generally bad (unless its a struct) because it triggers garbage collection and will cause lagspikes

lean sail
vestal arch
#

garbage collection happens anyways, but if you create a lot of reference type objects that you don't use for long, then you get a lot of garbage to collect

#

new is fine if you need it; check if you actually need it

glossy valley
#

I just haven't put it to use as I just changed this current script cause I found some faults

lean sail
#

You could probably handle it very simply. The interactable has an empty game object on it as a child which acts as the point where the highlight should be

glossy valley
#

Yeah but considering I'll have a ton of them, I just wrote a script for it to save some time

lean sail
#

Thats how id do it at least if interactable objects would need it placed in weird locations. But this is also a non-existant problem potentially if they all have similar structure

glossy valley
#

It's a top down 3d game so basically little to no terrain

#

Just a flat space,

night storm
#

if you need to use "new" in code you call multiple times though then its a good idea to store it in a variable, right? unless that code is called multiple times but very rarely in which case storing it in a variable might be a bit worse, idk

leaden ice
lean sail
glossy valley
#

The lowest point, and then adds a little, it's a highlight, I'll show you

lean sail
#

Ah i get what you mean, i was imagining an arrow or something

glossy valley
#

Oh, I

leaden ice
glossy valley
#

I'll have that eventually, but until then this works fine

lean sail
#

Ok then yea what i said probably doesnt apply. i think what you did with position + 0.05f is actually fine then

glossy valley
#

I'm actually very happy how it turned out tho, I made it very easy to implement in all objects that are interactable, so I just add the interactable script to it

#

Something I had issues with was getting the correct raycast for this though, I used spherecheck in the beginning, and then moved onto just rays but took me a full day to find OverlapSphere in the docs 😦

vestal arch
mellow geyser
lean sail
glossy valley
#

But overlaysphere was exactly what I was looking for, spot on 🙂

lean sail
#

I was saying you could raycast as well after getting the closest object, to make sure the player can actually see the object

#

!collab

tawny elkBOT
#

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
Collaboration & Jobs

naive swallow
#

(You were told this already)

glossy valley
#

It'll be pretty easy to implement luckily

#

For items, I won't be doing drops, it'll all be in menus so no item drops, is there any point of doing scriptable objects for items? I've only seen scriptable objects be used to physical objects

night storm
#

what kind of items do you have?

leaden ice
#

whether or not they're physical seems immaterial

glossy valley
#

So it's like a preset or a container basically?

#

I'm guessing this saves a ton of performance if you're dealing with a large scale of objects

night storm
#

its a way to avoid making a separate script for each item

glossy valley
#

I would want to use this for my trees then I think

night storm
#

can you put trees in your inventory or something?

glossy valley
#

No but they're repetetively placed wherever you go

#

Different trees, same logic

night storm
#

if they're just placed in the level then use a prefab, not scriptable objects

glossy valley
#

I have prefabs right now

night storm
#

scriptable objects are useful for stuff like items in your inventory, i dont see how they would help with trees

#

and you cant save performance with scriptable objects

glossy valley
night storm
#

how does it save performance with your trees?

glossy valley
#

You wouldn't have to duplicate the tree data across multiple instances, u reference to a single scriptable object that contains the shared data, as it avoids copying information

#

alot of memory saved

night storm
#

what data do they have? isnt it just a model?

glossy valley
#

Obviously not, in my sitation they are going to be animated, they are harvestable as of right now, they also contain a script for item drops

viral silo
#

Hello, wanted to code a simple debug tool for controller input so I decided to use Unity's UI Graphic Class as I found it easiest to do simple task of just rendering lines on just UI itself, it displays all and well except for the fact I can't call AddTriangle for the lines separately in same OnPopulateMesh function without having to connect them (I want them to be separate), might use separate class for this but prefer to be in same one.

Main Issue I've been encountering is UpdateGeometry in FixedUpdate causes too much lag for the entire game loop. Am I supposed to be using SetAllDirty and if so, where should I call it from? Same function that draws the vertices? Update? Or OnPopulateMesh? The documentation does not leave information on what SetAllDirty nor it's similar functions exactly do.

protected override void OnPopulateMesh(VertexHelper vh) {
    vh.Clear();

    leftRectWidth = _leftPanel.sizeDelta.x;
    leftRectHeight = _leftPanel.sizeDelta.y;

    // Draw the vertices for each point
    for (int i = 0; i < pointsX.Count; i++) {
        Vector2 point = pointsX[i];
        float angle = 0f;
        Color vertexColor = xColor;
        DrawVertices(point, vh, angle, vertexColor);
    }

    for (int i = 0; i < pointsY.Count; i++) {
        Vector2 point = pointsY[i];
        float angle = 90f;
        Color vertexColor = yColor;
        DrawVertices(point, vh, angle, vertexColor);
    }

    // Draw a line between the vertices
    for (int i = 0; i < pointsX.Count - 1; i++) {
        int index = i * 2;
        vh.AddTriangle(index, index + 1, index + 3);
        vh.AddTriangle(index + 3, index + 2, index);
    }

    for (int j = 0; j <  pointsY.Count - 1; j++)
    {
        int index = j * 2;
        vh.AddTriangle(index, index + 1, index + 3);
        vh.AddTriangle(index + 3, index + 2, index);
    }
}
latent latch
#

Have you tried just calling it once? Does it need to be constantly updated?

#

Usually UI stuff only needs to be rebuilt when there's a change

viral silo
#

So, I've replaced UpdateGeometry with SetVerticesDirty and does the same thing without causing as huge performance loss so there's that, so all that's missing is separating the lines, if I try to put them together in single for loop, it draws a line between last X points and first Y point.

latent latch
#

Yeah was going to suggest that

errant pivot
#

Quick question, is there any better way to store values into a 2d array than just writing the 60-ish lines of code to set each value individually, since 2d arrays arent available in the inspector like 1d arrays are

midnight hollow
lean sail
# midnight hollow

!code and you should actually describe what problems you're having instead of just pasting code and hoping people know what you want

tawny elkBOT
naive swallow
# midnight hollow

You're attempting to call Initialization in the base class but the base class is MonoBehaviour and that doesn't have that function

lean sail
#

That first one, you also likely dont want new on a method declaration

midnight hollow
#

i built a new code

midnight hollow
#

and someone knows the "Flip()" error?

naive swallow
midnight hollow
# naive swallow What is `Flip()`
    {
        if (isFacingLeft)
        {
            transform.localScale = facingLeft;
        }
        if (!isFacingLeft)
        {
            transform.localScale = new Vector2(-transform.localScale.x, transform.localScale.y);
        }
    }```
#

ohhh i know

#

its bc its protected

naive swallow
midnight hollow
#

should i put in the same script?

naive swallow
#

So in the script you're trying to call Flip() from, there is no such thing as Flip()

lean sail
#

I almost feel like this would be AI code if you are using new and protected in your method declarations without even understanding what they are

#

And a base class

midnight hollow
#

ye no one used protected

naive swallow
midnight hollow
#

exactly

naive swallow
#

So they didn't use AI for this one. Presumably it's a bunch of IDE auto-corrects

visual fjord
#

The player can have the collider (Hurtbox) in gameobject child? And if so, how can detect the collider?

#

And the tag is object "Player"

lean sail
#

Although protected would still let you access from derived

midnight hollow
#

i learned the protected at school since then i forgot the use of it hahahaha

#

i inserted the flip() inside the same script now i just have the monobehaviour error with the initialization() function

#

should i do like instead of "public class PlayerMovement : MonoBehaviour" should i put "public class PlayerMovement : Character"?

naive swallow
midnight hollow
#

yes

naive swallow
#

Then you should probably make it one

midnight hollow
#

then put "public class PlayerMovement : Character"?

naive swallow
#

Yes

midnight hollow
#

thanks bro i still hav a question

#

what and how am i suposed to put a variable not null here: if (horizontalInput > 0 && character.isFacingLeft)

naive swallow
#

Assign a value to character

#

Before running this line

midnight hollow
#

i declared character like this
protected Character character;

naive swallow
#

And where did you assign a value to it

midnight hollow
#

isnt ``` character = GetComponent<Character>();````assigning a value?

naive swallow
#

Does that run before you attempt to check character.isFacingLeft?

#

Does it run at all?

midnight hollow
#

can i send a video here?

naive swallow
#

Yes, if it fits

midnight hollow
#

nevermind bro i just replaced the Initialization() to Awake() in every occurence and then its working

dense estuary
#

I fixed it by using rb.MovePosition instead of setting transform.position

mossy minnow
#

hey yall, im making a photography game, and im able to save the render texture to a file, basically im also using that render texture in a scope shader for the viewfinder. but as you can see the entire render texture is way larger than what im able to see out of the viewfinder. is there a way to crop the output of this image?

#
 public IEnumerator TakeScreenShot()
 {
     yield return new WaitForEndOfFrame();

     Camera camOV = filmCameraLens;
     RenderTexture currentRT = RenderTexture.active;
     RenderTexture.active = camOV.targetTexture;
     camOV.Render();
     Texture2D imageOverview = new Texture2D(camOV.targetTexture.width, camOV.targetTexture.height, TextureFormat.RGB24, false);
     imageOverview.ReadPixels(new Rect(0, 0, camOV.targetTexture.width, camOV.targetTexture.height), 0, 0);


     imageOverview.Apply();
     RenderTexture.active = currentRT;

     // Encode texture into PNG
     byte[] bytes = imageOverview.EncodeToPNG();

     // save in memory
     string filename = fileName(Convert.ToInt32(imageOverview.width), Convert.ToInt32(imageOverview.height));
     path = Application.persistentDataPath + "/Snapshots/" + filename;
     System.IO.File.WriteAllBytes(path, bytes);
     Debug.Log("Click");
 }```
heres my code for the photo
latent latch
#

I'd just change the UVs/material settings instead of fooling with the texture itself

mossy minnow
#

cant rly do that, this shader works in mysterious ways

#

the image is projected a super far distance away so unless youre literally right next to the eyepiece you wont be able to see all of the texture

#

also the render texture needs to be square for it to work, and i dont want square images for the camera

untold stirrup
#

Hi, I'm working on an Android app, I want to build it but I get this error and it seems like there's something duplicated but I don't know what I should delete, I'm using admob and google signin with firebase

steady bobcat
#

its either included as a file and or declared as a gradle dependency (preferred)

untold stirrup
#

So I don't know why it says there is a duplicate

steady bobcat
# untold stirrup Yes, but I only find one with the .aar extension

what thing included this file?
Normally plugins now do NOT include libs like this but declare dependencies for external dep manager to setup via gradle
check your Assets/Plugins/Android/mainTemplate.gradle file to see them all listed. (force android resolve first)

untold stirrup
steady bobcat
#

the implementation blah line should have a comment pointing to these so these should be kept.. but how are there 2 of some 🤔

untold stirrup
steady bobcat
#

Hmm should only be one version then But the error states the same aar was included again 🤔

quiet axle
#

!vscode

tawny elkBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

forest vigil
#

Is there a way to make my button, after it is clicked & deactivated, return to its original color when i bring it back? It changes color on hover

uncut seal
#

Hi. I'm trying to recreate the portals from Valve's "Portal". The player should be able to stand with a part of their body in the portal without teleporting through it. To recreate this, I thought of removing the triangles from the meshcollider of the surface that the portal is placed on to allow the player to pass through this part of the surface, but I have been repeatedly unsuccessful in making it work. Could you help with this?

#

Here is my current code:

void CreatePassableArea(Collider wallCollider, Vector3 position, Transform portalTransform)
    {
        MeshCollider meshCollider = wallCollider as MeshCollider;
        if (meshCollider == null) return;

        // Create a new mesh instance to modify
        Mesh originalMesh = meshCollider.sharedMesh;
        Mesh modifiedMesh = Instantiate(originalMesh);
        
        // Calculate portal bounds in the wall's local space
        Vector3 localPosition = wallCollider.transform.InverseTransformPoint(position);
        Vector3 localSize = wallCollider.transform.InverseTransformVector(portalTransform.lossyScale);
        
        // Create bounds with small depth (adjust as needed)
        Bounds portalBounds = new Bounds(localPosition, new Vector3(localSize.x, localSize.y, 0.1f));

        // Process triangles
        List<int> newTriangles = new List<int>();
        Vector3[] vertices = modifiedMesh.vertices;
        int[] triangles = modifiedMesh.triangles;

        for (int i = 0; i < triangles.Length; i += 3)
        {
            Vector3 v1 = vertices[triangles[i]];
            Vector3 v2 = vertices[triangles[i+1]];
            Vector3 v3 = vertices[triangles[i+2]];

            // Check if triangle center is within bounds (more reliable than all vertices)
            Vector3 triCenter = (v1 + v2 + v3) / 3f;
            if (portalBounds.Contains(triCenter))
            {
                continue;
            }

            newTriangles.Add(triangles[i]);
            newTriangles.Add(triangles[i+1]);
            newTriangles.Add(triangles[i+2]);
        }

        // Apply changes
        modifiedMesh.triangles = newTriangles.ToArray();
        modifiedMesh.RecalculateNormals();
        modifiedMesh.RecalculateBounds();

        // Assign the modified mesh
        meshCollider.sharedMesh = modifiedMesh;
    }
late lion
#

Though if the player is not using collision events and is instead a character controller using physics queries, you'll need to do something similar in that code too.

shadow wagon
# forest vigil Dumb it down for me boss

if something needs to happen when you click, the interface for that is

IPointerClickHandler
Interface to implement if you wish to receive OnPointerClick callbacks.```
the description provided with each one, is self explanatory
#
using UnityEngine;
using UnityEngine.EventSystems;

public class Example : MonoBehaviour, IPointerClickHandler
{
    //Detect if a click occurs
    public void OnPointerClick(PointerEventData pointerEventData)
    {
        //Output to console the clicked GameObject's name and the following message. You can replace this with your own actions for when clicking the GameObject.
        Debug.Log(name + " Game Object Clicked!");
    }
}```
#

adding the IPointerClickHandler interface to your class, gives you access to the OnPointerClick method

#

which gives you the function of detecting a click

#

look through all those interfaces, pick out the ones that apply to your use case, which sounds like clicking, deselection, hovering, and that should give you what you need

steady bobcat
latent latch
#

My idea would be to just ignore the collider completely if I'm somewhat touching the portal

#

otherwise voxelize all the surfaces and chip away at that

iron spade
#

Hello, I am doing a deckBuilder with the UIToolkit. Is it possible to disable the scroll of the ScrollView when I want ? Because when I drag a VisualElement it also scrolls the scrollView. thx

leaden yoke
#

I have a problem, I'm still confused on how to make the player look left and right so I added this camHolder.rotation = Quaternion.Euler(0, newRotation.eulerAngles.y, 0); and it works but it stutters alot as you can see. The rigid body interpolate is on, the camera is not a child of the player that has the rigidbody and the camera is a child of CamHolder. Any ideas on how to fix/do it properly?

lean sail
leaden yoke
rigid island
#

camera rotation should probably be in lateupdate or fixed

lean sail
#

it doesnt look like the issue is looking up and down even. it looks like when you're moving it stutters

lean sail
# leaden yoke this is on the cam holder

not sure if im just blind but your video shows the camera is looking left or right with the player. the code youve shown doesnt do that. the camera rotation code being in update doesnt help also.
have you confirmed that its stuttering when you look around because it really looks like its more when you move. do you have interpolate on your rigidbody?

#

you should really just use cinemachine

leaden yoke
hexed pecan
#

@leaden yoke I agree with bawsi that nothing you have shown would rotate the camera left/right, unless it is a child of the rigidbody

lean sail
hexed pecan
#

Double triple check that you don't have any extra scripts affecting the rotation

leaden yoke
hexed pecan
#

Do you still have some cinemachine component active?

#

Show the inspector of the camera, cam holder, and the player

lean sail
#

ah it was the line they removed, that they showed in the initial message that rotated left or right

hexed pecan
#

Oh i see

hexed pecan
#

I wonder if the cameraPosition.position is not actually interpolated even though it is a child of the rigidbody

#

I doubt it, but that would make sense regarding this issue

leaden yoke
hexed pecan
# leaden yoke this is on the cam holder

For testing purposes, try replacing the line in lateupdate with something like cs transform.position = cameraPosition.parent.position + new Vector3(0, 1.7f, 0);

hexed pecan
#

Include your previous camera rotation code that you removed. Do it in lateupdate, not update though.

#

Move around, look around and see if the same issue from the previous video still exists

leaden yoke
hexed pecan
#

Yes, that

forest trout
#

Someone with experience let me know if this is okay to do or if there is a better way to do it. My idea is having a game with different levels, when you complete the level you are in, you are teleported to the next level, and the level you were is deactivated. The problem I see with this is, I would have to have the amount of if statements of the amount of levels I have in the game and I am checking if the condition is met for each one and then I have to teleport the player to each cordinated of the next level. Hope it makes sense.

leaden yoke
hexed pecan
#

You made it work in Update before, so surely you can make it work in LateUpdate now

lean sail
naive swallow
hexed pecan
#

No

lean sail
#

if you arent familiar with c# basics, please just use cinemachine lol

hexed pecan
#

At this point yeah

leaden yoke
lean sail
#

in cinemachine there are a ton of options u can change in inspector

leaden yoke
#

wtf I didn't even realise I was in code - general lol

lean sail
#

it depends on the camera you use, but there should be a dropdown somewhere about when the camera should update

leaden yoke
#

would I do anything script wise?

lean sail
#

probably not but you'd likely have to move that rb rotation code to the player, which it should be anyways. Im not too familiar with the first person cinemachine cameras but they really arent that hard to play around with

leaden yoke
lean sail
#

if you set it up correctly

#

a ton of people use cinemachine, its not like everyone is putting up with stuttering.

leaden yoke
#

OH SHIT. THERES NO STUTTER WHEN WALKING/LOOKING AROUND

unkempt zenith
#

What in the world is an invalid scene

#

I just want to check for null :(

unkempt zenith
#

Most normal Unity way to handle something basic like existance :D

hexed pecan
unkempt zenith
#

Least confusing Unity abstraction

#

But cheers

leaden ice
# unkempt zenith What in the world is an invalid scene

If you ask for a scene that doesn't exist or isn't loaded you just get a default Scene struct which will not be valid, and yeah since it's a struct it can't be null.

Really what they should have done is used the TryGet pattern like Dictionary.TryGetValue etc.

toxic stag
#

how do ppl to collaborate in unity if the cloud storage is only 5go?

dense pasture
#

is there not a double precision waitforseconds ?

#

for audio timing in a coroutine? or is it just not possible with frame timing

#

meh

somber nacelle
#

no matter what you will still be subject to deltaTime when using WaitForSeconds, it makes no sense at all to have an overload that accepts a double for that

dense pasture
#

mmk

soft shard
dense pasture
#

i'm just being anal about fractions of a second forget it

#

its good enough

soft shard
#

Ah, I see

dense pasture
#

trying to align action to the drop

leaden ice
#

if you do WaitForSeconds(1) it will never happen at exactly 1 second

dense pasture
#

how about a hack for the fact timeSamples resets to 0 after a clip loops?

#

without having to bounce it back and forth between two audio sources (already doing that, but i'm using it to queue the next chunk of the track)

#

or is that the easiest hack

lean sail
dense pasture
#

Audio sources. When you play a clip you can get the precise elapsed time of the clip based on timesamples / frequency

#

However if it loops back to start that value stays at 0

#

The hack I know of is to juggle clips between two audio sources but if there’s a way to get the accurate value another way I’d prefer that since I’d have to rewrite a bunch of stuff to juggle a loop of the same clip

#

For musical timing basically

#

The resetting to 0 seems to be a bug

lean sail
#

i havent messed with that enough to know if thats actually a bug, where it stays at 0. timesamples being the current playback position would make sense if it were 0 when the clip restarts.
If you just want the elapsed time, could you not just have your own timer and add deltaTime? it seems your timer is longer than the audio clip anyways

dense pasture
#

Audio time is super super finnicky though might not line up perfect

#

Thing with timesamples is it’s the audio source most accurate indicator of elapsed time in the clip and it’s an integer

#

Idk shit let’s try it

naive swallow
#

Is there any sort of built-in functionality for creating a rendered polygon given a bunch of vertices, or do I need to create a custom mesh using some sort of triangulator algorithm? Trying to make one of those filled in stat bubble thingies

young yacht
#
void MoveAim()
    {
        if (playerController.targetedEnemies.Count > 0)
        {
            Transform targetedEnemy = playerController.targetedEnemies[0].transform;

            var constraintData = headAim.data; // Store current data

            constraintData.sourceObjects.Clear();
            constraintData.sourceObjects.Add(new WeightedTransform(targetedEnemy, 1f));

            headAim.data = constraintData; // Reassign modified data

            rig.weight = 1f;

            headAim.data.sourceObjects.Add(new WeightedTransform(targetedEnemy, 1f));
            rigBuilder.Build();
        } else 
        {
            if (!isBuilt)
            {
                var constraintData = headAim.data;
                constraintData.sourceObjects.Clear();
                headAim.data = constraintData;
                
                headAim.weight = 0f;
                rig.weight = 0f;
                rigBuilder.Build();

                isBuilt = true;
            }
        }
    }
#

could anyone help here

#

im using multi aim constraint from animation rigging

#

but the target isnt updating

soft shard
# naive swallow Is there any sort of built-in functionality for creating a rendered polygon give...

I believe that "stat bubble thingy" in math is called a "radar chart" or "radar graph" (there may be some tutorials on that specific approach), im not a expert with mesh generation but I believe youd have to create a new Mesh from a vertices array, AFAIK, TextMeshPro works in a similar way for generating the letters, alternatively, maybe you could use a shader to draw the vertices array, though im not sure if there would be a technical name for that kind of shader (maybe compute? Vertex displacement?)

naive swallow
#

One of these things ought to work

lyric gate
#

can someone help me for my homework. i am genuinely so confused

quartz folio
#

Nobody will help if you don't have a question, you have to have shown you have tried

lyric gate
#

i have tried lol

#

im not familiar with c#

#

in only know python

naive swallow
lyric gate
shadow wagon
#

I'd also say its probably a good idea to speak to your teacher about the assignment, if youre struggling with it, I'm sure they can give some better guidance

lyric gate
#

i did lol they havent responded in like 16hrs

naive swallow
tawny elkBOT
shadow wagon
lyric gate
#

its online

shadow wagon
#

ah

lyric gate
#

i did unity last semester but i never did the code, i just focused on other stuff

shadow wagon
#

C# does things like that, a little different to python, so it's an easy mistake

#

if your course has any teaching material for C#, it couldnt hurt to go over that again

naive swallow
#

And also configure your IDE

shadow wagon
#

!ide

tawny elkBOT
subtle herald
#

A properly configured compiler will always catch little things like this thumbsUp

shadow wagon
#

oops, didnt spot the command used earlier 😆

sacred python
#

hi guys
can i use a shader in the script and get its result as a texture?

#

probably is possible, but how do i manage to do that?

karmic stone
#

Hello! I'm currently trying to create a building system, where my builds are decoupled from the player controller. Is it alright to run event.invoke every frame in a update, or should i just return the transform of the build object to a variable in the player class and edit that.

#

tried searching up performance impact of event.invoke and im getting nothing real good

rigid island
#

MB.Invoke isn't good

karmic stone
#

Action<Vector3> delegate { }

#

i think thats regular csharp events

rigid island
#

Yeah you should be fine invoking every frame, its normal to do so

karmic stone
#

thank you for the help nav. is it same performance as if i was to do class.method(vector3) every frame?

rigid island
#

micro-optimising 😉

cosmic rain
rigid island
#

doesn't it all become the same in IL ?

karmic stone
#

i just wanted to know it wasnt like a lag machine during runtime.

cosmic rain
#

Should probably not worry about it.
If you need to optimize something, use the profiler

rigid island
#

anyway the difference are so small you shouldn't worry it

karmic stone
#

thank you guys.

subtle herald
#

Also, worry about optimization way later. After everything works

shadow wagon
subtle herald
#

You'll most likely want a RenderTexture here

sacred python
#

ok but how i apply the shader on the render texture?

shadow wagon
#

Write the render texture to a compute shader, write code in shader which writes color onto the texture

#

The output render texture can be used like any image texture like any regular texture

sacred python
#

oh ok

#

thanks

#

but how about graphics.blit?

shadow wagon
#

that allows you to copy data from one texture and write it onto another

subtle herald
#

Blit() is used for fullscreen effects mainly

#

You wouldn't really need it here

#

If I'm understanding what you want to do correctly

shadow wagon
#

I used it to write images onto a render texture so they can be used in a shader

#

And you also use it to copy from one rtex to another rtex

subtle herald
#

Yeah, but tbh I'm not sure what they want to do anyways lol

#

They haven't described their end-goal

#

And I said "mainly" based on what I've seen others do. Not on what you've done lol So in my experience, I'm not wrong

shadow wagon
#

Ive seen blit used in a number of situations

subtle herald
#

So have I, mainly for full screen effects lol

#

Hence my statement

shadow wagon
#

I only gave those examples as they were the first that came to mind

#

You said mainly, implying the main usage is that

subtle herald
#

But yeah, it's the fastest way of copying pixel data

shadow wagon
#

it is

grand cedar
#

Failed to resolve project template: Failed to decompress [C:\Users\ABC\AppData\Roaming UnityHub Templates\com.unity.template.urp-blank-17.0.9.tgz].
😫
i can't do this

subtle herald
#

Again, I said "mainly" as it relates to my experience. Not my fault if you assumed but alright then 😄 Have a good day folks

grand cedar
#

@subtle herald

subtle herald
#

The hell? Idk lol

#

Don't just start pinging random people

#

If someone is online who can help then they will, just relax and wait

grand cedar
subtle herald
#

Try Google, plenty of stuff comes up if you copy and paste your exact question lmao

grand cedar
subtle herald
#

What? No....... that's not at all what I said nor suggested.

#

I'm asking you if you tried searching for a solution to your problem with Google?

subtle herald
#

Oh... nice. Yeah, this is where my assistance ends. lmao

grand cedar
#

But it's also useless.

#

@subtle herald look

subtle herald
#

Dude stop pinging me. If you're just going to default to AI and not listen to what I say then I'm not going to help you.

subtle herald
#

Alright, that's an easy block.

grand cedar
#

No one here helps

#

hmm it's okay 🍃

craggy pivot
#

Is there a way to find if a point is within a Mesh/MeshCollider?

leaden ice
#

(works for any type of 3D Collider)

elder gust
#

for basic multiplayer procedural maps (similar to like lethal company or something) should I have them all in one scene and just delete the old map and generate a new one if I want to go to a new map? or should I have them all in separate scenes?

night harness
#

lethal's moons are not really procedural

night harness
elder gust
night harness
#

ye

#

Unless your interior isn't dependent on living alongside the "moon" i would personally suggest the way lc does it

#

otherwise you may want to additively load both the moon and interior as seperate scenes

mossy minnow
#

hey guys, my game is running super bad, and i thing its to do with vsync but i have it turned off on all graphics settings

#

like theres no vsync but it still takes so much processing power, whats causing this?

#

this is a profiler attached to a build, btw

#

and ultra is the graphics setting for the build

grave bloom
#

based on unity document, object pool's collection check performs only in editor

#

but to be frank im not seeing any UNITY_EDITOR symbol around this checking

#

so how is unity going to disable the colelction check in build ?

cosmic rain
grave bloom
#

/// <param name="collectionCheck">Collection checks are performed when an instance is returned back to the pool. An exception will be thrown if the instance is already in the pool. Collection checks are only performed in the Editor.</param>

#

this is really frustrating... i dont see where this collection check has been disabled in Player Build

mossy minnow
#

not much i can do about that apart from turn the iterations down, ty though

cosmic rain
#

Or seeing the profiler data.

cosmic rain
cosmic rain
# grave bloom

Ah, actually, m_CollectionCheck sounds like a relevant flag. It could be false outside the editor.

#

And that could be toggled off from anywhere. Maybe even C++ side.

mossy minnow
#

its defo the kuwahara filter

#

keep in mind this performance is v exaggerated because i have the profiler attached, its around 60fps normally but it probably should be higher than that

cosmic rain
#

It seems to be running 22 times per frame too. Is that expected?

mossy minnow
#

ah no definitely not

#

its meant to run once per frame

#

ill have a look at it a bit more closely 😅

#

or, twice i guess because its running on the main camera and the camera object (im making a photography game)

errant smelt
#

Hi

dense estuary
#

How could I make instances of the same scriptable object have different values? The inventory system for my game is set up like a tree, the base is ScriptableObject, then ItemSpec, then (type)Spec's (like upgradeSpec or consumableSpec). In my game each item is worth calories, so you can keep a creature satiated, but I don't know how to make it to where different instances of the same item have different calories.

#

the classes like UpgradeSpec derive from ItemSpec

lean sail
#

if you created 2 upgradeSpec or consumableSpec, you can already assign them different values for calories

dense estuary
#

These are instances

#

My issue is, I want it so when one of these items is spawned in, it is given a set calories between a min and a max, and it keeps that set amount until it is fed to the creature.

lean sail
#

when you spawn the object, (i assume InWorldItem), it should read or be passed the values of your SO. youve already assigned a variable speed increase. if you look at other instances of your SO, they aren't the same value

#

this is just your data container, you dont spawn a SO into your scene. you use it to pass data to whatever needs it

dense estuary
#

Right, sorry, I have the data stored in the InWorldItem (the ItemPickup script on the InWorldItem).

#

There will be multiple instances of these instances in the scene

#

And I need a way to make each of those items have their own random amount of calories between a min and max.

dense estuary
#

Two of the same ItemSpec, in the scene.

#

If I were to store the min and max on the itemSpec, I would need to find the amount and store it in the ItemPickup script, but then that brings the issue of storing the chosen amount in the item.

lean sail
dense estuary
lean sail
#

just so i can write an example

fading epoch
#

https://paste.ofcode.org/drYhwXg9vuWSGz74dWJ9e
I'm trying to make throwing objects a possibility with tutorials but I'm missing something fundamental in the understanding of what I am looking at in Google so, I 'd love some help here!

lean sail
# fading epoch https://paste.ofcode.org/drYhwXg9vuWSGz74dWJ9e I'm trying to make throwing objec...

you'd have to say what you specifically struggle with here, although this code really is a mess. all these get components and controlling what happens to other objects is extremely fragile and hard to debug. a component on your object should have control of these things and should be called through a method. this would move logic to your "pickable" objects but also remove the need for using tags to determine logic

fading epoch
dense estuary
lean sail
# fading epoch The commented bit at the bottom is how I was attempting to have things thrown bu...

truthfully id scrap all the code there and remake that logic. setting the collider and rb info should happen purely from the object thats being picked up. You could use a base class to handle this for every object that can be picked up, then derive from that class when objects need more functionality.
I don't really know what the goal is here though so it's hard to suggest much more. you should almost never have this structure of

                    cubeItemHeld = false;
                    sphereItemHeld = true;
                    nothingHeld = false;
                    sphereBool = true;
fading epoch
lean sail
#

I would move the spawning logic to the SO, but either way something like this in ItemSpec

    
    public virtual void Spawn(Vector3 position, Quaternion rotation)
    {
        ItemPickup instance = Instantiate(inWorldItem, position, rotation);
                instance.SomeMethodToAssignValues(calories, isBig, etc);
    }

and at the same time u can generate that random value

dense estuary
#

Oh, alright.

#

Then the inworld items have different calories, but I'm not sure how I can make sure those different values stay with the item when the player picks them up.

lean sail
# fading epoch Yeah, that's very much me being a beginner as I try to finish a thing for a remo...

if you want something a bit more flexible and this being a tutorial you said, you could hold a reference to each specific object in the tutorial scene and then compare that. Depends though if the object with this code is in scene too, since prefabs cant reference scene objects
[SerializeField] SomeComponent myCube;
then when you GetComponent<SomeComponent >() you compare if its the cube. at least this moves you away from tags.
Then just take into account what i said about having a component on the cube itself set the rb.isKinematic and collider.enabled

lean sail
dense estuary
dense estuary
lean sail
dense estuary
#

If its passed to the spawned object, would I need to make a separate list for the calories? This is my Inventory script: https://hastebin.com/share/imafotokoz.csharp

dense estuary
lean sail
#

i suggest you try this and just see how it works. you quite literally just pass it a value through a method when its spawned

dense estuary
#

I know I can store the calories in the ItemPickup, but my inventory script stores the items the player is holding like this:

#

How does the Inventory script know how many calories the item is worth?

lean sail
#

it doesnt make sense for the inventory to store a list of SO. this is just your data container
you should probably make a new class containing only the info you want stored

#

and then ItemSpec can also create this new class passing it to ItemPickup

#

the alternative to this would be making unique instances of your SO at runtime using instantiate which honestly is much worse in my opinion. because you also need to manually destroy them

#

then you need to look into when to actually destroy them which is not a fun thing to solve

dense estuary
lean sail
#

yea, itd also remove repeated variables from ItemSpec and ItemPickup so i end up doing this anyways a lot of the time

dense estuary
#

Would it be bad for this base class to also hold a reference to the ItemSpec its spawned from?

lean sail
#

the parameters become a lot simpler, and in ItemPickup its just also holding its own reference to ItemData

    public ItemData itemData; 
    public virtual void Spawn(Vector3 position, Quaternion rotation)
    {
        ItemPickup instance = Instantiate(inWorldItem, position, rotation);
        instance.SomeMethodToAssignValues(itemData);
    }
lean sail
#

just a difference of reading the values vs being told the values

dense estuary
#

Because, the Items Use functionality is stored in the itemSpecs, so I would need to keep a reference to the ItemSpec.

#

The Use functionality is actually stored in the classes that derive from itemspec

lean sail
#

you might want to be careful with that, since item spec is an SO. if your methods ever need to know state then you'd be modifying data on an SO

dense estuary
#

I just modify the data of the player class using the data on the itemSpecs.

lean sail
#

idk what you use the method for, but just an example, you'd have no current way to code "on the 3rd use, this item gives the user +5 health!". because you cant store how many times it was used on the SO, or every single item would be reading the same value

#

if you never need to store data like that then its fine

#

you'd have to store it somewhere other than the SO, and possibly pass it to the SO as a parameterif needed

dense estuary
#

Parameter as in the get set thing for a variable?

lean sail
#

you pass it a value

dense estuary
#

The radars scan speed is stored in the player script, so when I use a speed upgrade, it multiplies the speed stored in the player class.

vestal arch
night harness
#

(to be pedantic, isn't that passing a value via an argument?)

vestal arch
lean sail
#

i wasnt specifically referring to the variable declared, i quite literally meant it like "you give the script a value"