#archived-code-general
1 messages Β· Page 395 of 1
it puts (Script) after every single component name if you haven't given them this attribute https://docs.unity3d.com/6000.0/Documentation/ScriptReference/AddComponentMenu.html
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?
this is a code channel.
its blurry probably because of Filtering mode / Compression
#π»βunity-talk or #πΌοΈβ2d-tools
my bad
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?
A GridLayoutGroup will request enough space to show all of its elements.
Its parent will need to give it enough space, of course
but I want it, to increase UI size/decrease it... like adding rows/coloums with a bagpack
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.
Yes, you can make a window that stretches out as you add more rows of items to a grid layout
what is a content size fitter?
so I have to attach this component on my UI?
You should read through the "Basic Layout" and "Auto Layout" sections of the UI docs
Unity's UI stuff... π© it works, but it's so unintuitive at times...
It's actually very straightforward if you just respect the layout system
thxx
it doesn't even respect itself, Fen! π
The problem is that all of the default UI objets do not play nice with auto layout
At all
let me introduce you to UIToolkit..whyyy unity
π
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
This is the golden rule. Each object in your hierarchy needs to be able to figure out how much space its children need
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 π
You can easily add margins around and between child elements
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
they have only padding, no? or are margins some new thing in latest Unity?
I'm talking about padding around the group and spacing in-between its children
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"
yes, but I don't want either of them π it's a sort of hack, because they didn't make one for single element, or didn't make it the default if the parent says "hey I'm controlling stuff, just measure what's measurable" or whatever
it works, but it's tedious, that's what I'm saying π
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
It would not make sense to have a "one child" layout group, because that's just a vertical or horizontal layout group
sure, but if you're in UI context and parent cares about child size, then this should get handled automagically π€·ββοΈ I shouldn't need to manually add 7 vertical layout groups in a chain to achieve a few objects wrapping each other
If parent A cares about child size, then the child needs to report the correct size
that works, but a single element one would have fewer options, do less work and be a better fit
Without any other context, the child will say it needs no space
Because it doesn't need any.
but its children do!
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
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 π€·ββοΈ
There are plenty of situations where you ask for less space than your child needs. An obvious one is a scroll view.
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
I just think that a lot of people have a very mangled understanding of UGUI, and that it works way better than most people think
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)
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")
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.
That is a fair point
Yes, hence me complaining about the terrible defaults earlier
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)
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 π
its not faster per default, there are things it does better, others it does worse. This is a conceptual issue of immediate vs retained mode drawing.
Thanks! I'll have to check which does what better. π
UGUI is a single-pass layout engine, 'all' other frameworks use multipass layouting, you can do multipass in UGUI too, you just have to fire it manually.
retained mode is evil when it comes to rendering/layouting tables and long lists
which is better for a health bar in the corner of the screen, ui toolkit or default unity gui?
depends on the context.
it shows the player's health? or what do you mean by context
the rest of the game, workflow and how it actually looks
huh, i didnt know it was that complicated
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"
do I add the Layout element on the inventory slot or the UI?
layout element component goes on the thing that is a child of the object with the layout component, so yes its probably the inventory slot
and content size fitter to the ui?
if you have more UI questions, you should stick them over in #π²βui-ux
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..
Clicked what?
Physics. class functions belong in FixedUpdate most of the time ?
Oh I read "i just clicked that" π€¦ββοΈ
Oh lol . I was just wondering its basically true
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
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
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
ahh..so thats framerate dependant ?
Changing your FPS to 5 will still let fixedupdate run faster than 5FPS thats why it works
Only if in Update, in FixedUpdate it's always the same, but if the character would go faster or your fixed timestep would be higher then I think you would see issues again
Like if you move more than 1 unit per frame (physics frame)
oh ok , so even if my char doesn't move forward/back it does this?
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
yeah I think its what you said, fixedupdate keeps consistent at low fps
update might be calling it slower than physics are moving ig
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
also I use physics to move the obstacles anyway with a rb
It's easy to fix tho, you just scale your spherecast's distance with the speed
the speed of which?
The stuff moving towards you
If they ever move faster than your current max spherecast distance then theres a chance to miss it
ah ok, its just 1 main object that has multiple colliders
What did you use for distanceCheck?
(I incorrectly assumed your spherecast length is 1)
.55
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
like this?
var hits = Physics.SphereCast(transform.position, cc.radius / 1.2f, Vector3.forward, out var hitInfo, distanceCheck * Time.fixedDeltaTime * 45 + 0.25f);
still misses in update
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
basically
containerMover.velocity = speed * Vector3.back;
in fixedUpdate
0.25 is optional I just think it gives better game feel
Yeah use that speed here
like this?
def got longer lol
might be hitting before my "head" hits
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?)
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
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
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
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
yeah I just want to basically simulate a "door" you run into with the correct shape
@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"
it went behind now but it only hit 1 out 3
Might need to add the sphere's radius to the distance too..
are there any drawbacks to just keeping that function in FixedUpdate? seems thats the only one working well at low fps
But yeah you wanna do it in fixedupdate anyway
Yeah point wasnt to move it to update, just to make the distance accurate
why do you care about low fps again? π
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
eh, I guess it's fair... 5 is a bit extreme, but yeah, makes sense to make it work on various FPSes
yeah like what if it dipped at somepoint not always 5 but just low enough and someone complains "HEY I missed my points"
It could temporarily run at 5 FPS when say your antivirus starts scanning or something
This
Just one dropped slow frame could be bad
my general rule is , if it works on crappy specs I'm happy it works lol
so, is it reasonably solved if you do it on FixedUpdate?
Should be
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
you need to be mindful of the length, but in FixedUpdate it should be easy as it aligns with the physics
yeah makes sense esp the main object moving those colliders is a RB so a physics function in fixedupdate makes sense for sync
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
yeah I'm used to doing that in Update for gravity / groundcheck but I wonder now if I should've been doing it in fixedupdate all along..
CC moves with Update code but ig its a kinematic physics object anyway
yeah, I do those in update, but that's because I also move in Update
yeah this is exactly why calling it in FixedUpdate sucked with CC
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.
C++ in what way ? You can call functions to C++ and vice versa
By using C++ programming instead of C#
It means you have to precompile your C++ code into a shared library (.dll on Windows) and export any functions you want to be able to call from C#. The native plugin API is not designed to be a replacement for C# scripting.
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
I already got a course for C++ I have started learning that is why I am asking
c# way easier to pickup
I am relatively new to game development
If youre married to the idea of using C++, might be best to learn using Unreal Engine instead
unless you need it for specific school or job, you're better off with c#
Before now the only game development I have been using has been Roblox Studio that is why I barely have experience in programming
yeah c++ aint the way tbh
you're going to have more to learn a objectively harder language
Ok I will start with Unreal and start development with Unity later
manually deal with memory management at your beginner level, going to learn twice the work just to make a game
also a language that unity does not primarily use for programming
build your own engine with Raylib πͺ
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
Why are you usinf switch when doesnt switching functions or voids?
You can just write FPSUpdate();
Just futureproofing
Saving myself like 3 lines of code for when I'm gonna have more camera modes lol...
You know what return does in youre code right?
Yeah
Becuase if Validstate is false the compailer not gonna read anymore in youre code
If there's no player to follow then I shouldn't really be trying to follow one
Ok
issue isn't related to that at all.
ValidateSelf is just a singleton helper I wrote and it'll return false if the instance should be destroyed
mistmatch between transform and physics
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
before what ?
In previous projects sorry
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
plus cinemachine brain has some options so you can switch update modes and try to match it to your needs
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?
!collab
: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
why dont u js make a channel for that its more effective
Can't answer, I'm not making the rules
the answer to that is here: https://discord.com/channels/489222168727519232/1180178376028327936
breh i wont find any that way
Not sure that asking randoms for DMs will be more successful tbh
Ookay no luck even with cinemachine
This isn't apart of my issue but yeah I suppose I could add it as a safety guard in-case anybody wants to turn enough to hit the floating point
yea but im not into that website thing
i used to do it when i was using roblox stufio
but didnt had any succses
The rules are different here - create an account on the Forums, this server is not the place for job ads
are you a genz ?
understanble
using a website has more shelf life
yea but it feels lifeless idk how to explain
It's probably has to do with the fact that this server isn't "official", it's not hosted by Unity themselves
Nope, work drains all my time and motivation unfortunately
aw understandble if u ever change ur mind pls dm me im desperate
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
If the camera follows that object, that's possible. It's called jitter though.
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?
are you sure the camera isn't falling? (:
wdym
Do you have Character controller and Rigidbody?
yeah
both components in one object(idk if its good that way)
Second person today with the same issue :p
If you want to use rigidbody then yeah, or use an existing asset/library
I've heard this is good
https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131?srsltid=AfmBOooVfDZCzUXiS68zjKLIvn2F8eav5402-Sx7uuOmI1lg2FoXk5_t
But it's also a bit more advanced
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
oh
If you do end up writing one, my main advice is that SphereCast is your friend
oh ok
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
Well yes you can use DrawWireSphere.
You could also use the built-in physics debug visualizer
If WireSphere wasn't in the right place well.. you didn't put it in the right place.
yeah I got that far lol. I should probably rephrase my questions a little. What I meant was how do I draw a wire sphere in the same place as the SphereCast.
The spherecast doens't happen in one place
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
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.
That position would just be transform.position + (transform.forward * directionLenght) according to your spherecast above.
that was my first try too but it's not it
That is, indeed, it
Something else is off if that's not working
Show your full script
nvm I may have made a mistake the first time I tried that because it work now lol.
The second one would be:
transform.position + (transform.forward * frontWallHit.distance) assuming the cast actually hit something
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
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
There's no mystery. Unity publishes a manual.
https://docs.unity3d.com/6000.0/Documentation/Manual/GameObjects.html
yeah, can check the Manual and Scripting API for GameObject or any class. all the information is there . . .
they also have a link to the C# code online . . .
You can run code without making a component.
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.
what specifically makes a "class" a component, not all classes are components, but all components are classes
Every kind of component inherits from the Component class
If you derive your class from MonoBehaviour, it is a component
Also yes that
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
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
no, there is one thread
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
so are objects updated arbitrarily?
or could you select some to run first
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.
cool, i dont think im at the stage where certain objects running first is a problem, but good to know
ah right, i mainly use java, didnt realise that colon in c# is the equivilent of the "extends" keyword
It takes the place of both extends and implements
is there anything in unity that isnt done through game objects and their components?
the stuff you create that is
ScriptableObjects . . .
Sure, tons of things
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
The only thing that is centered around gameObjects and components(aside from a few exceptions) is the entry point to your code.
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.
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
You should not "read through the 400+ classes in the documentation". The documentation is reference material. It's like the Dictionary. You don't read through the Dictionary. You look something up when you need it.
there is no reason to read through all of the documentation . . .
you will surely forget most of the things you read in the documentation when you read the entire thing
that's a good point . . .
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.
Yeah
Im only reading through to know what exists and what unity can do
The manual/documentation kinda sucks to navigate
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.
note that you should not conflate the Manual with the Scripting API
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
π¦
not sure if this is a thing in c#, but maybe you could mark the method as const?
that's a thing in c/c++
For what purpose? To denote that it doesn't change stuff inside or something?
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?
You can look into the Addressables package.
You can still reference them in inspector. Select all and drag and drop into a list or array.
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
You could automate the process.
for example?
Write a script that adds every instance of an SO to a list/array(possibly on another SO).
anyone here?
do you have a question regarding scripting?
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.
(general talk is in #π»βunity-talk )
uhh ok
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?
yes, that a method won't mutate something
it can be applied to params to say it won't mutate the param, or on the method to say it won't mutate this
I'm not sure if sealed works for methods
or final
yeah seems like it isn't a thing
https://stackoverflow.com/questions/3799062/const-methods-in-c-sharp
Aren't methods just sealed by default?
this isn't what const methods are about
const methods mean this is const within the method, not that the method is const
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
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!
sealed only makes sense if the method is virtual
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
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
Well, if the code doesn't run, then that's the cause. Are you sure OnRenderImage is something called in unity 6?
yea the code isnt running, thats the problem.
i think it is
wait, apparently for URP the onrender stuff is replaced with render passes
crap
i have no idea how to use those π€£
at one point you had no idea how to use OnRenderImage either
Read the docs, check examples. Try it out.
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();```
imma just make a new srp project i dont feel like messing around with this π€¦ββοΈ
not loaded correctly or is empty
worst thing is its working fine in editor but why
how come you're using www. ?
.ogg
What references the .ogg to put it in the build? Check the build log and see if it's listed
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
- path issue
- incorrect file format
- compression issues
these are the things that come to mind..
both paths are 1:1 idk really what happens in this case
maybe its trying to play before its fully loaded?
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
id Mute the audio vs disabling it
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
anyone could help me out with something?
not if you don't !ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #πβfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
they do.. !logs do they not?
or u just talkin about the console logs? are they not specific enuff or something?
i did ask but nobody answered so i asked again
you didn't ask there either...?
we can't help you when we don't know what problem you have
Because nobody is going to help you if you don't tell the issue
You tell the issue, give relevant context and somebody that knows an answer or wants to help will help you
maybe cause im waiting for someone to say ''yes i have experience making similar game what are your issue'' and i'll dm them
It's not realistic for someone to commit to spending time and answering your question without even knowing what you are going to ask.
You should really read the link that was send by That_Guy977
Ask your question up front, and whoever can answer will answer.
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
and i'm looking for help from someone who specifically worked on the type of game i'm working on
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
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
If only they just shared their issue, they would have probably had their answer by now
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
everything we just said still applies
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
because i want to exchange with people who has actually worked on a similar porject idk why its so complicated to understand xD
and everything we just said still applies
it doesnt but ayt
We are just trying to help you understand "i did ask but nobody answered so i asked again"
I don't see how the experience of a single person is going to give you a proper answer
Because it's not
You don't have to listen to us, but you will run into the same problem of nobody answering you again.
and you're also just, again, trying to get someone to dedicate time to you without telling them what for
i jsut want to talk with someone who is working or as worked on a similar project - thats all
that's not very respectful of anyone's time, least of all your own
idk why it is so complicated to understand
You are in a channel to ask questions and discuss anything related to general coding concepts in Unity
idk why it is so complicated to understand
and there's plenty of people here to talk with
you don't have to single someone out and have them dedicate time to a one-on-one conversation that doesn't benefit anyone else, or benefit from anyone else
there's a reason community servers like this exist
and it's not for networking
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
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
And notice how nobody is answering you because they are not interested in responding without knowing anything about the context
"anyone else" includes yourself, btw
So perhaps think about what is being said here. You're not the first person who approaches this channel like this
Also exactly the reason why sites like https://dontasktoask.com/ exists. This is such a common scenario that sites are made to explain the issue with this approach
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
i might have some question
yet again, very disrespectful of someone's use of time
because i dont care if it benefits anyone else lmao
sums it up nicely
and it goes both directions; maybe there was someone who had a better perspective, or alternate views
you'd never know lmao
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
is there another choice
(I use a processor to divide mouse input by unscaled delta time to turn it into a velocity value, so that I can use it just like a joystick input)
Always add 0.001 to the value 
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
Hey! can someone give me some references for client side prediction?
https://gabrielgambetta.com/client-side-prediction-server-reconciliation.html
I read this article on client side prediction, i understand like what this is all about but idk how do i implement all this in unity. Can someon help me please?
It really depends on which network framework you're using
netcode for game objects
ncfgo has a system called "client anticipation". Which is not a complete system, but it has the building blocks you'll need:
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/client-anticipation/
It's quite complicated to implement overall.
Client anticipation is only relevant for games using a client-server topology.
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?
yes
neat!
it's constantly evolving
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)
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
People keep asking me "Will you add VR support?" and "Will you add multiplayer?"

I'll do splitscreen
Splitscreen and hamachi - best networking solution
uhhh - sure - idk
Hamachi was the classic way to get your Minecraft server working tho
I'm just a lowly programmer
it's a VPN (like, an actual VPN, not a proxy)
I think there's some tool to tunnel inputs over hamachi my friend was using for PlateUp a while back
I could be misremembering
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.
Directly reference them in the inspector and subscribe in OnEnable
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
How to directly reference components on a different game object?
Also the overhead of needing to do 60f * Time.deltaTime but I made a helper method getDeltaTimeInTicks for that
You either rewrite the code to be framerate independent or you use FixedUpdate
I want to do the former
Drag them into the slot in the inspector
MoveTowards would make sure the result is always exactly 20
You will still get different total amounts of rotation, though.
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
it's extremely simple
you're already calling into huge amounts of functions you "can't see" π
this.gameObject is vastly more complex
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
just drag the entire game object in
Unity will find the component
You can also right-click on an object in the hierarchy and hit Properties
this will open another inspector
Dragging the GameObject into the slot for the component type will result in a reference to the specific component.
You don't need to drag the specific component.
I still would like to know the logic behind it, in this isolated example i'm not concerned with any of that
But yeah it seems pretty simple
Does that just cap it if it goes over the provided max?
Right
If you're close enough to the goal, it returns the goal
Otherwise, it moves closer to the goal and returns that
That sounds good, so wdym by this?
I presume that you're spinning something using logoRotationSpeed
yeah
If the game is running at exactly 60 FPS, then your total rotation will be
Thank you and @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
sigh.. it so complex i gdont get it
https://unity.huh.how/lerp/wrong-lerp
This explains a very similar problem
trying to port framerate-dependant code to be not framerate dependent
In this case, it probably doesn't matter at all
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
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
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?
oh yeah -- Mathf.MoveTowards or a clamp will both ensure the final value is exactly 20
rotation of 20.3333 would add up to rotate faster over say, 10 seconds than 20f would
Yeah, I used to make that mistake a fair bit
so the invariance is how fast it takes to reach it
right
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
I use 0.3333 as example since that's the default maximumDelatTime
From what I've seen, it never ever does. The FPS is really an engine tick delta time and the float can't give you an exact 60 FPS delta time: 1000/60 results in a delta time slightly off 60 FPS at like 59.97 or around that much. Then, of course, the software and hardware timers tick at a rate, so that furthers the error.
Yeah, this is a "spherical cow in a vacuum" scenario
Breaking away from framerate dependence can be very hard!
Yeah but... not using time.deltatime in calculations assures it will be at all the same values
Especially if you have very specific behaviors you need to preserve
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
In that case, you're good π
I will keep physics entity stuff in fixedupdate and interpolate them there
I think that's the way to go?
Yeah, physics will wind up being fixed anyway
Zig pseudocode of what I am doing to make it framerate independent:
And you could absolutely just do everything in FixedUpdate. That's how I'd implement a fighting game that's all about exact frame timings
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
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
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 !
Anyone know how to make a NavMesh agent jump? It seems to be locking the Y and negating anything I do with the Rigidbody...
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
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
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
how many raycasts would be ideal?
the raycasts would fire out of the edges of this circle
no idea! definitely make that something you can configure
What's the goal here?
Thanks. I think that's working. Just need to get the jump logic right now
there's objects which fall, and im using this to get what angle the object should fall
the reason i want to get multiple angles is because i will average them
okay sry didnt knew there was a tab for that
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);
Is there a reason you're doing this on 0.3 second intervals?
The answer is going to be "don't do that" :p
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Vector3.MoveTowards.html
you could probably lerp it as well
I bet you're doing a coroutine that yields a WaitForSeconds
which'll make this framerate-dependent
How can I make these two stroke materials not be saved?
Are you running this code in response to OnDestroy, perhaps?
(or otherwise running it outside of play mode)
this can cause issues if you're exiting play mode
Yeah, its specifaclly set to an equating depending on a set BPM, in this case 180
Thanks!
It's invokerepeating actually, coroutines kinda confuse me
InvokeRepeating might be more reliable at least
I'd hope that it prevents errors from accumulating over time
It does not, at least for now but we'll see
I wouldn't be suprised if i need to change something later
Help guys
Wdym saved? You mean instantiated?
Using the materials property will instantiate the materials
Yeah I dont think I know what you mean, clarify please
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.
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
Shouldn't you assign the materials back to all renderers, not just one?
You used GetComponentsInChildren in StartRackMovement, here you are just using GetComponent
good
Mate add some context when you send me a screenshot
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
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
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?
You can add [field:SerializeField] attribute
field: makes it target the backing field
help guys please
For this one, I don't think so public Vector2 Size => _rectangle.Size
using field in the attribute worked
Why did you change your StartRackMovement code to this?
Renderer[] childRenderers = rackToMove.GetComponentsInChildren<Renderer>();
if (childRenderers.Length > 0)
{
originalRackMaterials = childRenderers[0].materials;
}````
ah, fair enough
I probably wouldnt want to show any of my getters in the inspector anyway
Stop bumping your question if you wont' stick around for clarification.
okay
well, what's a RayTracedMesh?
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?
im trying to send data to a fragment shader
imo im not sure computebuffer is the right thing, i think it is
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
will this still work so that i dont have to like... hardcore everything that is raytraced?
are you going to put an entire mesh into this thing?
I don't think marshalling is related to sending data to a GPU...π€
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
this is the whole bit
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.
Ah, you're using it to get the stride of a mesh? That's a very weird thing to do.
i started using StructuredBuffer recently to send a bunch of structs to a shader
if im being completely honest i have no idea what im doing, im just kinda pinging from multiple online forums
i forget if I used sizeof or just hardcoded the size of the struct
that's going to make this quite difficult :p
i said it earlier, but im trying to not have to hardcode each shape to raytrace. can i still do that with structs or?
Just how many shapes do you have?
What kind of data is it? What does RayTracedMesh contain? Does it inherit from anything?
currently, no. thats probably the problem, right?
im wondering if structs will still work, so imma just look it up rq
you should probably start with some basic compute buffer usage
literally just giving numbers to a shader and having it add them for you
idk why i didnt π€£
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
According to this error, there's something inside of that type that is getting in the way.
its inheriting monobehaviour, and it has the start and update functions. i havent touched it yet
You can marshall classes, if all of their members are primitive data.
Ah, okay, that makes more sense.
Ok, that's the issue then.
I was starting to wonder if I was in the wrong there :p
is it not allowed to inherit monobehaviour?
No.
oh
MonoBehaviour is a lot of stuff. A lot of managed stuff too
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
(but this ain't happening)
Try it. Color is a struct so it might work.
same error
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
see here
ill search about that too
i mean, that's not really something you'll search up
Are you sure
oh wait lol
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
that sorta fixed it
sorta
the error is gone
new error π€£
Hm... Maybe not.
Ah, indeed. That.
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
wait what
Yeah, so it would have to be a struct.
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
It's actually more uncommon to pass custom data to a non compute shader. But yeah, the rules are simple: the buffer elements need to be structs or primitive data types.
could i have one array for positions, and one array for colors, and pass those to the shader?
You can. Or you can have a structure that contains both.
i could have a struct, but can i use them and not have to hardcode each position?
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
Wdym by "hardcode each position"?
Surely you can set it up in a way where you wouldn't need to hardcode every case.
right now i code each object and their positions and colors within the shader
im trying to not do that
That's definitely sounds inefficient.
Then don't do that.
im trying to figure out how to not do that
and do it another way
i can see now my original way wont work
@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.
I have a struct in my shader called "Sphere"
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
Yeah, so basically, you'll need to get the data from the scene, put it in the buffer and use in the shader.
Indeed.
Look at the stuff in your scene and fill a buffer with data based on that stuff.
since my list is now of a struct containing position, color, and radius, i cant see it in my editor which is fine. i thought i could just add a new mesh to the list in code if there were more RayTracedMeshes than meshes in the list, but its not working
You can make it serializable and expose as a MonoBehaviour serialized field.
i mean, i also need it to be a static list to access it from other scripts
Yeah, it wouldn't work and even if it did, reattaching requires a whole separate data structure to cast rays against. A regular mesh wouldn't work.
Expose it as a list then. Whatever way you prefer.
"mesh" is the name of the struct, and the rays being cast are completely within the shader if were talking about the same thing
Don't make it static. Make it an instance list on a singleton.
I'm talking about meshes in general. If you would want to render anything besides spheres at some point.
oh yea
Singletons can work anywhere. It depends on how you implement it.
im gonna be working specifically with spheres for now, future me can worry about actual meshes π€£
oh thats good to know
I have [SerializeField] behind it but its still not visible in-editor
Structs need to be marked with Serializable attribute
oh
thanks! now all i need to do is properly add it in the shader
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
Does the log print outside of play mode?
yep
its not a big issue atm, just would be nice if it were fixed
oh and btw
Are there errors then?
its sorta working
Well, then fix the error, and it might work.
there isnt any errors
Then you'll need to share more context.
oh okay i found an error
the singleton isnt working in edit-mode
im sure im doing it right
Does awake run in edit mode?
i think, ill try using start instead
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.
Make sure you don't have an infinite loop in your shader.
Or out of bounds access.
everything else in the script runs in edit mode, its just the awake thing i think
yea imma check rq π€£
i havent saved in like a solid hour
Add logs or breakpoints to confirm this kind of guesses.
Assets should be fine. It's only the scene changes that you'll lose. You can also get the scene backup.
oh wow
i thought everything got completely reverted if unity crashed
Only stuff that is not saved.
the entire project is gone ππππ
nvm it just didnt get put into unity hub, i found the files
my first unity jumpscare
I FIXED IT
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
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?
Since GameManager is a Singleton you could add static methods for SetData and GetData, similar to PlayerPrefs, and then it's just
GameManager.SetData("myKey", myString);```
I'm curious with how you've put properties into your singleton class, to make it feel like it's getting out of hand.
Is it just a case that you've got a class with say one giant list of
public float myFloatOne;
public float myFloatTwo
...
...
public float myFloatTwentySeven;```
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
I'd say there are 2 approaches (maybe they overlap, I don't know :D):
- 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)
- you make 2 "functions" one is
CreateObjectsFromDataand the other isGetDataFromObjectsand then make anISaveableinteraface 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 π
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
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
This is a great way to do it
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?
you should probably implement the save load of these on some manager that can instantiate them, not on the objects themselves
I'm sure there's some similar thing to Awake() when a scene is newly loaded
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
thanks guy. im working on it with clearer ideas
how do i restart a particle system to be able to call Play on it again
you are allowed to reference the documentation yourself
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/ParticleSystem.Play.html
.Stop() followed by .Play()
tried tjat
didnt work
one guy on SO said time=0
didnt work either
another to slap a Simulate witj dummy vars
I very much doubt the documentation is lying
i just know that ```
confetti.Stop()
confetti.time = 0
confetti.Start()
only works once
that is not .Play()
and that the code immediately preceeding it is exec'd jusy finr
Well, come back when you are actually next to the project open and ready to debug
Try with a new default Particle System to see if the problem is in your code or in your particle system setup
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
you can't write classes that have a variable number of generic parameters, so you'd have to have a separate definition for each one
// 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
Add some logs to the code.
what kind
i can visually see it gets to load_map from the visual effects it performs
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.
(the second time is because i triggered this two times)
There's something really wrong with that screenshot.
manjaro hates me
its about as readable as a 2010 captcha
irrelevant, if you come here for help then YOU need to make sure you provide usable information
heres the second and third try
is this enough for "this is the best i can give"
what do you think? Could you work with that?
yes
then do it coz I'm not going to expend the effort
then dont
How are you taking the screenshot? Are you on windows?
all its showing is stuff that was already established
fork of archlinux
(terrible, ik)
some built-in* stuff, what program exactly is it using idk
Let's assume there's no issue and the log prints every time the particle system is supposed to play.
What about looking at the inspector? You should be able to see the particles lifetime if you select the object.
I'd also check if the reference in the script is referencing the correct object.
And that there are no errors.
probably looking at the wrong thing but all its showing me is the particle var setup god sheet
oh wow it actually made a good csreenshot this timethis stuff?
oh
Well, there you go. Probably were looking at the wrong place
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
Must be some parameters/settings getting modified
prolly
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
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.
[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
!code. use a paste site please
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Why is [SerializeField] private int[] _gridMap; showing up in the Inspector as a List?
arrays and lists statically are pretty much the same thing
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
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
Arrays have a specific size at runtime
But you can re-assign the field whenever you want (or use the Resize method https://learn.microsoft.com/en-us/dotnet/api/system.array.resize?view=net-9.0 )
i dunno exactly what Unity does when applying serialized properties
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?
efficient querying and retrieval
Depends on your query and retrieval patterns
but essentially, a tagging system, indexed on whatever you will query by.
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?
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
also make sure Jump is being called
you could try adding a debug log to make sure it is
player wont move any ideas why
Probably jumpPower is 0, or the mass of the object is two high,
OR
You have other code elsewhere that overwrites the velocity
OR
Your Jump code is not running at all.
There's nothing in here about an animator
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?
of course
vertical * moveSpeed this will be your new vertical velocity after that runs
i always manage to miss these thingsπ€¦ββοΈ
overwriting anything that was there before
Thanks for help!
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)
}
}```
"loaded" does not mean GetComponent
try adding logs inside Garden's Awake as well, before/between/after the GetComponents
its not a problem about getting the Size property to be accessible in my Grid, its just that Grid is going to use the Size property to construct an array
issue is that Size doesnt get a chance to be set before anything can use it
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
it might be me, but it honestly feels really frustrating that you cant construct MonoBehaviour classes like a normal class
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
you could use Start instead
you can, you just use AddComponent instead of new()
It does so because you've added these two components to a game object somewhere in your scene
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
script execution order
GetComponent does not call awake under any circumstance.