#archived-code-general

1 messages Β· Page 395 of 1

heady iris
#

I know that Unity likes to abuse the word "script", though

young yacht
#

hello, i made a sprite with 1128x1700, imported it to unity and it looks super blurry, i tried changing the PPU but still looks blurry asf. i also always set to native size, but still blurry, could anyone help me here?

rigid island
young yacht
#

my bad

lyric verge
#

Guys, how can I make an Inventory system, I use a grid layer group and I want the UI to extend/shrink whenever I add or remove slots from it or when the slots get added or removed, how can I approach that?

heady iris
#

A GridLayoutGroup will request enough space to show all of its elements.

#

Its parent will need to give it enough space, of course

lyric verge
#

but I want it, to increase UI size/decrease it... like adding rows/coloums with a bagpack

heady iris
#

You should have either:

  • A layout group
  • A layout group and a content size fitter

on every element with variably-sized children. Content size fitters should be used if your parent doesn't have a layout group.

heady iris
lyric verge
#

what is a content size fitter?

lyric verge
#

so I have to attach this component on my UI?

heady iris
#

You should read through the "Basic Layout" and "Auto Layout" sections of the UI docs

little meadow
#

Unity's UI stuff... 😩 it works, but it's so unintuitive at times...

heady iris
#

It's actually very straightforward if you just respect the layout system

lyric verge
#

thxx

little meadow
#

it doesn't even respect itself, Fen! πŸ˜„

heady iris
#

The problem is that all of the default UI objets do not play nice with auto layout

#

At all

rigid island
little meadow
#

πŸ˜‚

heady iris
#

Every single UI object collapses into a tiny blip if you add a layout group that controls child size

#

This causes people to do Evil Stuff

#

like just leaving Force Expand enabled on everything

#

or inserting random Content Size Fitters in places they don't belong

#

It's really quite simple. Children tell their parent layout groups how much space they want, then space gets allocated

#

Everything gets its min size, then preferred sizes are met, and then anything extra goes into flexible size

heady iris
little meadow
#

That is true, but it doesn't make it any less annoying πŸ€·β€β™‚οΈ And then all of these need to be configured in a specific way to get the results that you want, there isn't a layout group that's just "get child size" or is there? You can't easily add paddings and margins to all, so you need to stack MORE layout groups for simple things. And then you set it all up, but it doesn't update properly unless you tell it "ForceUpdateNAO!"

#

So, yeah, it works, I've been able to achieve what I need... but it's been way more tedious than say XAML (WPF's UI thing)

#

Or basically any other UI framework, really... except IMGUI πŸ˜‚

heady iris
#

That's why the layout groups have margin and padding settings

#

The vertical and horizontal layout groups both work fine if you just have one child

little meadow
#

they have only padding, no? or are margins some new thing in latest Unity?

heady iris
#

I guess it doesn't have an exact equivalent to CSS with its separate margin and padding around each object

#

to be honest i've never thought "i wish i had fifteen incompatible kinds of padding"

little meadow
#

it works, but it's tedious, that's what I'm saying πŸ™‚

heady iris
#

well, yeah, the default behavior is nothing, because that's how Unity generally works!

#

if you have a game object with no components on it, it shouldn't do anything

heady iris
little meadow
heady iris
#

If parent A cares about child size, then the child needs to report the correct size

little meadow
heady iris
#

Without any other context, the child will say it needs no space

#

Because it doesn't need any.

little meadow
heady iris
#

now we're getting into Spooky Action At A Distance, where every UI element has to traverse all of its children (recursively) to figure out how much space it needs

little meadow
#

in any case... we can agree to disagree πŸ™‚ I just find some other UI systems I've used to be much more convenient and elegant πŸ€·β€β™‚οΈ

heady iris
#

There are plenty of situations where you ask for less space than your child needs. An obvious one is a scroll view.

little meadow
#

I'm not saying one shouldn't be able to control this behaviour πŸ™‚ I'm saying that perhaps some defaults or slightly different approach can make it much more elegant... because as it stands, almost everyone I've seen had problems with it

heady iris
#

I used to have tons of UI problems. Now I don't.

#

I used to put content size fitters where they don't belong and leave force-expand enabled all over the place

#

The defaults are really bad

#

That is the core problem with the UI system, IMO

#

(in fact, literally every checkbox on a vertical layout group is wrong by default)

little meadow
#

See? You have to fight the system every time! It works, after a fight, if you're a skilled fighter! That's not what I want from tools that I use reasonably often!

#

(I won't even mention how many years it took them to rename "Child Control Size" to "Control Child Size")

chilly surge
#

The biggest issue I have with UGUI is performance related (and from what I've heard runtime UI Toolkit is somehow worse). If I don't like how layout works I could at least have my own abstraction on top of UGUI, but performance isn't really something I could easily fix myself.

little meadow
#

That is a fair point

heady iris
little meadow
#

Random question: is UI Toolkit for editor more performant than IMGUI? (Yeah, yeah, not the right channel, but I'm only looking for a quick yes/no/sometimes)

heady iris
#

I haven't profiled it.

I do know that you're not allowed to use automatic IMGUI layout in property drawers for performance reasons

#

so maybe that's a hint πŸ˜›

cold parrot
little meadow
cold parrot
cold parrot
night storm
night storm
cold parrot
#

the rest of the game, workflow and how it actually looks

night storm
#

huh, i didnt know it was that complicated

cold parrot
#

if you ask for whats better, you have to take everything into account, because the answer to that question always depends.

#

unless we know in detail how your project works a blanket recommendation could be right for 99% of situations but wrong in yours.

#

the simple answer is: the difference is likely irrelevant and there is no "better"

lyric verge
#

do I add the Layout element on the inventory slot or the UI?

night storm
lyric verge
#

and content size fitter to the ui?

heady iris
rigid island
#

PSA: so at Application.targetFramerate = 5
Update Physics function like, spherecast does not detect colliders well..

#

it just clicked that in FixedUpdate ofc now its sync and works fine..

rigid island
hexed pecan
#

Oh I read "i just clicked that" πŸ€¦β€β™‚οΈ

rigid island
#

Oh lol . I was just wondering its basically true

hexed pecan
#

Yeah colliders really only change their physical position each fixedupdate probably related to that

#

What positions are you using for the spherecast tho?

#

I'm just curious, might learn something here

rigid island
#

just transform.position , i'm using a CC though

#

the player doesn't move forward or back, just up down left right

#
 private void FixedUpdate()
    {
        if (hasHit)
        {
            if (resetting) return;
            StartCoroutine(ResetHit());
            return;
        }

        var hits = Physics.SphereCast(transform.position, cc.radius / 1.2f, Vector3.forward, out var hitInfo, distanceCheck);

        if (!hits) return;
        if (hitInfo.collider.TryGetComponent(out Shape shape))
        {
            //etc
        }
    }```
#

its old code but going to switch to nonalloc for a bit of extra perf

hexed pecan
#

Oh yeah your dir is always Vector3.forward thats why it wont work in update and with low framerate

#

Length is only 1 but you might move more than that per frame

rigid island
#

ahh..so thats framerate dependant ?

hexed pecan
#

Changing your FPS to 5 will still let fixedupdate run faster than 5FPS thats why it works

hexed pecan
#

Like if you move more than 1 unit per frame (physics frame)

rigid island
#

oh ok , so even if my char doesn't move forward/back it does this?

hexed pecan
#

Ohh wait yeah... lol

#

If it doesnt move in Z then forget about that

#

I still wanna internalize why it didnt work in update

#

Actually my point still stands

#

You aren't moving but the objects are moving towards you

rigid island
#

yeah I think its what you said, fixedupdate keeps consistent at low fps

#

update might be calling it slower than physics are moving ig

hexed pecan
#

This is what happens basically

#

Tunneling effect pretty much

#

In this example you look forward (yellow) only 1 unit when the world is moving ~2 units

#

So you miss the hit

rigid island
#

also I use physics to move the obstacles anyway with a rb

hexed pecan
#

It's easy to fix tho, you just scale your spherecast's distance with the speed

rigid island
#

the speed of which?

hexed pecan
#

The stuff moving towards you

#

If they ever move faster than your current max spherecast distance then theres a chance to miss it

rigid island
#

ah ok, its just 1 main object that has multiple colliders

hexed pecan
#

(I incorrectly assumed your spherecast length is 1)

rigid island
#

.55

hexed pecan
#

You could use something like Time.fixedDeltaTime * speed + maybe some extra 0.25

#

So you get the distance that you (the world) moved during one fixed step

rigid island
#

still misses in update

hexed pecan
#

Don't multiply with distancecheck
Oh also use Time.deltaTime insetad of fixed here

#

And is 45 the speed/velocity magnitude of the world (in units/second)?

#

Time.deltaTime * speed + 0.25f should do it

rigid island
hexed pecan
#

0.25 is optional I just think it gives better game feel

hexed pecan
rigid island
#

def got longer lol

#

might be hitting before my "head" hits

hexed pecan
#

I cant tell if its good or bad from the gif, is it too long?

#

Remove the 0.25 at least

#

Math should be correct though... Distance moved in one frame = deltaTime * speed

#

(You changed to deltatime instead of fixeddeltatime right?)

rigid island
#

yeah let me try without 0.25

#

gif is laggy and also its running at 5fps lol

#

but the "tile" was being hit before the head reached the spot

hexed pecan
#

Best way to test is probably to pause game and go frame by frame

#

See if the spherecast is the same length as the distance traveled

rigid island
#

thing is, if I do that it actually hit before

#

In Update without deltaTime. I think it gives enough time to catchup when I pause

hexed pecan
#

Ohh I think you just want to shift the spherecast back

#

So you don't look ahead, but instead look from last to current pos

rigid island
#

yeah I just want to basically simulate a "door" you run into with the correct shape

hexed pecan
#

@rigid island Try something like thiscs var distance = Time.deltaTime * speed; var origin = transform.position; origin.z -= distance; var hits = Physics.SphereCast(origin, cc.radius / 1.2f, Vector3.forward, out var hitInfo, distance);

#

Basically just moved the origin back so it casts "from previous to current pos"

#

Instead of "from current to next pos"

rigid island
#

it went behind now but it only hit 1 out 3

hexed pecan
#

Might need to add the sphere's radius to the distance too..

rigid island
#

are there any drawbacks to just keeping that function in FixedUpdate? seems thats the only one working well at low fps

hexed pecan
#

But yeah you wanna do it in fixedupdate anyway

hexed pecan
little meadow
#

why do you care about low fps again? πŸ˜„

rigid island
#

yeah just wanted to see what the worst case scenario is and noticed none of the tiles were hit, that'd be a big gameplay flaw

little meadow
#

eh, I guess it's fair... 5 is a bit extreme, but yeah, makes sense to make it work on various FPSes

rigid island
#

yeah like what if it dipped at somepoint not always 5 but just low enough and someone complains "HEY I missed my points"

hexed pecan
#

It could temporarily run at 5 FPS when say your antivirus starts scanning or something

hexed pecan
#

Just one dropped slow frame could be bad

rigid island
#

my general rule is , if it works on crappy specs I'm happy it works lol

little meadow
#

so, is it reasonably solved if you do it on FixedUpdate?

hexed pecan
#

Should be

rigid island
#

yeah thats why was curious if there is anything I'm not noticing since it seemed to fixed it

#

Iirc when i tried doing it in fixedupdate for something else it wasnt as good as Update

little meadow
#

you need to be mindful of the length, but in FixedUpdate it should be easy as it aligns with the physics

rigid island
#

yeah makes sense esp the main object moving those colliders is a RB so a physics function in fixedupdate makes sense for sync

little meadow
#

in Update it could be more weird, because transform.position may not be where rb.position is (because interpolation), and that may have some effect on the calculation... πŸ€”

#

should be consistently doable though, just more things one may need to take into consideration

rigid island
#

CC moves with Update code but ig its a kinematic physics object anyway

little meadow
#

yeah, I do those in update, but that's because I also move in Update

rigid island
heavy pulsar
#

What is a native plugin? I searched about whether we can use C++ on Unity and it said we can use native plugins to do it.

heavy pulsar
rigid island
#

nah not gonna happen

#

just use a C++ engine then

late lion
somber nacelle
# heavy pulsar By using C++ programming instead of C#

from the sound of it, you don't even have much (if any) experience with c++ so does it really matter all that much? Just learn c# instead or choose an engine you can use c++ in so you can better learn how that language works

heavy pulsar
rigid island
#

c# way easier to pickup

heavy pulsar
#

I am relatively new to game development

wheat spruce
#

If youre married to the idea of using C++, might be best to learn using Unreal Engine instead

rigid island
#

unless you need it for specific school or job, you're better off with c#

heavy pulsar
#

Before now the only game development I have been using has been Roblox Studio that is why I barely have experience in programming

rigid island
#

yeah c++ aint the way tbh

#

you're going to have more to learn a objectively harder language

heavy pulsar
#

Ok I will start with Unreal and start development with Unity later

rigid island
#

manually deal with memory management at your beginner level, going to learn twice the work just to make a game

spare dome
#

also a language that unity does not primarily use for programming

rigid island
languid hound
#

Would anyone mayhaps know why my camera jitters when walking and looking around

#

That's my entire camera controller right now aside from the GetMoveDirection method and the class definition. cameraPosition is parented to an interpolate rigidbody

#

I saw someone else had the same issue but my setup is coincidentially identical to their fix and yet I'm still getting insane jitter

stoic anvil
#

You can just write FPSUpdate();

languid hound
#

Saving myself like 3 lines of code for when I'm gonna have more camera modes lol...

stoic anvil
languid hound
#

Yeah

stoic anvil
#

Becuase if Validstate is false the compailer not gonna read anymore in youre code

languid hound
#

If there's no player to follow then I shouldn't really be trying to follow one

stoic anvil
#

Ok

rigid island
languid hound
#

ValidateSelf is just a singleton helper I wrote and it'll return false if the instance should be destroyed

rigid island
#

mistmatch between transform and physics

languid hound
#

Yeah I don't really know how to fix that though because I've had a near identical camera setup before and it worked fine

#

Minus the fact that the other one was in LateUpdate but I tried LateUpdate in this one too

languid hound
#

In previous projects sorry

rigid island
#

it all depends how the player moves

#

also i'd use cinemachine

languid hound
#

Yeah I'm probably gonna have to end up switching anyways :/

#

It'll benefit me long-term I suppose when it comes to other camera modes

#

I'll look into it soon then. Thank you

rigid island
#

plus cinemachine brain has some options so you can switch update modes and try to match it to your needs

stoic anvil
#

rotation.x = Mathf.Repeat(rotation.x, 360f);

#

Add this

#

And Check sensitivity and rotation values during runtime

#

Is Player.LocalPlayer and cameraPosition objects in scene?

simple egret
#

!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

sharp egret
simple egret
#

Can't answer, I'm not making the rules

sharp egret
#

breh i wont find any that way

simple egret
#

Not sure that asking randoms for DMs will be more successful tbh

languid hound
#

Ookay no luck even with cinemachine

languid hound
sharp egret
#

i used to do it when i was using roblox stufio

#

but didnt had any succses

simple egret
#

The rules are different here - create an account on the Forums, this server is not the place for job ads

rigid island
sharp egret
#

understanble

sharp egret
#

ima hop off

rigid island
#

using a website has more shelf life

sharp egret
#

yea but it feels lifeless idk how to explain

simple egret
#

It's probably has to do with the fact that this server isn't "official", it's not hosted by Unity themselves

sharp egret
#

aw

#

alr gn

#

spr2 are u intresed in that deal tho?

#

the game thing yk

simple egret
#

Nope, work drains all my time and motivation unfortunately

sharp egret
#

aw understandble if u ever change ur mind pls dm me im desperate

languid hound
#

Okay I found my issue

#

For some reason some completely irrelevant line where I was limiting the rotation of a SEPARATE object was causing the camera to lag

cosmic rain
opal juniper
#

guys i have a problem, everytime i try to make a rigidbody character controller, and start the scene, the player just goes up forever

#

even with the scripts disabled

#

anyone knows why?

heady iris
#

are you sure the camera isn't falling? (:

opal juniper
#

wdym

hexed pecan
opal juniper
#

yeah

hexed pecan
opal juniper
#

both components in one object(idk if its good that way)

hexed pecan
#

Second person today with the same issue :p

opal juniper
#

damn

#

so do i have to make a kinematic character controller?

#

like from scratch?

hexed pecan
#

If you want to use rigidbody then yeah, or use an existing asset/library

#

Writing one from scratch is possible ofc but there's so many issues you will need to fix/edge cases that you need to consider

opal juniper
#

oh

hexed pecan
#

If you do end up writing one, my main advice is that SphereCast is your friend

opal juniper
#

oh ok

lucid brook
#

Hi, I'm casting this Spherecast Physics.SphereCast(this.transform.position, sphereCastRadius, this.transform.forward, out frontWallHit, detectionLenght, wallLayer); and was wondering how I draw that with OnDrawGizmos() the times I have tried the WireSphere was never in the same place as the Spherecast

leaden ice
#

If WireSphere wasn't in the right place well.. you didn't put it in the right place.

lucid brook
leaden ice
#

there are at least three different places you might want to draw a sphere:

  • Where the cast starts
  • Where the sphere "hits" something
  • where the end point of the sphere would be if it doesn't hit anything
lucid brook
#

That's the bit I'm struggling with yeah. I'm trying to get it just at the third option. the second one would be nice but not necessary for what I'm doing.

leaden ice
#

That position would just be transform.position + (transform.forward * directionLenght) according to your spherecast above.

lucid brook
leaden ice
#

Something else is off if that's not working

#

Show your full script

lucid brook
#

nvm I may have made a mistake the first time I tried that because it work now lol.

leaden ice
#

The second one would be:
transform.position + (transform.forward * frontWallHit.distance) assuming the cast actually hit something

pure grove
#

hello, I have a problem. I made a child image on my button, top left anchored. Issue is when button goes to left, image goes to right side to the middle. At most right of the canvas it works properly what is the problem? I cant solve

halcyon swallow
#

i fell like asking here is better than the forums
are there any guides anywhere on how unity works under the hood?
my current theory is that every "gameobject" is a packet of code that contains "transform" at minimum, that you can add more classes to
so things like cameras or cubes and are just "gameobjects" that contain extra classes like mesh and rigidbody to make them function properly
and when unity starts, it runs all the code of each gameobject
which is why you cant run code without attaching it to an "empty gameobject" first

rain minnow
#

they also have a link to the C# code online . . .

heady iris
#

You just have to ask Unity to do it for you

#

but yes, you are correct that a "camera" is a GameObject with a Camera component attached to it

#

and a "cube" is a GameObject with a MeshFilter (to provide the mesh), MeshRenderer (to draw the mesh), and BoxCollider (to give it a physics shape)

#

Everything is a GameObject with Components attached to it.

halcyon swallow
heady iris
#

Every kind of component inherits from the Component class

leaden ice
#

Also yes that

heady iris
#

user-defined components must derive from MonoBehaviour, yeah

#

the hierarchy is Object (Unity's top-level object type) <- Component (can be attached to GameObjects) <- Behaviour (can be enabled and disabled) <- MonoBehaviour (can be extended by you)

#

(and Object inherits from System.Object, which is the ultimate ancestor of every class)

#

all of these types are in the UnityEngine namespace

halcyon swallow
#

so once you have created all of these "game objects" with a bunch of components and scripts in the editor, what is unity doing when you run the game?
does each game object run at the same time on its own thread? that seems obvious but i feel like it would create a lot of clashing and desync

leaden ice
#

imagine a big for loop

#
foreach (Component c in allComponentsInTheWorld) {
  c.Update();
}```
#

that's over simplified, but more or less what's going on each frame

#

(for Update)

#

basically - they run one at a time

#

definitely not in their own threads

halcyon swallow
#

so are objects updated arbitrarily?
or could you select some to run first

leaden ice
#

There are ways to control it

#

but for the most part you can imagine it is arbitrary

#

and most of the time you want to design your code so it works no matter what order the Update(s) run in

#

there is LateUpdate if you really need things to run after other things Update, and other tools as well.

halcyon swallow
#

cool, i dont think im at the stage where certain objects running first is a problem, but good to know

halcyon swallow
leaden ice
halcyon swallow
#

is there anything in unity that isnt done through game objects and their components?
the stuff you create that is

rain minnow
#

ScriptableObjects . . .

leaden ice
#

basically everything else besides that.

#

There's a whole universe of things that aren't GameObjects and components. The only thing we could do is list a few examples:

  • Any code you write that isn't related to GameObjects and components
  • The whole world of DOTS/ECS
  • UI Toolkit if you're using that
  • The job system
  • Audio through FMOD (if using that)
  • infinite other things
cosmic rain
#

The only thing that is centered around gameObjects and components(aside from a few exceptions) is the entry point to your code.

leaden ice
#

Yep there are basically 3 main entry points to your code in Unity:

  • Component event functions (Start/Update/Awake etc)
  • Systems in ECS
  • niche things like RuntimeInitializeOnLoadMethod and a few others
#

once you have "entered" your code, you do whatever you want.

halcyon swallow
#

okai
im more just worried ill read through the 400+ classes in the documentation and realise ive missed something big :p
i dont have enough vyvance to read through the entire unity documentation lol
it seems like you can do most things with objects, canvases, props, sounds, particles, players ect ect ect

leaden ice
rain minnow
#

there is no reason to read through all of the documentation . . .

spare dome
cosmic rain
#

What you do need is skip over the manual to know what features unity implements, so that you don't need to reinvent the wheel.

halcyon swallow
#

Yeah
Im only reading through to know what exists and what unity can do
The manual/documentation kinda sucks to navigate

cosmic rain
#

The manual is very easy to navigate imho. The pages are split into categories and subcategories, so you can only look at what you're interested in. As for the API docs, as has been said, you should use them as a reference. There's not much point reading through them.

#

Honestly, I always though of unity manual as one of the most readable manuals out there.

heady iris
#

the latter is literally just a list of every class in Unity

#

the former describes concepts in Unity

#

I'm struggling to understand why this causes Rider to warn me about an impure method causing the struct value to get copied

#

If Foo or Bar are made into a class, the warning goes away

#

(and if I call foo.bar.BarMethod(), there is no warning)

#

I presume it has to do with item being a foreach iteration variable

#

Oh, duh, I get it. item is immutable, so calling a possibly impure method on it requires a copy

#

duh

#

πŸ¦†

vestal arch
#

that's a thing in c/c++

cosmic rain
pearl burrow
#

Hey guys,
how do you deal with loading the inventory items prefab at runtime without loading them with resource.load?
I keep hearing its bad to use it but would it be bad to use it once at start to load all the SOs?

#

i need the references to the SO because i save their ID into a json

#

if they are a few sure i can reference them in the inspector but when they are alot?

leaden ice
cosmic rain
pearl burrow
#

it doesnt seem a good practice for my preference. When i create a new SO i need to add it manually and it might happen to add some already added

cosmic rain
pearl burrow
#

for example?

cosmic rain
timber zealot
#

anyone here?

lone zealot
timber zealot
lone zealot
# timber zealot im a beginner

welcome to Unity then πŸ”₯ there are lots of beginner resources online where you can start from. This channel is for asking code-related questions so you came to the wrong channel.

timber zealot
#

uhh ok

inland tusk
#

Im trying to do IK for my hands that will follow the rifle and i have a problem with Targets, actually when i will set target manually through inspector IK works and everything is fine but when im trying to do this through code its not working somebody have any idea?

vestal arch
fleet gorge
#

or final

vestal arch
fleet gorge
#

Aren't methods just sealed by default?

vestal arch
#

const methods mean this is const within the method, not that the method is const

thick terrace
#

it's readonly in C#, not const

#

you can only declare struct methods readonly but it should silence that warning since it makes this immutable

zealous lagoon
#

Hello, thought I'd ask for a tip from the pros. I've worked on countless games but never finished any cause my code got way too hard to work on, trying to avoid that here. I'm making a sort of space shooter game, and enemies spawn in shapes line lines, squares, triangle or circles before they go around moving the screen on custom paths. I've figured out a decent way to handle and store enemy data, but am now working on stage data.

I was thinking of creating some sort of abstract PatternGenerator class of which basically creates a list of spawn positions from some parameters (e.g. a circle given radius and how many enemies to populate on it).

Is it a good idea to make the stage data then a scriptable object which lists which patterngenerator to use at what time with what parameters to spawn enemies? Or am I just overcomplicating. How do "regular" games handle such stage data?

Thanks for any tips!

thin aurora
#

It marks the method as not being able to be overridden, and the method that seals it is the last method to override it

#

So yes, technically they are sealed by default

untold shoal
#

i have this in my script

#

my problem is even tho i added [ExecuteAlways], i know this code doesnt run because the shader is supposed to return the color red in the frag shader

#

yes the useShaderInSceneView bool is true

#

im in a urp 3d project in like unity 6000 or whatever

cosmic rain
# untold shoal

Well, if the code doesn't run, then that's the cause. Are you sure OnRenderImage is something called in unity 6?

untold shoal
#

yea the code isnt running, thats the problem.

untold shoal
#

wait, apparently for URP the onrender stuff is replaced with render passes

#

crap

#

i have no idea how to use those 🀣

trim schooner
#

at one point you had no idea how to use OnRenderImage either

cosmic rain
thin sonnet
#

I just trying to load audioclip and seems like its working fine in editor but on build I getting this "Initialize clip, freq 0Hz, Channels 0, Samples 0, Length 0, Load state Unloaded" thats audioclip

#
AudioClip clip = www.GetAudioClipCompressed(false, AudioType.OGGVORBIS);
clip.LoadAudioData();```
untold shoal
#

imma just make a new srp project i dont feel like messing around with this πŸ€¦β€β™‚οΈ

hidden compass
thin sonnet
#

worst thing is its working fine in editor but why

trim schooner
#

how come you're using www. ?

thin sonnet
#

.ogg

trim schooner
#

What references the .ogg to put it in the build? Check the build log and see if it's listed

hidden compass
#

isnt there a different one?

#

ya like UnityWebRequest

thin sonnet
#

yea I tried and both result with empty audioclip

#

thats in editor vs build game

#

or I need to wait some time when its loaded? idk

hidden compass
#
  • path issue
  • incorrect file format
  • compression issues
    these are the things that come to mind..
thin sonnet
#

both paths are 1:1 idk really what happens in this case

hidden compass
#

maybe its trying to play before its fully loaded?

thin sonnet
#

tried this but its spamming entire time like its doing nothing and clip is invalid

#

uhh its possible to disable audio in unity itself?

#

maybe thats why its not working

#

when game is built with "Disable Unity Audio"

#

main thing I dont want to play audio but just read samples from audioclip and sent those by encoding them to client

hidden compass
#

id Mute the audio vs disabling it

thin sonnet
#

ahh only if unity made proper error logs smh

#

I dont have any clue why this happens

#

somehow manipulating audioclips in batchmode should work + nographics

boreal cove
#

anyone could help me out with something?

vestal arch
#

not if you don't !ask

tawny elkBOT
hidden compass
tawny elkBOT
#
πŸ“ Logs

Documentation

Editor logs

Windows: %LOCALAPPDATA%\Unity\Editor\Editor.log
MacOS: ~/Library/Logs/Unity/Editor.log
Linux: ~/.config/unity3d/Editor.log

Unity Hub

Windows: %UserProfile%\AppData\Roaming\UnityHub\logs
Mac: ~/Library/Application support/UnityHub/logs
Linux: ~/.config/UnityHub/logs

hidden compass
#

or u just talkin about the console logs? are they not specific enuff or something?

boreal cove
vestal arch
#

we can't help you when we don't know what problem you have

thin aurora
#

You tell the issue, give relevant context and somebody that knows an answer or wants to help will help you

boreal cove
#

maybe cause im waiting for someone to say ''yes i have experience making similar game what are your issue'' and i'll dm them

chilly surge
#

It's not realistic for someone to commit to spending time and answering your question without even knowing what you are going to ask.

thin aurora
chilly surge
#

Ask your question up front, and whoever can answer will answer.

thin aurora
#

Also, nobody is going to appreciate DMs

#

This channel exists for questions, so you can just ask here

#

The issue with asking if somebody is available is because there's no guarantee whoever answers is even able to help with your question

boreal cove
#

and i'm looking for help from someone who specifically worked on the type of game i'm working on

thin aurora
#

So explain your issue in here and somebody with knowledge on the issue will help you

#

Also, make sure to share relevant code and errors if there are any

vestal arch
#

what you're looking for right now, is for someone to accept your request without knowing any of the details of the issue, and you're expecting them to be able to 100% help alone, and you'll both be free at the same time
that's not going to work out for either of you

#

that's what this community server is for

#

to get around that entire issue

#

if you want help, you need to tell us what you need help with

#

i find that 90% of the time someone comes in asking for some specific experience to help, once we finally wring out the question from them, it's not specific to that constraint at all

#

so maybe you don't even need that kind of specific person to help you

#

but you won't know if you never tell us what problem you have

thin aurora
#

If only they just shared their issue, they would have probably had their answer by now

boreal cove
#

maybe because i have other specific question to ask them about their experience making this type of game? anyway i've figured it out on my own

#

have a nice one

vestal arch
#

everything we just said still applies

thin aurora
#

Still something you can ask here

#

You too πŸ‘

vestal arch
#

not sure why you're trying to argue that one answer from one random person is better than a community answer but aight

#

also if it's about privacy concerns; why would you trust a single random stranger any more than you trust multiple random strangers

boreal cove
#

because i want to exchange with people who has actually worked on a similar porject idk why its so complicated to understand xD

vestal arch
#

and everything we just said still applies

boreal cove
#

it doesnt but ayt

chilly surge
#

We are just trying to help you understand "i did ask but nobody answered so i asked again"

thin aurora
#

I don't see how the experience of a single person is going to give you a proper answer

#

Because it's not

chilly surge
#

You don't have to listen to us, but you will run into the same problem of nobody answering you again.

vestal arch
#

and you're also just, again, trying to get someone to dedicate time to you without telling them what for

boreal cove
#

i jsut want to talk with someone who is working or as worked on a similar project - thats all

vestal arch
#

that's not very respectful of anyone's time, least of all your own

boreal cove
#

idk why it is so complicated to understand

thin aurora
#

idk why it is so complicated to understand

vestal arch
#

there's a reason community servers like this exist

#

and it's not for networking

thin aurora
#

And once again, nobody is going to use DMs when this channel exists

#

Literally nobody in here is interested in a personal conversation when a server full of people exists that can also answer questions

boreal cove
#

because i dont care if it benefits anyone else lmao - i just asked ''hey is there anyone working on a similar project, i might have some question'' but ayt

thin aurora
vestal arch
thin aurora
#

So perhaps think about what is being said here. You're not the first person who approaches this channel like this

vestal arch
#

let me propose a scenario for you;
imagine someone else, with the same goal as you, makes this same request
do you think it'd make sense for that to have 2 separate convos between 4 disconnected people, where 2 people get like, 80% of the full story, and any onlookers just don't get anything
versus having a common space to have that discussion, and have a single convo between, say, 500 people, where all of them, including you, gets 100% of the full picture

#

this server is that common space

#

utilize it to its full potential

vestal arch
hidden compass
#

because i dont care if it benefits anyone else lmao
sums it up nicely

vestal arch
#

and it goes both directions; maybe there was someone who had a better perspective, or alternate views
you'd never know lmao

heady iris
#

well, this is a mildly interesting problem

#

when I enable the frame debugger, I get a frame with an unscaled delta time of 0

#

This blows up my mouse input by dividing by 0

#

I suppose that anything that wants to divide by deltaTime or unscaledDeltaTime always needs to check for a zero

robust dome
#

is there another choice

heady iris
thin aurora
heady iris
#

fortunately, I almost never divide by deltatime

#

in fact, the only other place I do this is in..my own processor that I wrote before I decided to use the one Cinemachine provides

#

Wait, didn't I report this bug and get it fixed...?

#

I had the same thing happen with turning on the recorder

#

that causes a frame with a deltaTime of zero

#

ah, that was on the Input Axis Controller

last robin
leaden ice
last robin
heady iris
#

It's certainly a challenge

#

I've been poking very lightly at this kind of thing

leaden ice
heady iris
#

It's easy to compute correct values based on the most recent server response when it's just stuff like "X += 1", but simulating more complex interactions (like physics) and making the result look nice (imagine particles, sounds, etc.) quickly gets really tricky

#

ooh, I didn't know about that. Is that new?

leaden ice
#

yes

heady iris
#

neat!

leaden ice
#

it's constantly evolving

heady iris
#

I'm sticking to turn-based multiplayer at the moment, but I'm going to give realtime a crack eventually

#

(maybe a 1v1 game with rollback)

leaden ice
#

I tried doing this a month or two ago and gave up and am working on a single player game now lmao

#

It's not easy

heady iris
#

I'll do splitscreen

leaden ice
#

Splitscreen and hamachi - best networking solution

heady iris
#

you mean steam remote play/parsec/etc.?

#

or did Hamachi get into video streaming

leaden ice
#

uhhh - sure - idk

heady iris
#

Hamachi was the classic way to get your Minecraft server working tho

leaden ice
#

I'm just a lowly programmer

heady iris
#

it's a VPN (like, an actual VPN, not a proxy)

leaden ice
#

I think there's some tool to tunnel inputs over hamachi my friend was using for PlateUp a while back

#

I could be misremembering

hardy pasture
#

When I have multiple trigger colliders on children of the main parent game object, one collider per child. A component on those child game objects generate an event:

    [UsedImplicitly]
    void OnTriggerEnter2D() {
        OnCollided?.Invoke();
    }

What's the proper way to get the components and subscribe to the events in the parent game object component?

One way I see: GetComponentsInChildren with the component. This will get all but doesn't allow me to differentiate between the two.

Another is to have fields in the parent game object component:

    public GameObject LeftColliderGameObject;
    public GameObject RightColliderGameObject;

Then set those in the editor using the child game objects, and then in the Start method:

    void Start() {
        LeftColliderReporter = LeftColliderGameObject.GetComponent<ColliderReporter>();
        RightColliderReporter   = RightColliderGameObject.GetComponent<ColliderReporter>();
        LeftColliderReporter.OnCollided += () => Function();
        RightGateColliderReporter.OnCollided += () => Function();
    }

This works, but this feel more like a hacky workaround than a proper way to get the children and a way to have proper event for separate colliders.

leaden ice
toxic lichen
#

Hello,

I'm porting/cloning/rewriting an old Monogame game in Unity which uses/assumes a fixed 60 ticks per second and 60 FPS in all of its logic. This results in the game speeding up visually if you try to run it at a frame rate higher than that. In my clone, I'd like to make it support any framerate out of the box but still be as close as possible visually to the original.

There is some inconsistencies with floating point accuracy when increasing a timer/speed/any float using Time.deltaTime

float logoRotationSpeed = 0;
if (logoRotationSpeed < 20f) {
    logoRotationSpeed += 1f;
}
// Original game's update code, resulting in accurate 20f rotation speed!
// In Unity trying to do the same logic in Update() is not guarenteed
float logoRotationSpeed = 0;
if (logoRotationSpeed < 20f) {
    logoRotationSpeed += 1f / 60f * Time.deltaTime;
}
// logoRotationSpeed might end up as 20.333333 in worse case scenario!

Is this just a tradeoff I need to live with? Any solution? The inaccuracy is small, and this is only for visual effects, so I doubt it'd be noticeable. One idea I had was to clamp logoRotationSpeed after incrementing it/decrementing it, that helps but it's a bit more verbose everywhere I need to use it

hardy pasture
toxic lichen
#

Also the overhead of needing to do 60f * Time.deltaTime but I made a helper method getDeltaTimeInTicks for that

leaden ice
toxic lichen
#

I want to do the former

leaden ice
heady iris
#

You will still get different total amounts of rotation, though.

toxic lichen
#

How does that work under the hood? I'd prefer not call into any function that is doing anything I can't see, for purposes of this experiment

heady iris
#

it's extremely simple

#

you're already calling into huge amounts of functions you "can't see" πŸ˜‰

#

this.gameObject is vastly more complex

hardy pasture
# leaden ice Drag them into the slot in the inspector

I can only do it with the whole game object and then GetComponents, I don't understatnd how to do it on a component of a separate game object, because once I click on another game object, the inspector swiches to that game object and once I start dragging the component from that other game object, I can't drag it on the game object where I wan it

heady iris
#

Unity will find the component

#

You can also right-click on an object in the hierarchy and hit Properties

#

this will open another inspector

leaden ice
toxic lichen
#

But yeah it seems pretty simple

#

Does that just cap it if it goes over the provided max?

heady iris
#

If you're close enough to the goal, it returns the goal

#

Otherwise, it moves closer to the goal and returns that

toxic lichen
heady iris
heady iris
toxic lichen
#

yeah

heady iris
#

If the game is running at exactly 60 FPS, then your total rotation will be

heady iris
#

0 * 1/60 + 1/20 * 1/60 + 2/20 * 1/60 + ...

#

(assuming that logoRotationSpeed is divided by 60 -- if it isn't, then it's literally just 0 + 1/20 + 2/20 + ...)

#

If your game runs at a different framerate, even though logoRotationSpeed's value increases by the right amount per frame (more on slow frames, less on fast frames), you'll wind up with a different summation

toxic lichen
#

sigh.. it so complex i gdont get it

heady iris
toxic lichen
#

trying to port framerate-dependant code to be not framerate dependent

heady iris
#

In this case, it probably doesn't matter at all

toxic lichen
#

like i said i made a helper fn that give me deltaTime * 60

#

so i can use the same values as in the original code

heady iris
#

the logo's spin will wind up being a tiny amount off from how it would be in a game locked to exactly 60 FPS

toxic lichen
#

otherwise i'd have to divide everything by 60, probably giving ugly numbers

#

yeah I think I understand that fen. but does clamping it if it goes over/under at least help?

heady iris
toxic lichen
#

rotation of 20.3333 would add up to rotate faster over say, 10 seconds than 20f would

heady iris
#

Yeah, I used to make that mistake a fair bit

toxic lichen
#

right

heady iris
#

The amount of time it takes may also vary a tiny bit from what you expect

#

Extreme example: imagine the game is running at 3.01 frames per second

#

After one frame, Time.deltaTime is just barely under 0.333

#

If you increase the rotation speed by Time.deltaTime * 60, you'll be just barely under 20

toxic lichen
#

I use 0.3333 as example since that's the default maximumDelatTime

hardy pasture
heady iris
#

Breaking away from framerate dependence can be very hard!

toxic lichen
heady iris
#

Especially if you have very specific behaviors you need to preserve

toxic lichen
#

regardless of what speed it take to get there

#

maybe with game slowdown or speedup

#

Fen, this is just for rotating a logo on a menu. I compared it to the original game and I can't even see a difference with my own eyes

#

It's only for visual effects

heady iris
#

In that case, you're good πŸ˜›

toxic lichen
#

I will keep physics entity stuff in fixedupdate and interpolate them there

#

I think that's the way to go?

heady iris
#

Yeah, physics will wind up being fixed anyway

toxic lichen
#

Zig pseudocode of what I am doing to make it framerate independent:

heady iris
toxic lichen
#

original (fixed update) game's code:

#

yay or nay

#

the original game was so poorly coded, they used & rather than && in a ton of places for boolean and

heady iris
#

Yeah, multiplying every rate-of-change with 60 * Time.deltaTime will work

#

At 60 FPS, this has no effect. At higher framerates, this reduces the value

toxic lichen
#

time.getDeltaTimeInTacks is my helper method for that

#

it's just my delta time * 60

#

where i could change 60 later if i wanted to simulate a different tick speed than original game

#

i think this system will work!

#

Thank you !

tardy tendon
#

Anyone know how to make a NavMesh agent jump? It seems to be locking the Y and negating anything I do with the Rigidbody...

heady iris
#

By default, an agent controls its Transform

#

If you want to jump along an off-mesh link, consider setting it to not update its position during the jump

devout knoll
#

is it possible to cast a sphere to the end of a raycast, and then collect all the object angles within it? and if so, how could i do it?

i.e. image 1 would only give me 30d, but image two would give me 30d and 45d

heady iris
#

I can't think of a way to ensure you find every surface -- but consider a spray of raycasts

#

Especially if you just need to find all the surfaces on a circle

#

rather than every single surface the sphere is close to

devout knoll
#

how many raycasts would be ideal?

heady iris
#

the raycasts would fire out of the edges of this circle

heady iris
#

What's the goal here?

tardy tendon
devout knoll
#

the reason i want to get multiple angles is because i will average them

rigid island
paper pine
#

okay sry didnt knew there was a tab for that

toxic lichen
#

Which brotli compression level does Unity use for web builds?

#

On .wasm files

vague cosmos
#

What's the best way for me to smooth the movement of the circles at the top? The code moves the circles by updating the transform.x by -0.1 every 0.3 seconds in this clip using this.transform.position = this.transform.position + new Vector3(-0.1,0,0);

heady iris
#

Is there a reason you're doing this on 0.3 second intervals?

#

The answer is going to be "don't do that" :p

spare dome
heady iris
#

I bet you're doing a coroutine that yields a WaitForSeconds

#

which'll make this framerate-dependent

fossil blaze
#

How can I make these two stroke materials not be saved?

heady iris
#

Are you running this code in response to OnDestroy, perhaps?

#

(or otherwise running it outside of play mode)

heady iris
vague cosmos
vague cosmos
heady iris
#

InvokeRepeating might be more reliable at least

#

I'd hope that it prevents errors from accumulating over time

vague cosmos
#

It does not, at least for now but we'll see

#

I wouldn't be suprised if i need to change something later

hexed pecan
#

Using the materials property will instantiate the materials

#

Yeah I dont think I know what you mean, clarify please

fossil blaze
#

When I pick up a rack it changes the material whether it can be placed or not, after I have placed it, for some reason it keeps these validity materials.

hexed pecan
#

You didn't show any code that would restore the original materials

#

You should just do the inverse of StartRackMovement: Assign the original materials back to the object

fossil blaze
hexed pecan
#

Shouldn't you assign the materials back to all renderers, not just one?

#

You used GetComponentsInChildren in StartRackMovement, here you are just using GetComponent

hexed pecan
#

Mate add some context when you send me a screenshot

fossil blaze
#

no good

#

bug

hexed pecan
# fossil blaze

So originalRackMaterials changed from Material[][] to Material[]?

#

Are you just relaying my messages to ChatGPT

#

Use !code to post it correctly, and include the whole script

tawny elkBOT
fossil blaze
wheat spruce
#

Is it possible to make Unity show lines like public Vector3 Origin { get; private set; } or public Vector2 Size => _rectangle.Size in the inspector, without having to do any backing field stuff?

hexed pecan
#

field: makes it target the backing field

fossil blaze
#

help guys please

hexed pecan
wheat spruce
#

using field in the attribute worked

hexed pecan
# fossil blaze help guys please

Why did you change your StartRackMovement code to this?

                Renderer[] childRenderers = rackToMove.GetComponentsInChildren<Renderer>();
                if (childRenderers.Length > 0)
                {
                    originalRackMaterials = childRenderers[0].materials;
                }````
wheat spruce
#

I probably wouldnt want to show any of my getters in the inspector anyway

hexed pecan
fossil blaze
#

okay

worn star
#

i made this πŸ₯Ή , it finally works

untold shoal
#

idk if im doing this wrong

#

this line of code

#

its giving this error

heady iris
#

well, what's a RayTracedMesh?

untold shoal
#

its a script, idk if im using this right at all

#

its got nothing in it currently

heady iris
#

It only works with a type that can be converted into an unmanaged structure -- basically, something you turn into raw data

#

Why are you trying to do this?

#

I presume you're trying to pass data into a Job, or maybe send data to the GPU?

untold shoal
#

imo im not sure computebuffer is the right thing, i think it is

heady iris
#

Consider just making a struct, then

#

A struct that contains only unmanaged types (e.g. ints or a struct) will be valid here

#

I'm unclear exactly what you're doing here, though

untold shoal
#

will this still work so that i dont have to like... hardcore everything that is raytraced?

heady iris
#

are you going to put an entire mesh into this thing?

cosmic rain
#

I don't think marshalling is related to sending data to a GPU...πŸ€”

untold shoal
#

i wanted to apply the raytracedmesh script to any object and then send the position/mesh data or wtv to the shader to be raytraced

heady iris
#

well you definitely aren't sending an entire component to the GPU

#

this seems odd

untold shoal
#

this is the whole bit

cosmic rain
#

The way to send data to the GPU is very defined. It's done via graphics/compute buffers or by setting shader root parameters and not in any other way.

untold shoal
#

wait

#

i just thought of something

#

brb

cosmic rain
heady iris
#

i started using StructuredBuffer recently to send a bunch of structs to a shader

untold shoal
#

if im being completely honest i have no idea what im doing, im just kinda pinging from multiple online forums

heady iris
#

i forget if I used sizeof or just hardcoded the size of the struct

heady iris
untold shoal
#

i said it earlier, but im trying to not have to hardcode each shape to raytrace. can i still do that with structs or?

cosmic rain
#

Just how many shapes do you have?

untold shoal
#

spheres

#

for now

cosmic rain
#

What kind of data is it? What does RayTracedMesh contain? Does it inherit from anything?

untold shoal
#

currently, no. thats probably the problem, right?

#

im wondering if structs will still work, so imma just look it up rq

heady iris
#

you should probably start with some basic compute buffer usage

#

literally just giving numbers to a shader and having it add them for you

untold shoal
#

idk why i didnt 🀣

heady iris
#

the important thing is that you can't just throw managed C# objects into a compute shader -- there is no .NET runtime out there!

#

If you've never heard of "managed" and "unmanaged" before, maybe play with the Job system a bit

cosmic rain
heady iris
#

it's a class, so,

#

πŸ’₯

untold shoal
cosmic rain
#

You can marshall classes, if all of their members are primitive data.

heady iris
#

Ah, okay, that makes more sense.

heady iris
#

I was starting to wonder if I was in the wrong there :p

untold shoal
#

is it not allowed to inherit monobehaviour?

cosmic rain
#

No.

untold shoal
#

oh

cosmic rain
#

MonoBehaviour is a lot of stuff. A lot of managed stuff too

heady iris
#

You can definitely have a component type that you use to create other objects

#

e.g. iterate over a bunch of RaycastComponents and build a list of RaycastInfo objects

heady iris
untold shoal
#

this is the class now

#

do i have to get rid of the color stuff too?

cosmic rain
untold shoal
#

i also tried setting them as vector4 and still same error

#

i just realised that without monobehaviour i cant attach this to anything, which was kinda the whole point.

#

thanks for your guys' help but i think im going to research on computebuffers and take a different approach after

heady iris
#

i mean, that's not really something you'll search up

untold shoal
#

oh wait lol

heady iris
#

it is a little confusing, because the documentation says that SizeOf...

Returns the unmanaged size, in bytes, of a class.

#

I'm pretty sure that you can do something to make a class marshallable, because I'm seeing examples that involve classes.

#

oh yeah, you have to declare a [StructLayout] for it

#

struct types implicitly have a sequential layout, but classes require you to explicitly say so

untold shoal
#

sorta

#

the error is gone

#

new error 🀣

cosmic rain
cosmic rain
heady iris
#

Yeah, so that's the second part

#

A blittable type is one where the managed (C# world) and unmanaged (raw data) representations are identical

#

You literally just copy-paste the data

cosmic rain
#

Yeah, so it would have to be a struct.

untold shoal
#

dam

#

all i need to figure out is how to pass data to the shader in buffers

#

idk why its so hard for me 😭

#

and its not even a compute shader, so it should be easy

cosmic rain
untold shoal
cosmic rain
#

You can. Or you can have a structure that contains both.

untold shoal
#

like, i wanted to have the raytracedmesh script to just easily attach, setup the size and color, and then be able to move the object around and the data still gets fed to the shader

cosmic rain
#

Surely you can set it up in a way where you wouldn't need to hardcode every case.

untold shoal
#

im trying to not do that

cosmic rain
#

That's definitely sounds inefficient.
Then don't do that.

untold shoal
#

im trying to figure out how to not do that

#

and do it another way

#

i can see now my original way wont work

cosmic rain
#

@untold shoal We can't really help you without knowing more context. For example, what kind of data are you trying to pass to the shader.

untold shoal
#

for now RaytracingMaterial just contains color

#

I want to pass position, size, and the raytracingmaterial data to this structured buffer

#

So all the data isnt hardcoded like this

#

ive just figured out how to pass data through a buffer to the shader

#

the "position data" list just contains a single color and it works fine

#

this sphere only exist in code, but the position data is working fine and i can move it around by changing the position data

#

now i just have to have a position data element for each sphere, and have it update accordingly

cosmic rain
heady iris
#

Indeed.

#

Look at the stuff in your scene and fill a buffer with data based on that stuff.

untold shoal
cosmic rain
untold shoal
#

i mean, i also need it to be a static list to access it from other scripts

cosmic rain
cosmic rain
untold shoal
cosmic rain
#

Don't make it static. Make it an instance list on a singleton.

untold shoal
#

Do singletons work if the script is running in editor?

#

like, im not in playmode

cosmic rain
untold shoal
#

oh yea

cosmic rain
untold shoal
#

im gonna be working specifically with spheres for now, future me can worry about actual meshes 🀣

untold shoal
untold shoal
cosmic rain
untold shoal
#

oh

untold shoal
#

ive been at this for 2 days 🀣

#

this line only runs in playmode

#

The script has [ExecuteAlways] in it, and I can use Debug.Log in this script

#

eh, its not a big issue, tho if anyone finds a solution im all ears

cosmic rain
untold shoal
#

its not a big issue atm, just would be nice if it were fixed

#

oh and btw

cosmic rain
#

Are there errors then?

untold shoal
#

its sorta working

untold shoal
#

oh i mean there isnt

cosmic rain
untold shoal
#

there isnt any errors

cosmic rain
#

Then you'll need to share more context.

untold shoal
#

oh okay i found an error

#

the singleton isnt working in edit-mode

#

im sure im doing it right

cosmic rain
untold shoal
#

i think, ill try using start instead

cosmic rain
#

It definitely wouldn't run normally.

#

Neither would start.

untold shoal
#

oh

#

do i put it somewhere else?

#

just got this error and didnt save 😭

cosmic rain
#

Well, you need to make sure the instance is assigned in edit mode. So either make the script run in edit mode or use some editor callback.

cosmic rain
#

Or out of bounds access.

untold shoal
untold shoal
#

i havent saved in like a solid hour

cosmic rain
cosmic rain
untold shoal
#

i thought everything got completely reverted if unity crashed

cosmic rain
#

Only stuff that is not saved.

untold shoal
#

nvm it just didnt get put into unity hub, i found the files

#

my first unity jumpscare

untold shoal
#

im using OnEnable instead of Awake

#

and now all the spheres from my scene are rendering at the same time

#

thanks dlich and fen for your guys' help, finally after 2 days ive ironed out all the errors

pearl burrow
#

Hi,
talking about save and load systems im having some "issue".
I have a singleton class (lets say GameManager) that holds the gameData object which is created by loading and saving the game.

But now every time i need to edit values in the game data i need to call
GameManager.Instance.gameData.<valueToBeChanged>
As my project is growing more and more classes use this and its true im the only one working on my own project but it starts to looks ugly and highly dependent on that (hey there singleton).
I used this pattern also because some object instantiated at runtime need to edit values in the gameData and i dont know a better solution. Any help?

cyan ivy
wheat spruce
pearl burrow
#

no my singleton class is something like this

  //singleton stuff initializataion
  public GameData gameData;
}

[Serializable]
public class GameData {
  int level;
  //etc
}```
#

sry i forgot how to format for c# language πŸ₯²

#

its not about having many properties but having to call the gamemanager every time. Im currently working on a solution tho. mostly i save ongamepause or on quit and i load only at start

so im creating a way to store all the save method of the class that needs that only save what it needs to be saved

#

i've just tought about it

little meadow
#

I'd say there are 2 approaches (maybe they overlap, I don't know :D):

  1. the objects on the scene use the same data that's in GameData... say you have an enemy, it has EnemyData somewhere in GameData, and you use that same EnemyData inside the enemy to store its data (the part that needs to be saved/loaded)
  2. you make 2 "functions" one is CreateObjectsFromData and the other is GetDataFromObjects and then make an ISaveable interaface maybe and you use all of this to save/load
    Also, there's probably many save tutorials that explain it better than me right now πŸ˜…
wheat spruce
#

Ah, I think I understand now. But I don't think I can offer much advice, as I haven't done much in the past when it comes to doing this kind of data saving

pearl burrow
#

something like

  int level = 0;
  //stuff that player does
  
  public void Save(ref GameData gameData) {
    gameData.level = level;
  }
  public void Load(GameData gameData) {
    level = gameData.level;
  }
}

public interface ISave<T> where T : SaveData {
  public void Save(ref T gameData);
  public void Load(T gameData):
}``` 

ive made it generic so i can have my different objects
#

then at start i search all the object of type isave and call the load, and when needed i call save from all the object of type isave and save

pearl burrow
#

my only concern is that object instantiated at runtime will be saved successfully if present in the scene at the moment i save

#

but when loading?

little meadow
#

you should probably implement the save load of these on some manager that can instantiate them, not on the objects themselves

pearl burrow
#

oh right

#

love programming

wheat spruce
#

I'm sure there's some similar thing to Awake() when a scene is newly loaded

cyan ivy
#

But they implement load right, so at time of instantiation you need to assign the gameobject an instance of a script that implements Load of that type. Perhaps a Delegate function that takes the instantiation call to capture the object description?

#

This is starting to feel a bit like the Command Pattern

pearl burrow
#

thanks guy. im working on it with clearer ideas

fiery elm
#

how do i restart a particle system to be able to call Play on it again

knotty sun
fiery elm
#

one guy on SO said time=0

#

didnt work either

#

another to slap a Simulate witj dummy vars

knotty sun
#

I very much doubt the documentation is lying

fiery elm
knotty sun
#

that is not .Play()

fiery elm
#

and that the code immediately preceeding it is exec'd jusy finr

fiery elm
#

writing frpm memory, laptop out of lower

cosmic rain
#

Well, come back when you are actually next to the project open and ready to debug

cyan ivy
#

Try with a new default Particle System to see if the problem is in your code or in your particle system setup

subtle path
#

so i have this code for my event system (from a tutorial)

 public class EventManager
 {

     #region BaseEvent

     public class GenericEvent<T> where T : class, new()
     {
         private Dictionary<string, T> map = new();

         //this is to apply filters for different listener groups
         public T Get(string channel = "")
         {
             map.TryAdd(channel, new T());
             return (T)map[channel];
         }
     }
     #endregion

     #region Events



     public static readonly LevelEvents Level = new();
     public static readonly LevelEventArg LevelArg = new();

     public class LevelEvents
     {
         public class LevelEvent : UnityEvent { }

         public GenericEvent<LevelEvent> OnLevelInstantiated = new();
     }
     public class LevelEventArg
     {
         public class LevelEvent : UnityEvent<string, float, int> { }

         public GenericEvent<LevelEvent> OnLevelDestroyed = new();

     }
     #endregion
 }```

is there a way to have events with dynamic parameters, without having to write everything new?
#

to be more specific:
i dont want one "LevelEvents" and one "LevelEventsArgs" class. I'd like to have just one reference that i can use with or without parameters

thick terrace
fiery elm
# cosmic rain Well, come back when you are actually next to the project open and ready to debu...
    // Update is called once per frame
    async void OnTriggerEnter(Collider other) {
        if(other.gameObject.tag == "Player"){
            var ball = other.gameObject.GetComponent<Ball>();
            ball.shoot_blockers |= Ball.AIM_LOCK_CUTSCENE;

            confetti.Stop();
            confetti.time = 0;
            confetti.Play();
            await Task.Delay(TimeSpan.FromSeconds(2.5));

            GameManager.us.load_map(GameManager.us.current_board_index + 1 ?? 1);        
            gameObject.SetActive(false);
                        
            //GameManager.board_start_points
        }
    }
#

issue is: the confetti part only procs the first time, not the second
a) load_map() is called just fine, just the particles in specific dont work
a) the gameObj is reset back to active yes

cosmic rain
fiery elm
#

i can visually see it gets to load_map from the visual effects it performs

cosmic rain
#

For starters just a log to see that the code executes for sure.

#

Judging by other things happening might not be reliable. Add logs.

#

And then Also investigate the particle system at runtime.

fiery elm
#

(the second time is because i triggered this two times)

cosmic rain
#

There's something really wrong with that screenshot.

fiery elm
knotty sun
# fiery elm

why would you post a screenshot which is totally unreadable?

fiery elm
knotty sun
#

irrelevant, if you come here for help then YOU need to make sure you provide usable information

fiery elm
#

is this enough for "this is the best i can give"

knotty sun
#

what do you think? Could you work with that?

fiery elm
#

yes

knotty sun
#

then do it coz I'm not going to expend the effort

fiery elm
#

then dont

cosmic rain
#

How are you taking the screenshot? Are you on windows?

fiery elm
#

all its showing is stuff that was already established

fiery elm
#

(terrible, ik)

#

some built-in* stuff, what program exactly is it using idk

cosmic rain
#

I'd also check if the reference in the script is referencing the correct object.

#

And that there are no errors.

fiery elm
cosmic rain
#

There should be an overlay window in the game/scene viewport.

#

Not the inspector.

fiery elm
#

oh wow it actually made a good csreenshot this timethis stuff?

cosmic rain
#

So, what do you see there at runtime?

#

When the it's supposed to be playing

fiery elm
cosmic rain
#

Well, there you go. Probably were looking at the wrong place

fiery elm
#

probably yeah

#

weird that it offset like that tho
the particle emitter itself is in the hole and i dont recall fucking with the position

#

i think its part due to me cp-ing the object that held the partilce holder

#

may have done sm shallow copy stupids in there

#

yeah i just checked
if i reactivate the original particle holder and activate it (through inspector) it particles in the same place

cosmic rain
#

Must be some parameters/settings getting modified

fiery elm
#

already had a bug where such copying didnt reset the reference
(x with child y -> y) -copy-> (z with child w -> y)

#

which, fair, feature not bug

#

wouldnt be surprised if i missed sm else

cosmic rain
#

In the first place, there's no such thing as copying gameobjects and components. So I'm not sure what exactly you did.
You can clone them via Instantiate.

tribal mortar
#

[Serializable,CreateAssetMenu(menuName = "Scriptable/Factory/BuildingFactory")] public class BuildingFactory : BaseFactory<Building> { public override Building Create(string name) { var result = products.Find((x) => x.name == name); return result == null ? result : Instantiate(result); } } [Serializable] public abstract class BaseFactory<T> : ScriptableObject { [SerializeReference] public List<T> products; public abstract T Create(string name); }

i want to change this code using zenject factories, can anyone guide me how to make objects by name in zenjects

knotty sun
#

!code. use a paste site please

tawny elkBOT
wheat spruce
#

Why is [SerializeField] private int[] _gridMap; showing up in the Inspector as a List?

vestal arch
#

a list is just a wrapper for an array, which keeps track of how full it is, then makes a new array if the old one is full and you want to add more

heady iris
#

Unity uses the same UI for both

#

They are serialized identically

wheat spruce
#

it does seem quite strange that the UI is identical for each, if only for the fact that the UI element has the add/remove buttons which goes against the point that arrays are supposed to be fixed length

heady iris
#

Arrays have a specific size at runtime

#

i dunno exactly what Unity does when applying serialized properties

lethal tapir
#

static void Main(string[] args)
{
// Create the dictionary
Dictionary<Deva, Caste> DevaCasteDict = new Dictionary<Deva, Caste>();

// Assign castes to devas
foreach (Deva deva in Enum.GetValues(typeof(Deva))) 
{ 
    switch (deva) 
    { 
        case Deva.Indra:
        case Deva.Aditi:
        case Deva.Agni:
        case Deva.Svaha:
        case Deva.Mitra:
        case Deva.Ashwinis:
            DevaCasteDict[deva] = Caste.Vedic;
            break; 
        case Deva.Perun:
        case Deva.Veles:
        case Deva.Mokosh:
        case Deva.Svarog:
            DevaCasteDict[deva] = Caste.Slavic;
            break;
        case Deva.Dievs:
        case Deva.PerkΕ«nas:
        case Deva.Gabija:
        case Deva.Ε½emyna:
            DevaCasteDict[deva] = Caste.Baltic;
            break; 
        case Deva.Zalmoxis:
        case Deva.Mara:
            DevaCasteDict[deva] = Caste.Romanian;
            break; 
        case Deva.Zeus:
        case Deva.Athena:
        case Deva.Apollo:
            DevaCasteDict[deva] = Caste.Greek;
            break; 
        default:
            break; 
    } 
} 

// Print the dictionary 
foreach (var deva in DevaCasteDict) 
{ 
    Console.WriteLine($"{deva.Key} belongs to {deva.Value} caste.");
}

}

#

Question: How would I implement a system that dynamically categorizes and displays deities with potentially overlapping characteristics or attributes across multiple traditions, using a data structure that supports efficient querying and retrieval?

leaden ice
#

but essentially, a tagging system, indexed on whatever you will query by.

reef lagoon
#
public class JumpConnect : MonoBehaviour
{
    [SerializeField] float  jumpPower = 5f;
    private Vector2 originalPos;
    private Rigidbody2D rb;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }
    public void Jump()
    {
        originalPos = transform.position;

        rb.AddForce(new Vector2(rb.velocity.x, jumpPower), ForceMode2D.Impulse);
    }
}

This is what im using to make player jump and im referencing Jump function. It plays animation but player wont move any ideas why?

heady iris
#

why are you adding a force based on the current x velocity?

#

just push the player upwards

#

Also, make sure that "Jump Power" isn't a zero in the inspector

#

The field initializer doesn't matter if you have a saved value of 0

vestal arch
#

also make sure Jump is being called
you could try adding a debug log to make sure it is

leaden ice
#

There's nothing in here about an animator

reef lagoon
#

I tried having it on 0 and I checked jumpPower and made it 1000 didnt work but i now noticed that the velocity changes for a split sec but then goes to 0 so it is applying force it seems like but character wont move:/

#

Im calling the jump in another script

#
public override void Activate()
{
    if (IsReady())
    {
        // Jump logic
        animator.SetTrigger("jumped");
        animator.SetBool("isJumping", true);

        jumpConnect.Jump();

        cooldownTimer = cooldownTime; // Reset cooldown
    }
}
#

Here

#

private void FixedUpdate()
{
//Adds velocity for movement on y and x axis
rb.velocity = new Vector2 (horizontal * moveSpeed, vertical * moveSpeed);
}
ohh wait can this erase the jump?

leaden ice
#

of course

#

vertical * moveSpeed this will be your new vertical velocity after that runs

reef lagoon
#

i always manage to miss these thingsπŸ€¦β€β™‚οΈ

leaden ice
#

overwriting anything that was there before

reef lagoon
#

Thanks for help!

wheat spruce
#

I dont get the way Awake is called when Garden gets the two components.
What I would expect to happen is it first gets Rectangle, which I beleive would call its Awake method as the documentation says Unity calls Awake when an enabled script instance is being loaded.. That should construct the Size property.
Then when Garden gets my Grid component, the Awake in SimpleGrid should be able to get that constructed Size property from the Rectangle

public class Garden : MonoBehaviour {
  [SerializeField] private SimpleRectangle _simpleRectangle;
  [SerializeField] private SimpleGrid _simpleGrid;

  private void Awake() {
    _simpleRectangle = GetComponent<SimpleRectangle>();
    _simpleGrid = GetComponent<SimpleGrid>();
  }
}

public class SimpleRectangle : MonoBehaviour {
  [field: SerializeField] public Vector2Int Size { get; private set; }

  private void Awake() {
    Size = new(10, 10);
  }
}

public class SimpleGrid : MonoBehaviour {
  private void Awake() {
    Debug.Log($"{GetComponent<SimpleRectangle>().Size}");
    //this only ever prints (0,0)
  }
}```
vestal arch
#

"loaded" does not mean GetComponent

#

try adding logs inside Garden's Awake as well, before/between/after the GetComponents

wheat spruce
#

issue is that Size doesnt get a chance to be set before anything can use it

heady iris
#

I don't know if Awake runs in a particular order

#

It's probably down to the exact order that the objects get created during game startup

wheat spruce
#

it might be me, but it honestly feels really frustrating that you cant construct MonoBehaviour classes like a normal class

heady iris
#

what would you be constructing here, though?

#

Unity is creating the SimpleRectangle and SimpleGrid objects as the game starts

#

Consider an explicit "init" method if you need to enforce a specific ordering

vestal arch
knotty sun
heady iris
vestal arch
#

also perhaps the event order could work

#

i forget what it's called

heady iris
#

You could absolutely use AddComponent to attach another SimpleRectangle to your game object, but this would have nothing to do with the one stored in _simpleRectangle

knotty sun
#

script execution order

leaden ice