#archived-code-general
1 messages ยท Page 418 of 1
in normal game development, you'd just...add the dependency
Note paths are relative to the executable so maybe you made a mistake there
But as per the rules we can't help you further when modding is involved
Even Bepinex, even if the game allows it I believe
Is there any way to make a world-space canvas only render to a certain camera without using layers?
probably not
turn it on and off
Depending on the render pipeline, how you do this will vary
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/MonoBehaviour.OnPreRender.html
This is used in the BiRP
For scriptable render pipelines, you'll use https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Rendering.RenderPipelineManager-beginCameraRendering.html
so, you'll react to each camera being rendered by either enabling or disabling the canvas
Doesn't work, the render calls are issued before those callbacks are executed
oh, yes, it does help to read the documentation...
Unity calls OnPreRender after the Camera performs its culling operation. This means that if you make a change that affects what the Camera sees, the change will take effect from the next frame. To make a change to what the Camera sees in the current frame, use MonoBehaviour.OnPreCull.
(this is for OnPreRender, not for the SRP's callbacks)
oh no it don't
- Using URP
- There's no pre-culling callback for SRPs afaik. I tried using RenderPipelineManager.beginCameraRendering before something where and it doesn't work. Disabling canvas, disabling the object itself, doesn't work.
- I'm 90% sure the draw calls are prepared for the canvases really early on, at PostLateUpdate, unlike all other types of renderer, and any camera callback happens before rendering, too late to change what's already been prepared.
I was jabbing at myself there :p
Does disabling other kinds of renderers work with beginCameraRendering?
or is it a complete bust for everything?
:<
Why are canvas such a black boxes
Disabling individual Canvas Render is a bust, will disable it for all camera.
oh, I meant to turn off a mesh renderer, just as a sanity check
Ok guys so il ltry to do the github tommorow. but for now ill try something different.. So the problem is taht he cant see my projects while he is on my acc. Is there a way so he can see it? do i need to send the file to him and how?
this is not a code problem
mine btw
@thin aurora @rigid island
wrong channel. Also I dont use UVC so no idea
ah, that's a static event
Just checked, disabling other renderer doesn't work that late. Needs to happen before the resident drawer stuff I'm guessing?
Probably won't let you toggle stuff per-camera
That's just an event for the canvas itself :(
(but maybe it gets invoked once for each camera?)
oh which channel should i use?
there's also preWillRenderCanvases. very funny.
probably #๐ปโunity-talk
thanks
Perhaps; I don't know much about that system
Yeah me too.
Looks like Canvas is a static event that happens once for everything :L
Aight thanks for trying :<
!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
Do you guys know any way to detect whether a UI element is over any other UI elements and how to tell which one it is? Example in screenshot being the reticle being over that white square. The reticle can move, so I want to tell which white square it's over.
use the event system to raycast against the UI
I'm having trouble downloading the Google.Protobuf namespace for C#
how do I do that?
private List<RaycastResult> GetUIElementsUnderPoint(Vector2 reticlePosition)
{
List<RaycastResult> results = new();
PointerEventData pointerEventData = new(eventSystem)
{
position = reticlePosition,
};
print("Reticle Pos: " + pointerEventData.position);
raycaster.Raycast(pointerEventData, results);
return results;
}
This is the method I'm using
actually
how do I make a package which is working for the project folder, to work inside unity?
And then I'm getting calling the method here. However, it returns no elements.
List<RaycastResult> elements = GetUIElementsUnderPoint(targetRectTransform.anchoredPosition);
what is raycaster here?
It is a GraphicRaycaster on the canvas
why? just use the EventSystem
I changed it to this, and same result
if you have more than one canvas in your scene then using a specific GraphicRaycaster won't be sufficient, using the EventSystem will raycast from all of them
okay, now explain what is not working how you expect with this because you've provided literally no useful information
๐ฎ
Lol well it's still returning no UI Elements
The reticle I have on my UI is over an element, but it's not picking anything up.
Here it is clearly over the element
and what debugging have you done for this
I have tried different types of raycasts now, I've printed out whether there is elements or not in the list, and I've also swapped out the event system variable to EventSystem.current
It seems like you are working around the eventsystem. You just want to get the current selected object?
consider drawing a gizmo where the anchoredPosition of targetRectTransform is to make sure you are actually using the position you expect to be using
I just want to see what other UI elements are below my reticle UI element
Ok, good idea I'll try that
And the reticle is on mouseposition? So you just want to get the current hovered or do you want to have objects below that active one?
No, actually the reticle is adjusted using physical levers within the level. It just reflects the changes on the UI. It adjusts the anchored position on the UI. So in this example, I am over a certain white square with the reticle, so I want to be able to identify which square the reticle is over ๐
I'm making a game that has 2D characters in a 3D world. What's the best way to place sprites/images in world space knowing they will use a billboard effect?
Should I make a separate world canvas for each character?
(could not find the right channel to post this)
Oh okay, got you. I agree with boxfriend to do some drawline debugs to check, if you really shooting in the right direction
I'm looking for some help with Zenject. Is this the right channel for it?
!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
more like, it's not a Unity specific issue, but one for a commonly used package for Unity, hence the question ๐
Still no question to be found yet to determine if its related or not ๐
I'm currently playing around with Zenject because I think dependency injection would solve quite a bit of my hardcoded dependencies.
I got it to work in a test project, it went fairly smoothly, but I don't understand when and how it actually does the injection. A regular program would inject everything before actually running the app, but Zenject needs to do some voodoo magic to get it to work with Unity.
The git/asset store page seem to imply that you can also inject at runtime because of it, but I am struggling to get this to work.
Could someone explain how I could achieve this?
Not answering your question here, but just be aware Zenject has not been updated in quite some time, like years at this point
I know, and I'm currently using Extenject, but that was updated in 2021 or so
I personally wouldn't use something not actively maintained that is so deeply embedded in my architecture
do you have a DI tool you'd recommend otherwise?
No but I wish I did tbh
singletons ๐
cuz like I said, I did some testing, but haven't incorporated it yet
I'll eventually bump into something where I wish I had more elaborate techniques
VContainer seems to be actively maintaned but I have not used it myself
yeh, its latest update is from dec 24
honestly, VContainer might just do what I need as well.
gonna read up on the documentation some more
I was trying refactoring my game into dots for entity from regular mp and made new branch for it. I gave up after awhile and now when returning to the old branch, all my scene hierarchy objects are gone... I can only see old scripts, is there a way to fix it ?
this?
did you close unity before switching to the old branch?
yes both vs code and unity
probably delete the library folder too
anything else ?
did you try it after deleting?
... is your working scene called "untitled"? Dont think so
no.. here is an older screenshot I found
Open the correct scene! If you reset unity or branch, unity does not remember the last opened scene... just open the correct scene
omg, so unity creates whole ui and all game objectes in a file called scene thats whats it for
I can actually create then different ones for menu adn not put everything in one scene
I found it ty I am so dumb
I highly advice you to go to !learn and go through pathways or basic tutorials to understand, whats happening
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
ty I will check out some guides, it rly feels like I am going with my head through stuff sometimes
I have an editor tool (super huge, not made by me) that consistently crashes unity 6.
The problematic function is this (look screenshot below), although obviously it's not the full code. Specifically running the ShowAsDropDown function crashes unity. There is nothing after that line, in the tool. The class here is EditorWindow, which is opened from within a PropertyDrawer.
Anyone has any clue where to look?
Inside editor log, that's all I get regarding the crash:
Obtained 22 stack frames.
#0 0x005fb67436071c in burst_signal_handler(int, siginfo_t*, void*)
#1 0x00741d43f191d0 in (Unknown)
#2 0x00741d40e2b14d in (Unknown)
#3 0x00741d3f6b3943 in (Unknown)
#4 0x00741d40e4c15e in (Unknown)
#5 0x00741d40e1a490 in (Unknown)
#6 0x005fb6749c5fe9 in PresentContextGL(ObjectHandle<GraphicsContext_Tag, void*>)
#7 0x005fb674a03592 in WindowGLES::EndRendering(bool)
#8 0x005fb675d28edb in GUIView::OnInputEvent(InputEvent&)
#9 0x005fb675c8dc66 in GUIView::ProcessInputEvent(InputEvent&)
#10 0x005fb675d27fcd in GUIView::DoPaint()
#11 0x005fb675d2a1ee in GUIView::RepaintAll(bool)
#12 0x005fb6755f7d99 in Application::TickTimer()
#13 0x005fb675cffe9e in MainMessageIteration(void*)
#14 0x00741d446de559 in (Unknown)
#15 0x00741d44741257 in (Unknown)
#16 0x00741d446df287 in g_main_loop_run
#17 0x00741d44be4d7f in gtk_main
#18 0x005fb675cfe2dc in main
#19 0x00741d43f01e08 in (Unknown)
#20 0x00741d43f01ecc in __libc_start_main
#21 0x005fb673bb9029 in (Unknown)
Launching bug reporter
I'm not very experienced with editor tools, and the person who wrote this enormous 1000+ line tool is not at the company anymore, so I'd appreciate anything
What is ShowAsDropDown doing?
Beyond that, I know as much as you, friend
Ohhhh, progress! Turns out the issue is inside CreateGui actually, and it's within this rootVisualElement.experimental.animation.Start block... somewhere
I should mention everything worked on 2022.3, but unity 6 is clearly problematic
yupp, removing the line fixes the issue. Any idea why this crashes unity so insanely hard? I recognize this is an experimental package, but damn, didn't expect that
are you sure you are on latest versions of packages? Because "experimental" is already a bad namespace to hope for working
yeah, the issue started when upgrading from 2022.3 to freshest unity 6
no relevant packages to update, it seems
Depends on your unity version
https://docs.unity3d.com/6000.2/Documentation/ScriptReference/UIElements.IExperimentalFeatures-animation.html check the dropdown top left for supported versions
seems like unity 6 is supported, just like 2022.3
unity 6 beta and alpha I see here
Ah and 6, still confused by this dropdown filtering out the current selected ๐
can you try to debug log your values and see, if you are just missing some value somewhere?
what would you suggest?
what you just replied to ๐
simply running the RootVisualElement.experimental.animation.Start crashes unity HARD. I'm not able to get a debug out, and I have no clue what I'd debug out anyway
you can see pretty much all the values in there anyway
Just wondering about the values being used like TargetHeight
you can find targetheight in this screenshot
in my original message
And is it value valid? Also, can you try to just run any other public method of animation?
it is valid, because it's used for the height of the dropdown, and it works without the animation
this worked, if that's what you mean
so simply creating the animation object doesn't destroy everything utterly
for testing, can you remove the onValueChanged method and see what happens?
yeh, not a number will def. kill stuff expecting a number
this worked
surprisingly so
I would debug log that onvaluechanged values instead of using them. Just log and see, what you get
What do you expect assigning minSize/maxSize to do
I said it's not my tool
I know as much as you do mate
the person who made it left the company
Well, as you are using it and its not supported anymore, its yours now ๐
so, you're suggesting they not assign minSize and maxSize, right?
Well you have rest of code
instead of assigning, I debugged it, here's what I got
the size variables looks like just local or instance variable or something
so the onvaluechanged callback and the animation start is working
I assume, TargetHeight * Time, which might be 0 on start could kill the rendering of the elements
so, notably, it didn't segfault!
That does sound plausible
I sent the full debug log of it
first call didnt have 0
What exactly did you log?
I doubt that would do anything? ๐ค
I added that + Vector2.one*0.01f as an experiment if minsize == maxsize is the reason
That's just defining the possible size of editor window
sure as hell crashes unity lmao
it sounds like this is making the window resize to match the size of the root element
At least it's likely expect you to do something with element there
which shouldn't cause a segmentation fault, notably
could you just hard code the min amd maxsize to 100 and see, what happens?
@wintry crescent
that's what I'd do next
works
doesn't crash unity
Unity may just not doing anything when value doesn't change
okay, next thing I would try. Create the vector2s outside of the animation.start function and just overwrite the x and y values and assign the vector to the min and maxSize
I wonder if TargetHeight is going to some bonkers value (such as NaN) because it depends on the size of the editor window
there was a mystery NaN earlier
not from the logs earlier. Numbers went up and done
Debugged out TargetHeight * time
right, but you aren't setting the min/max sizes there
otherwise the editor would've crashed
i guess there wasn't a crash there, though
Oh boy...
You are creating a min and Maxsize of the same size. Leaving 0 or NaN space left
just for testing, could you just add + 10 to maxSize?
that doesn't make sense -- those are the size limits of the window
if they're the same, then the window has a fixed size
I imagine this creating some kind of quad with minSIze being top left and max being bottom right. If you are bringing those to the same points, they are leaving no space. Is that wrong?
this does not crash the editor
So your sizes cant be of the same size I guess
FRIENDS YOU WILL NOT BELIEVE THIS
THIS DOESN'T CRASH THE EDITOR
but this does
haha, so maxsize before minsize works? That is def. a design flaw in the system ๐
yep XD
great ๐
not sure what you expected there lmao
I just wanted to prove me wrong ๐
well, Id say, write a bug ticket for this, as this does not seem right to me.
I can't cause a crash just by setting the sizes
are you on Unity6?
can't be bothered tbh, I'm really tired and going to sleep now, and by the time I wake up I'll forget
i'm trying various combinations of sizes
Well, disappointed but you do you
I have a backlog of like 3 unity bugs
that I have to make a simple project that replicates them
and report them to unity
but it's soooo muuuuch woooork
i've gotten a few weird graphical problems fixed
well, im out of this conversation
How is this the case, isn't this just variables being captured in a lambda? Like that's normal C#, how is that causing a crash by swapping the order?
probably properties not variables
overriden getter/setter
it's odd to see burst_signal_handler here
Ah lol
Good question and for sure a bug. Dont understand it myself but i guess its something unity will have to address
I wouldn't expect Burst to be involved..
So simply setting minSize bigger than maxSize cause crash?
Not related to animation I assume
it's not the size, its the order, setting minSize before maxSize in the lambda seems to cause it
I still guess, the multiplication of 0(time) on minsize crashes it
if someone can replicate and report that bug, I'd be eternally grateful
but I am going to sleep
looks like it require minSize to be set first and the maxSize seems to be property that use minSize value which defaults to 0 and cause problems?
time is never 0
debugged it out and checked
I mean it seems like on the moment minSize get bigger than maxSize it would crash
If you set maxSize first, maxSize remains bigger
Good call there. That might be the issue
no it doesn't, it's normalised time between 0 to 1 start to end of animation, as far as I can tell
and it just doesn't call on t=0
cathei already might have the right answer. you set first minsize and then maxsize. And somehow, for whatever reason, it does not like minsize being bigger than maxsize probably
nah, its soooo muuuch wooork ๐
and that's understandable!
;D
anyway, goodnight ^^ ping me if anyone here submits a bug report pls, so that I'll know to not do it if I somehow remember tomorrow
good night there
If Unity were to solve this, it seems like they need to cache the property sets and apply them in the correct order after the lambda executes
That sucks to implement on their part honestly
..Or they could adjust maxSize when minSize set to bigger size
And vise versa
I doubt that animation features are intended to use with those properties anyways
Yeah true
I was unable to cause any crashes even with minSize exceeding maxSize
Sorry, I just could not reproduce the issue. This one does not crash at all
using UnityEngine;
using UnityEditor;
using UnityEngine.UIElements;
using UnityEngine.UIElements.Experimental;
public class AnimationEditorWindow : EditorWindow
{
static AnimationEditorWindow window;
[MenuItem("Window/Animation Editor")]
public static void ShowWindow()
{
window = CreateInstance<AnimationEditorWindow>();
window.ShowAsDropDown(new Rect(100, 100, 100, 100), new Vector2(500, 300));
}
private void OnEnable()
{
VisualElement element = new VisualElement();
element.style.width = 100;
element.style.height = 100;
element.style.backgroundColor = new StyleColor(Color.cyan);
rootVisualElement.style.backgroundColor = new StyleColor(Color.yellow);
rootVisualElement.Add(element);
ValueAnimation<float> animation = rootVisualElement.experimental.animation.Start(
0.0f,
1.0f,
550,
(element, time) =>
{
window.minSize = new Vector2(20f * time, 20 * time);
window.maxSize = new Vector2(10f * time, 20 * time);
}
);
animation.Ease(Easing.OutBounce);
}
}
Guess there is something going on with the rest of this system or a personal bug ๐
Maybe a problem in a runtime panel, but that is a guess
is there something about using SetActive that might be causing this "blip"?
its very brief but the lightning arc appears out of position momentarily when activating it
the lag spike?
weird
check the unity profiler
there should be a spike and u can see what it is
if its consistent that is
no spike this time
think it was just obs lagging for a sec at just the right time
is it just not updating its local position in the parent while inactive or something?
what's the difference between this and just having the while loop on top? i've never seen this before
do while runs the content of the loop at least one time then checks the condition and breaks the loop once the condition is false
you've never seen a do while?
nope. first time i've seen it
Does anything set the position of the lighting object?
k, thank you. seems like it could be useful at times
nothing is setting it in code that i know of
yeah while loop can be skip entirely if bool isn't true, the do/while running function inside at least once opens more options
i dont think you need SetActive at all here. if you make the prefab active than it'll be active when instantiated.
Is it a particle system?
the problem is that the lightning effect is briefly appearing in the wrong place
Depending on execution order, this could mean that you see the wrong points for one frame
could try that
especially if the line renderer is set to use world space
Can you manually cause the Lighting Bolt Script to update?
possibly!
actually, I'd just have it update itself in OnEnable
it has a "manual" mode too
time to see if theres docs (not getting my hopes up)
ah yeah take off world space and use hard coded vectors it works
thanks all
That sidesteps the issue entirely
yep!
Asking this here because I think it's more of a coding problem then a UI one:
Currently, I have a dialogue system where a letter is added to the string of a text object every frame. however, this causes an issue when you get to the end of a line while in the middle of a word. The word will start writing on the original line for a few frames, then switch to the next one once it runs out of space. I tried to fix it with manual line breaks, but they look sloppy and I can't use them with the justified style. What can I do so the letters fill in exactly how they appear in the end without changing the spacing during the animation?
the way I want it to look the whole time:
the way it looks during the middle of the animation before the spacing changes:
instead of adding text, you can animate maxVisibleCharacters
I just started getting this error transform.position assign attempt for 'Player' is not valid. Input position is { NaN, NaN, NaN } after I moved my ledge climb to a coroutine.
private IEnumerator LedgeClimb()
{
grabbed = true;
playerMovement.RigidBody.isKinematic = true;
currentClimbSpeed = climbSpeed;
currentClimbDistance = Vector3.Distance(this.transform.position, climbDestination);
while (currentClimbDistance > minClimbDistance)
{
playerMovement.isGrounded = false;
this.transform.position = Vector3.MoveTowards(this.transform.position, climbDestination, currentClimbSpeed * Time.deltaTime);
currentClimbDistanceProcentage = 1 - currentClimbDistance / climbDistance;
currentClimbSpeed = climbSpeed * climbSpeedCurve.Evaluate(currentClimbDistanceProcentage);
currentClimbDistance = Vector3.Distance(this.transform.position, climbDestination);
yield return null;
}
grabbed = false;
playerMovement.RigidBody.isKinematic = false;
playerMovement.RigidBody.linearVelocity = Vector3.zero;
}
dammit
I solved this by adding a rich text thing that made the characters invisible until the right time
that would've been so much easier
climbDistance is probably going to zero
where does that get set?
or is that a constant?
ahhh that's what I messed up. I set climbDistance before I start the coroutine but I must have removed that by accident.
Those errors about NaNs can be really annoying
you don't get a stack trace; I think it catches the problem later on
yeah I don't remember ever getting one before, they are very unclear in what it wanted from me. when I double clicked on it it also send me to the line above it. The Vector3.MoveTowards one, which didn't help
I'm back, with more questions 
I'm having some issues when it comes to moving my player up and down slopes. My player hovers slightly off the ground to make moving over small bumps smoother but as soon as I walk up a slope the player gets pushed into the slope instead of neatly going up it. Even though I use Vector3.ProjectOnPlane() the DrawLine even shows the normal of the force correctly, but the player is still pushed against the slope instead of up it. https://gyazo.com/eda0309a9fd16b23422e9c8de943afd5
Relevant PlayerHover Code ```C#
onSlope = Vector3.Angle(Vector3.up, groundHit.normal) != 0;
slopeAngle = groundHit.normal;
`Relevant PlayerMovement Code` ```C#
if (playerHover.onSlope)
{
velocityChange = Vector3.ProjectOnPlane(velocityChange, playerHover.slopeAngle);
Debug.DrawLine(this.transform.position, this.transform.position + velocityChange.normalized, Color.red, 5f);
}
ForceMode forceMode = isGrounded ? ForceMode.VelocityChange : ForceMode.Force;
rigidBody.AddForce(velocityChange, forceMode);
are u applying extra downward force?
No, in this instance of going up a slope I should be adding upwards force through PlayerHover.
if (playerHover.onSlope)
{
velocityChange = Vector3.ProjectOnPlane(velocityChange, playerHover.slopeAngle);
// small force upwards to counteract being pushed into the slope
velocityChange += playerHover.slopeAngle * 0.2f;
}
ForceMode forceMode = isGrounded ? ForceMode.VelocityChange : ForceMode.Force;
rigidBody.AddForce(velocityChange, forceMode);``` idk my best gusse lol
that works kinda, though if I now stand still on the slope I slide down it. which is..... weird. Also this makes going down the slope worse.
cuz gravity is still acting on the player and its still not working for down?
{
velocityChange = Vector3.ProjectOnPlane(velocityChange, playerHover.slopeAngle);
if (rigidBody.velocity.magnitude < 0.1f)
{
rigidBody.velocity = Vector3.zero;
}
}``` this should work
No that's not why it happens, my player hovers above the ground so slopes have no effect on it. the thing that makes the player slide down the slope now it the velocityChange += playerHover.slopeAngle * 0.2f; because it will always add a force in the direction of the slope normal, so that way.
Without the velocityChange += playerHover.slopeAngle * 0.2f; the player stays on the slope just fine.
no worries
gusse i have much much more learning to go lol
oh hard same
although most of c# is pretty simple jus math i cant do or vectors
If I want to make a grid system on an Uneven Terrain for Tower Defence, how would I proceed?
or anything that deals with math vectors and moving stuff using math
ig ill jus have to go watch this 2 hour long video on them ๐๐
yea my mind cant handel that for 2 hours id go play a game or sum shi ๐ญ
i have a question, how does subnautica remove bits of water from the sea when the player makes rooms?
try out 3b1brown and Ben eater
It doesn't. There's no such thing as bits of "water" in games(unless they run some kind of realistic water physics simulation). There's probably just a post processing effect applied to the view from the window.
when ur in the water u can swim
So, they use triggers or colliders to define water. When you add a room, they either remove a water area trigger or add a non water area trigger. The rest is pure logic in code.
It could be a bit more complex than colliders. They might be keeping a spatial data structure that defines the type of areas in the game or something like that. The concept is the same as with triggers though.
That's just a guess though. There are many ways to implement the same thing. No one would be able to tell you without seeing the game source code(aside from maybe the devs).
Pretty sure it's the opposite. Everywhere is water. They define "not water" areas inside of it
When you're in an "air" trigger, you can walk. Otherwise, you swim
Yeah, that's just details of implementation
They ship buckets out to other games
if u instantiated a prefab under ExecuteInEditMode , but u wanna connect it back to the prefab, is it like this?
GameObject spawnedObj = Instantiate(prefabs[0], transform);
PrefabUtility.RevertPrefabInstance(spawnedObj, InteractionMode.AutomatedAction);```
did you read what that method does? because no, that would not be it. but you're on the right track, double check the PrefabUtility class
okay
it seems i did not.... ๐คก
i found instantiateprefab
but it needs to be spawned inside a scene right?
the script im working is an automated script designed for making prefabs
if you want to save a gameobject as a prefab asset there is the SaveAsPrefabAsset(AndConnect) method, if you want to connect a prefab instance in the scene (like one you instantiated) back to the original prefab there is ConvertToPrefabInstance
ohhhh ty๐
I have a method call like this one
EventBus.InvokeEvent<TimerEvents.TimerPauseEvent>(new(pauseTimeLeft));
what would it take to get rid of the new keyword entirely, and just have the pauseTimeLeft as a parameter?
oh, I should mention - the parameter of InvokeEvent is of type T, that is specified in the <> brackets
hence the option to have an implicit "new" there in the first place
and since it can be implicit, it could potentially be gone... too? maybe?
Pass in an existing object of that type.๐คทโโ๏ธ
I assume pauseTimeLeft is just a float?
๐ญ that's precisely what I'm trying to avoid
yes but it can be anything for different events (aka different T)
I wanna have LESS typing not more ;P
Well, you can only pass in an instance of T.
Just how lazy are you?
You could implement implicit conversion of float to your parameter type.
Though it's gonna be more typing
what if I have an event that takes in 2 parameters, though
in the constructor I mean
As long as they're position in the right order. It should be fine.
Ah, well, then bad luck.
You could use args array and parse it somewhere else. But I wouldn't recommend that
yeah, I was thinking about it, but it has literally zero type safety
which is definitely not what I'm going for
It has type safety. You will have to cast it to the right type. Otherwise it's gonna be null.
If it didn't have type safety you could cast it to any type and get messed up data.
yeah but it'll be possible to pass in an incorrect args array
yeah but I want to remove the new keyword AND retain all its benefits ;D
I think it's impossible without doing some code gen or REALLY scary reflection so I think I have to abandon the idea though
possibly both
So, you would prefer to write it as:
EventBus.InvokeEvent<TimerEvents.TimerPauseEvent>(pauseTimeLeft);
rather than:
EventBus.InvokeEvent(new TimerEvents.TimerPauseEvent(pauseTimeLeft);
yup exactly!
that's precisely what I'm going for
it's just that this pesky "new" is required in the first option
that makes things a bit uglier than I'd like them to be
Itโs never a good idea to be held up by making code pretty. Make it maintainable and readable.
Being clever like that gets you murdered by colleagues in your sleep.
I do know that, it's just that sometimes (perhaps even often) the two go together
What are we designers?
I would get rid of the Event in InvokeEvent to make it more readable. Then new fits into the sentence better:
EventBus.Invoke(new TimerPauseEvent(pauseTimeLeft));
(and remove the nested class)
I like my systems to be nice and pretty black boxes from the outside, and when you go inside you're hit with a wall of comments that explain everything
"EventBus, invoke a new timer pause event"
xd
It never does in real (production) code. Thatโs why itโs a waste of time.
can't do that as Event is not the only thing that can be invoked
Events aren't the only thing that can be invoked in your event bus? What else can be invoked?
it's... complicated
it's a mixture of multiple systems, old and new
gotta love old code, don't we
Maybe focus on refactoring it then, instead of wasting time on impossible syntax sugar.
Does it have to be combined into the same class?
nope, we need the other functionality
I mean considering how similar it is, it makes the most sense
Refactoring is intended to keep the other functionality.
EventBus.Invoke(TimerPauseEvent.Instantiate(pauseTimeLeft));
There, got rid of new
you can listen for events and procedures and you can invoke events and commands
commands convert themselves into a procedure list, and procedures have logic inside them which events dont, but can be listened for just like events
๐ thanks XD
Why is an event bus involved in that?
because it works pretty much like events, just with logic inside them
I'm not gonna modify the whole project to not rely on that, that's not my task
my task was to un...screwup the old system and I did, it's cleaner now and supports normal events
โAbstractions from hell and other storiesโ
oh come on it's not that bad XD
Doesn't make sense if you ask me. It's either an async logic or passing a delegate in an event.
Hell is the best place ever until you get out
How about using a different term for events and commands? Execute commands, Raise events.
nah, I like both to be invoked, I like consistency like that
Even if it doesnโt make sense?
It makes sense to ne
I don't see the problem with the new keyword in this context. I like to think of my events as payloads and that I'm constructing it as a whole before passing it along. I prefer that over thinking of events as a set of parameters.
I am following a tutorial and Im wondering if this is a new handler of unity's api
I could not find its corresponding api page so if anybody knows what this is or if they know a page where this handler is explained it would be great help!
I don't think drag and drop exists anymore. you can make do with drag begin, drag and drag end.
ty
anyone using binary json? It is deprecated in the newtonsoft package Unity provides and a separate one had been created but damned if I can find the way to use it once added as a dll. I think BsonWriter became BsonDataWriter?
put your cursor on it and do ctrl+. VS will auto add it for you
It's green, so it exists - though may be obselete/ deprecated
Just looked - it's for visual scripting
whats your goal?
OK I got it compiling but I want to save to more compressed format than txt json
unfortunately does not serialize in quite same way it seems
hit a self referencing loop
for what purpose? you could just gzip your json
yes that is other option!
if you need speed, you should look into message pack or protobuf
yes heard of protobuf, I guess trouble is I can use newtonsoft and its opt in/out syntax so maybe stick with that and external compression until any speed issues
Trouble with Unity serialisaton is it is fields first not properties first, it is short on options too i think
Quick question that maybe someone has some experience with: I'm wondering whether it is more performant to construct a new gameobject from scratch in code, adding all components through code, or to set up a prefab with the base components, instantiate that prefab, and then change all the values. This is in the context of creating gameobjects with generated meshes.
I doubt there will be a big difference but maybe someone can weigh in
well I do such things and create in code
but if you want specific types of objects with other components in some cases - use prefabs
You can attach a 'root'/main component that pre-references a bunch of others on a prefab to make post-creation easier
well, its made for performance and simplicity, if you want convenience, performance/simplicity is not an option anymore
well my objects are always the same, and the code is just
var myComp = new GameObject().AddComponent<MyComponent>()
myObj.AddComponent<MeshRenderer>()
var meshFilter = myObj.AddComponent<MeshFilter>()
var meshCollider = myObj.AddComponent<MeshFilter>()
// and then setting some object specific mesh and collider settings
yeah I do that a lot - no issue, dunno of difference with using a prefab
the prefab instantiation can theoretically be optimized by the engine, the manual construction cannot, so pick your poison.
yeah this true - not benchmarked it
i would say gameobject instantiation is inherently so incredibly inefficient that it doesn't matter
your goal should be reusing objects and not creating them after startup of the scene if performance is your goal
ah yes true - I myself pool when speed an issue
Not an option for procedural generation (except pools ofc)
depends on what you are creating, typically most stuff is still reusable
I would continue as is anyway, just do not expect to create loads of things in 1 frame
you may need to modify vertex position, but you would potentially not need to make a new mesh... but that depends, if you are making a dungeon, you should proc-gen that from a set of reusable parts.
also mind you that meshes are a bit tricky to proc-gen, there are a lot of hidden inefficiencies and potentials for memory leaks that dwarf the gameobject creation/instantiation costs.
how about 31 chunks of terrain meshes with 14.6k vertices each ๐
yup im trying to optimize it as much as possible right now, using jobs and such
but i was just looking at my gameobject creation code and wondering if I could optimize that
pooling is probably the best option for more optimization
if you are using jobs, aim to not create gameobject at all, design them such that they are just preallocated containers that you fill with the part of the world you need to display. otherwise your job-optimization might end up not having any noticable effect
or use entities ๐
๐ฌ
im considering switching to instanced rendering for the terrain meshes
something like DrawInstancedPrimitives
but you might mean something else?
you should be careful with that, this means you are effectively making a custom renderer and abandoning gameobjects, which makes it very tedious to interate these visuals with other stuff.
Definitely true, should be doable though
I would rather use entities than make a custom renderer, since entities gives you a lot of prebuilt things that you would need to DIY, and the end result will probably be better with entities
I honestly doubt the difference would be very impressive
even compared to just using straight gameobjects
with classic meshrenderers
depends, you can do impressive stuff with jobs
entities just removes the gameobject overhead but keeps stuff on the cpu.
entities without jobs don't make much (10x or more) of a difference for performance
thing is, I'm not ever really updating the chunk objects after they've been generated, so any performance gains would wholly depend on whether rendering data on entities is faster than rendering classic meshrenderers
with jobs you can get to 100 - 1000x depending on what you are doing, certainly in the area of mesh proc-gen.
my noise gen code has already benefited by like 50x from serial generating to parallel generating in burst compiled jobs
probably makes little difference
yeah i'd think so too
mesh rendering is pretty optimized i think
yes and no, its fine for regular objects, but when it comes to "massive amounts of objects" the bottleneck is the calculation of the transform matrix for these objects, and there you would probably want to use jobs+entities or compute-shaders
yeah true
but many of these cases can just be delegated to a vfx graph
its certainly a complicated setup once you need that.
there is also a neat asset that helps with creating custom GPU based instancing renderers (GPU instancer)
I'm currently rendering 961 chunks (2-3M tris after culling) at like 200fps on an rtx 2070super
oh wait it's only 441 chunks
bumped it down because i made the chunks bigger
those numbers don't mean much ๐
ideally you want the terrain/background rendering to be sub 1ms
there is too much stuff to calculate in a game to waste CPU/GPU on the background
is there a way to actually profile that specifically?
precisely because its spread between cpu and gpu and also mostly internal
not really, you can use feature toggles and check how much the gains are
fair enough
its a bit like stabbing in a black box
yea lol
you gotta have a plan and know why it works
i would aim for making stuff that is optimizable later, ie. make sure you don't block your path by silly early decisions.
im honestly not sure I can get unity to render this at higher speeds than 3-4ms per frame
but i would not optimize unless its absolutely neccessary
never seen framerates higher than that in unity
and I've easily gotten <1ms in custom renderer experiments ive made
in c++
unity will always have a certain setup cost per frame that6 you cannot avoid, 2-4 ms, but you can do a lot of stuff after that because of this overhead
its mainly spent on optimizing what comes after
not convenience
its what a modern render pipeline needs to do to be performant
it does not scale linearly
like BIRP did
but also to be able to handle anything you throw at it
you can easily optimize a renderer for a very specific scenario to be way faster than that
but it's only going to be able to render your very specific thing
yes, unity's SRPs are aimed at optimizing dynamic scenes (moving camera, LOD, object activations etc.)
the more visual fidelity you need, the more you need to make your scenes static.
I am having an issue with order of execution maybe someone could tip me whats wrong, in short i have a monobehaviour that is merely there to fetch some resources and create some default models, i added it to the custom order script list to execute before default time, but then in my logs i have a script that needs one of this default models coming before the log on the priority script. this is all happening in edit mode
the general advice is to not use ExecutionOrder, ever.
build your systems such that ordering is either explicitly expressed in code (by calling methods in order) or irrelevant.
i dont understand why.. i need this script to be executed before anything else
won't Awake work for you?
i am using awake
if this is your bootstrap script, then an order of -1 should suffice. what are your expectations?
this asset looks sick btw
there are specialized ones for terrain/ vegetation too
the default model generation in on awake, the log that is coming before is on another monobehaviour but its a model as public field, so its generated by the inspector
Start an ienumerator that waits until the stuff is ready?
show code
btw the cinemachine is there automatically when i apply changes it comes to -1 for some reason i just added the defaults as the 1st before default time
public MyModel()
{
Debug.Log("Model initialized");
}
[ExecuteInEditMode]
public class MyMonobehaviour : MonoBehaviour
{
public MyModel myModel = new();
}
[ExecuteInEditMode]
public class Defaults : MonoBehaviour
{
void Awake()
{
Debug.Log("Defaults");
}
}
does the gameobject being active or not effect the Find() function?
I named the gameobject correctly yet it says its unassigned
you should look up the find method in the docs
Only returns active GameObject
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/GameObject.Find.html
this can give you a workaround if you got acomponent to search for. But direct reference is always better than using find
I dont know if this helps but i have a custom inspector on the "MyMonobehaviour"
Is there a reason why setting a 2dtexture on an unlit shader (on a canvas graphic) works normally, but setting a 2dtexture on a canvas shader results in what appears to be the topleft pixel filling the entire graphic?
the only difference is the type of shader (unlit/canvas) in shadergraph
how do you set the texture? What is a "canvas shader" in that case?
a canvas shader is a shader in shadergraph that has the canvas option selected, rather than unlit or lit
texture is set via material.SetTexture
it is a texture2d I generate during runtime
does it make sense?
oh huh there's actual canvas shaders
it's unity 6 specific thing
I just guess the unlit default shader is just built up differently than yours. you might miss something in your shadergraph shader
it works if I set it to unlit, but masking breaks
The normal canvas shader is basically just stencil stuff so what are you trying to even do with this
probably better off just editing that directly
I'm sampling the texture in the shader and putting it inside the fragment base color
in a way that works on unlit material
pretty straightforward
I just want to display a texture on my custom shader
by setting it via code
Did you try to expose the texture as property and assign that to the basecolor?
For me it sounds like you are missing the UV distribution part somewhere
what do you mean? I have a Texture2D inside the shader in shader graph, and I'm setting it via material.SetTexture
it works on unlit
that multiply goes pretty much directly to the color value in fragment shader
this works for me in UI
did you do something funky with your vertex or fragment?
vertex is untouched, I have sth fancy in the alpha but it works on unlit so i dont think that's the issue
what I posted is the entirety of the color in fragment
anything in your vertex?
why do you have the option to add uv, and I dont
I'm on newest unity 6
Expand it with the down arrow on the node
also you got built-in targeted if that matters
did you create it via this?
oh wait yeah that node looking different
I think that was the pre unity 6 node
I tried adding a new one and it looks like yours
I know that built-in shader graph was included a little later so maybe they just updated it
I'm surprised it's still supported
it works kinda, but the UV seems completely screwed up
Sounds to me like a none code question anymore #archived-shaders
expectation vs reality, assigned texture vs displayed
yea good point
the ctor on MyModel() is called immediately on load of MyMonobehaviour, before any Awake, if you want to have it run in Awake you need to call the new() in Awake, not as part of the field declaration. This has nothing to do with execution order at that point.
private void Update()
{
// player jump
if (PlayerJump.triggered && isGrounded)
{
Debug.LogWarning("jump is working ");
Rigidbody2D.AddForce(Vector2.up * JumpHight, ForceMode2D.Force);
}
//player attack
if (PlayerAttack.triggered && isGrounded)
{
Debug.LogWarning("attack button is working ");
Utility.connection.ChangeAnimationState(animator, Player_State.Attack.ToString());
}
}
am trying to make the player jump , but when it jump , he is too fast almost like he is teleporting , i try to change the mass and gravity , but didn't work
Try to use impulse instead of force
i try this before and didn't work was the same this happen and i just try it again now , my player won't even jump now, even if i increase the jump force
I'm trying to optimize the inputs from my game, and I managed to learn the basics from the Input System but all the tutorials I see still uses Update() to detect the inputs, which is exactly what I dont want to use
The original input system uses Update to poll for inputs. If you don't want that, you can use the current input system that uses events.
I'm using the new system but still
what does "optimize" mean here?
Do something that runs without taking that much from the device, and running an input processing method every single frame isnt that good.
Checking inputs every frame is completely normal
That's what the new input system is doing internally anyway
Do you actually have a problem right now?
sometimes the fps decreases by 3 or 4, what wasnt supposed to be normal for the amount of features it has for now, and as its 2d
is there a callback for once the asset database is done refreshing? or just any callback thatโs called every time any asset is imported?
wdym
I think I was descriptive enough
when literally any asset of any kind that unity needs to handle importing, ie when the progress bar comes up after importing an asset, Iโm looking for a callback for after itโs done doing that
so if I import an audio file for example, once itโs done importing it I want to run some code directly after that
in this case, i think not
do you know why the framerate went down?
hmm...so AssetDatabase has some events that tell you when entire packages get imported
but it doesn't have callbacks for database refreshes
no. the decrease is very slight
nvm I think I found something
one thing that comes to mind is https://docs.unity3d.com/6000.0/Documentation/ScriptReference/AssetPostprocessor.html, which you could abuse
Iโll give the asset post processor a shot
but this would call your code before the import is over
you'd get the call right before the import finishes (as postprocessors are running)
oh well
good enough for my case
so.. i should check this?
I was talking to Zweronz there.
You should use the Profiler to see what's going on
If your framerate is dropping whilst you perform an action, then the issue is probably with the action itself
not with how you're receiving input
i did as you say but it still instantiates the model before awake, although then its re-instantiates in awake again, i can safeguard and ignore the models i need if they are not defined yet (for this first automatically instantiation of the model) but is there a way to simply prevent this instantiation? i guess unity simply sets all fields to default
Hi everyone,
Does anyone know if this works: PrefabUtility.GetCorrespondingObjectFromOriginalSource(GameObject)?
I'm trying to get the prefab of an instance object in my scene (Editor only). I want to save the prefab in a ScriptableObject. I've got two buttons, one for loading the object and the other for saving it, allowing me to configure some level data and save it.
However, I can't figure out how to get a prefab from its instance and save it in a ScriptableObject.
Can anyone help? Thanks in advance.
Edit : I think i've got something... PrefabUtility.InstantiatePrefab() And not Instantiate()...
Instantiate just creates a clone of that object. Its never the original prefab, so there is no connection ther .So yea InstantiatePrefab is probably your best bet to preserve original
PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot() works when NOT in a prefab stage on an instance in a scene
But yea if you instantiate it incorrectly in editor it won't be a prefab instance and this wont work.
these freaking methods names rofl
Hello, I'm seeking for an advice with implementation of old RE-style fixed camera system. I've made one with trigger zones, but I don't like this solution, because trigger colliders will overlap sometimes and make it a bit convoluted (or I did it wrong, dunno).
Any ideas how to do it more properly without constant checking is player in view/zone? I'm using cinemachine ofc.
If you switch to a zone's camera when you enter it, overlapping zones will behave decently
have you tried the Already included feature in cinemachine for that?
takes a bit of tweaking but wayyyy better than using triggers
ah, neat!
I was thinking about it when I saw in some tutorial using it, but I saw a comment that those clean shot cameras still rendering all thing if they not disabled, lol. Or that's false?
That is very much wrong.
Cinemachine Cameras do not render anything
All they do is tell the real camera where to go
@astral nexus yeah doubt thats true. all its doing is switching cams to which one Main Camera renders
It is true that all of the cameras are doing their shot-quality evaluations
that's a given
Will setting enabled to true call OnEnable() and setting it to false call OnDisable()?
Yes, the messages get sent immediately
Note that if an object is deactivated, the behaviours on it will be treated as disabled
The messages get sent if isActiveAndEnabled changes.
Oki, thanks! Will try this ClearShot camera thing
yeah def! give it a try. Its pretty good when i used and also made a RE style game myself
some areas need tweaking but you can get really good results
so you may want to turn off cameras that are nowhere near the player
at that point, though, you'd probably just deactivate entire chunks of the world (or unload a scene)
I need help. I added First Person Controller Asset to my Unity project as player controller. I wanted to make a cut scene and it works fine.In cutscene I disable the player game object totally(thePlayer.SetActive(false)). After the cutscene finishes I do thePlayer.SetActive(true) and player won't stop moving until I make an input(W, A, S or D). Can anyone help?
Can't really help without the code
So I try to follow this tut.
https://www.youtube.com/watch?v=nSDhT6mxF8w&list=PLJWSdH2kAe_Ij7d7ZFR2NIW8QCJE74CyT&index=4
When I finished the vedio, I got an error that say: " NullReferenceException: Object reference not set to an instance of an object" on line 14. I check if I were missing a sprite, but it didn't seem like the issue.
The game still runs, but the error annoys me a lot. How do I fix it?
In this video we will be updating our #unity3D inventory system's graphics to use a 3rd person character controller and cinemachine!
Source Code: https://github.com/sniffle6/Scriptable-Object-Inventory
If you like this channel, or just Unity in general, consider joining my Discord at: https://discord.gg/5yj4Ecp
*******************************...
Can I send the code in DM?
You probably forgot to assign the item variable in the inspector.
Or you have another copy of the script on the scene
!code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ 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.
I already assign the item variable in the inspector.
Hum...Okay I fixed it. I don't know why, but when I deleted the Apple and drag it from the prefab again. The error disappear.
how exactly would you go about character customization/clothing options for a 3D game? I have the model prepared, with (for example) 10 hair options, and theyโre all just be parented to the head in the rig, then would I just make it to where all the meshes they arenโt using with to be invisible? I feel like thatโs self explanatory but then Iโd need to do the same with every armour option, then the player would be running around with tons and tons of invisible meshes? I feel like thereโs a more optimized way?
using StarterAssets;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CutScene1 : MonoBehaviour
{
public GameObject thePlayer;
public GameObject cutSceneCam;
public Transform transformPlayer;
private CharacterController charController;
private float moveSpeed = 5f;
Quaternion rotacija = Quaternion.Euler(0f, -90f, 0f);
private void Start()
{
transformPlayer = thePlayer.GetComponent<Transform>();
charController = thePlayer.GetComponent<CharacterController>();
}
private void OnTriggerEnter(Collider other)
{
this.gameObject.GetComponent<BoxCollider>().enabled = false;
cutSceneCam.SetActive(true);
thePlayer.SetActive(false);
thePlayer.transform.position = new Vector3(816f, 147f, 280f);
thePlayer.transform.rotation = rotacija;
StartCoroutine(FinishCut());
}
IEnumerator FinishCut()
{
yield return new WaitForSeconds(3);
cutSceneCam.SetActive(false);
thePlayer.SetActive(true);
}
}
depends on the design too. Having them all on the gameobject not active has no extra performance cost because its already loaded it into memory, the cost of visuals come out when your camera is rendering the triangles (when you activate visuals for camera to render)
Otherwise you need to dynamically load them so you can offset that with async methods and addressables for example
Here's the cutscene code
Player movement code is the one that matters
A tool for sharing your source code with the world!
Hey all I'm trying to place a unit in a grid space where the mouse position currently is. For some reason unity is placing it based on the global position and not the local position when the game object is a child of the grid. Code is in this pasebin : https://paste.mod.gg/hvavkejchdex/0
A tool for sharing your source code with the world!
Weird thing is the Debug.log is placing the unit Where I want it to be. But for some reason when its instantiated, it instead utilizes it as a gloabal position instead.
So you're changing a world into a cell position (Vector3Int), but then instantiating it using that Vector3Int as a global position
Should that not be in ref to the grid object tho? So I would have to do: GridRef.WorldToLocal() THEN GridRef.LocalToCell() ?
Right, if you want the pivot of the cell in world space you need to change that cell into a world position
Right but in this case I'm converting mouse position to a cell on a grid.
I want those ints to show me the closest cell position to the mouse cursor.
Which you are getting I believe here, but the problem is that you want to instantiate it directly on the pivot right
I mean you know the world value already from the pointer
just I assume you want to align it now
Looks like the input handling is done in _input = GetComponent<StarterAssetsInputs>();
so that's the script where the issue would be
seems pretty clear that it's probably just storing stale input data since you disabled it
maybe I'm stupid, but how can I change ClearShot camera fields in cinemachine through script? Like default target, etc.
code on the screenshot is throwing null reference, even when field is set in the inspector
am I missing something?
chances are your find methods isn't finding
I've tried for this pure possibility as a test: using _target serialized field before and it's doesn't work either
What should I do to fix it
like I don't know why, lol, because funny enough - default target and other stuff in clear shot camera is set by it (I've checked), but it still throwing error there like if if ClearShotCamera object is null
either change the code in the input script or don't disable the input script
Thanks
I'm experiencing an error with a gameObject that has an OnMouseDown and OnMouseDrag on it. When I use the button that is over the gameobject it activates the mouse handlers. How Do I stop this from happening? I've seen some outdated solutions but I'm not sure what is current practice.
use the event system instead of those outdated methods
isn't that completely unrelated
And you'll get that fix for free
I am working on an implementation of Cubical Marching Squares and using a sphere as my test geo this is the earliest result I've gotten to run without console errors.
What is most likely to be faulty to produce a result like this? My VertexOffset, EdgeConnection, EdgeTable, TriTable lookup tables? Or the code making use of the tables?
I admit I am out of my element trying to render voxel isosurface type stuff so I'm not sure where to start to determine why it looks the way it does
The corner vertex is because its treating the very first vertex as 'inside' even when its not which I can fix, but the bridging I am guessing is because of bad lookup tables?
i don't see how the EventSystem would have anything to do with clicking on colliders
if you use the event system instead of OnMouseEnter etc, you will get the behavior that the UI blocks the clicks etc by default
i.e. if you use IPointerDownHandler instead of OnMouseDown
OnMouseDown is used for clicking on game objects with physics colliders on them
it has nothing to do with UI input
You can and should use it for game world physics objects as well
and you will get the UI blocking behavior for free
it works for both UI and physics objects
No, I'm saying to move away from it.
Ah, I see -- you attach a Physics Raycaster to the camera
Use the IPointerClickHandler Interface to handle click input using OnPointerClick callbacks. Ensure an Event System exists in the Scene to allow click detection. For click detection on non-UI GameObjects, ensure a PhysicsRaycaster is attached to the Camera.
https://docs.unity3d.com/2018.3/Documentation/ScriptReference/EventSystems.IPointerClickHandler.html
Neat. I had no clue about that.
I've not done very much with clicking on things in the world
beyond very basic "click -> raycast" stuff
That makes sense. Everything goes through the EventSystem, which understands if the UI is in the way
As an aside: if you're in a situation where you can't use event system events, you can call this method to ask if the mouse is over something
I was always fuzzy about that "Physics Raycaster" doohickey's purpose
Thank you! This worked!
ok completely unrelated problem to the one before (Which i've since fixed), I'm getting a NRE when OnCollisionEnter2D is being called and I have no idea why, I was thinking maybe it could be something to do with the GetComponent<EnemyStats>() or something (short and brief becuase its just a null reference exception its probably something stupid tbh)
NullReferenceException: Object reference not set to an instance of an object
ProjectileMove.OnCollisionEnter2D (UnityEngine.Collision2D other) (at Assets/Resources/Scripts/ProjectileMove.cs:6)
A tool for sharing your source code with the world!
which is line 72
The IPointer interfaces also take into account of canvas ordering so elements ordered earlier will block raycasting. Sorting is a pain in the butt otherwise doing it by graphics raycasting
oh right its different for the pasted mb
line 6
then yes, stats is null which means the object that was collided with does not have an EnemyStats component
oh
you can use TryGetComponent to check if it has the component and do the GetComponent all in one line. you'll want to do the same for the PlayerStats component in the else if as well
yeah thought i might have to use that just wasnt sure lol thanks
TryGetComponent is great.
It's not much smaller than a GetComponent followed by an if(result), but it's very...expressive?
it's obvious what you're doing
(there is also a nominal performance benefit in the editor: it doesn't create an invalid unity object if it fails)
well now the fun part is figuring out why it thinks the collided object doesnt have an EnemyStats component when I have checked numerous times and it clearly does
I'm unclear how this works in 2D physics, but in 3D physics, Collision.gameObject is the object with the Rigidbody on it if one is involved
The Collision2D documentation doesn't specify
...well, Collision also doesn't really make it explicit
If you want the object with the collider on it, access the collider field and then get its game object
ill try that first then
also keep in mind that OnCollisionEnter would also be called for collisions with scene geometry (assuming that this object has a rigidbody)
Either way, you should check what object you're actually getting
It doesn't matter what you think you're receiving.
Doing an if statement with CompareTag() seems to have fixed the issue
thanks guys ๐
you can also just bail out if TryGetComponent fails
if (!hit.gameObject.TryGetComponent(out Foo foo))
return;
foo.Bar();
right now it throws a NullReferenceException if it fails which not only bails out but tells me that it bailed out
It does not.
huh
Trying to use the result will cause one.
TryGetComponent returns a bool that indicates if the component was found
no i mean like im throwing it myself (if thats what you meant then mb)
oh
just...don't do that
if the component doesn't exist, you didn't hit an enemy
you hit something else
but thats also caught by this here though right
most of my collision messages look something like this
if (!hit.collider.gameObject.TryGetComponent(out ImportantComponent thing))
return;
thing.Whatever();
Tags are okay, but they fall apart if an object can represent more than one kind of thing
what if you can shoot it AND pick it up?
is there something im missing with these colliders thats not triggering the script?
There's no rigidbody involved, so the colliders on the ship won't do anything
player controller doesn't trigger collisions? it seems to stop movement normally
That's very different.
in fact, moving a CharacterController into a wall doesn't cause a collision at all
ill switch to return in that case but i'll probably just do a Debug.LogError() so it still has the same effect of 'hey i jumped ship just telling you'
why does it stop it from moving through it?
It just looks at the environment and moves accordingly
the CharacterController can cause collision and trigger messages in some situations
the main issue i'm running into is when using the evasion skill it phases through the wall
(when things hit it)
but i'm using smoothdamp for that
if by "player controller" you mean "CharacterController" then that has its own collision message. OnCollisionEnter requires a rigidbody
i see
You can, indeed, get a message when a CharacterController tries to go through a solid collider
This isn't an error, though.
Bumping into a collider is normal behavior
Errors should be displayed (and exceptions should be thrown) when you get into an unexpected situation
does using smoothdamp on the transform.position just not trigger collisions at all?
unexpected in this case is an object with the Enemy tag not having an EnemyStats component (because without one it doesnt have any stats which shouldnt happen for an enemy, it also breaks other scripts that reference it)
That completely sidesteps everything!
the CharacterController has no say, and the physics system has no clue what's going on
ah
You can use SmoothDamp to move the current position towards a target
and then use that change to tell the CC to move
Vector3 desire = Vector3.SmoothDamp(transform.position, target, ref velocity, 1f);
Vector3 move = desire - transform.position;
controller.Move(move);
e.g.
its really just down to that the wall doesn't stop the evasion skill
ah thats what i was hoping for. ok cool
yep that does it!
so for the projectiles (brick breaker mechanics), does that mean i still want to use a rigidbody on the "ball" even if i'm going to override its motion rules and ignore physics?
Correct. You can use a kinematic rigidbody -- although this won't generate messages when it hits a static collider
"static" meaning that there isn't a rigidbody involved; this has nothing to do with the Static flags of game objects
yeah
If you're totally ignoring physics, then you'll probably want to use a spherecast to sweep out the path of the ball
i can't just have the boundaries trigger OnCollision off a sphere collider on the ball?
for most purposes it will travel in a set direction and velocity until it impacts a wall, enemy or the player paddle
But there's no physics happening here
You're just moving the ball around
The physics system isn't simulating the motion of the ball and finding where it hits colliders
That's the issue.
yeah, i suppose is there a better way to just detect when non-physics objects cross collider boundaries?
i'm not super familiar with the whole toolkit
A spherecast can tell you if any colliders get in the way of a sphere moving from one point to another
I'm having some issues when it comes to moving my player up and down slopes. My player hovers slightly off the ground to make moving over small bumps smoother but as soon as I walk up a slope the player gets pushed into the slope instead of neatly going up it. Even though I use Vector3.ProjectOnPlane() the DrawLine even shows the normal of the force correctly, but the player is still pushed against the slope instead of up it. https://gyazo.com/eda0309a9fd16b23422e9c8de943afd5
Relevant PlayerHover Code ```C#
onSlope = Vector3.Angle(Vector3.up, groundHit.normal) != 0;
slopeAngle = groundHit.normal;
`Relevant PlayerMovement Code` ```C#
if (playerHover.onSlope)
{
velocityChange = Vector3.ProjectOnPlane(velocityChange, playerHover.slopeAngle);
Debug.DrawLine(this.transform.position, this.transform.position + velocityChange.normalized, Color.red, 5f);
}
ForceMode forceMode = isGrounded ? ForceMode.VelocityChange : ForceMode.Force;
rigidBody.AddForce(velocityChange, forceMode);
Sort of off topic but does anybody here know if the .vsidx visual studio generates for indexing new files is safe to ignore in version control?
I just want to ignore them when doing backups and probably in VC as well all these small files tend to add up and slow down transfer rates for my ancient nas. i cant see any reason it would cause a problem but id really rather not fuck up my VC
yeah i mentioned that... do you know if thatl cause an error when searching if the vsidx is missing
isn't that normally in the .vs folder which should be ignored? ๐ค
yeah. good call thought i was ignoring that already ty
Hi hi!
I am having my brain melted by the following problem. I made a state machine for my game, and the transitions between the states are triggered due to some signals. For example, Atack1(State) -> AnimationEnded(Signal) -> Idle(State).
I added something I called TransitionFilters, that work to block out the transition between states (or allow them).
Now, the real problem: These TransitionFilters, are all classes that inherit from an ITransitionFilter (an interface), and I want to be able to create these transition filters on a scriptableObject. But for that, I wanted to have some kind of drop-down to select the type of TransitionFilter I want to create, like the added image.
Currently, every type of filter has an enum value used to have a dropdown in the inspector:
public enum TransitionFilterType
{
DF_NULL,
DF_IS_MOVING,
DF_FROMTOFRAME,
DF_UNTILFRAME,
RS_MODECHANGE
}
But I don't know how to map these enums, to their corresponding class withouth it being a headache. Currently I am using a switch case:
public static StateTransitionFilterSRL BuildStateTransitionFilterSRL(TransitionFilterType _type, int _frameLength){
switch (_type)
{
case TransitionFilterType.DF_IS_MOVING:
return new IsMovingFilterSRL();
case TransitionFilterType.DF_UNTILFRAME:
return new UntilFrameFilterSRL();
case TransitionFilterType.DF_FROMTOFRAME:
return new FromToFramesTransitionSRL();
}
}
But it's gonna get ugly real fast with each type of filter
Basically the question lies in:
How can I expose on the inspector all the child classes that inherit from ITransitionFilter, and map said exposed variable to the proper class/constructor of the corresponding class?
I wanted to have some kind of drop-down to select the type of TransitionFilter I want to create
i recommend using an asset like this one for that, makes it super simple
https://github.com/vertxxyz/Vertx.SerializeReferenceDropdown
Note that I'm using Odin in the current project I'm working with so I've not had time to make sure that package is functioning well, but it should handle simple cases easily.
There are many different type dropdown packages for SerializeReference though, so each would be a harmless drop in replacement for one another if one doesn't work
i haven't had any issues with it in 6, other than when some other type i had no control over forced the inspector to use IMGUI and i needed to grab the editor patching dll
That's good to hear
I have a bunch of random packages that I've not touched for years that I'd love to nuke, and some that haven't been touched but are very stable and will stick around forever
One day I'll get time to set a load to ReadOnly and pretend they never existed
@somber nacelle I am a dum dum and never played around with SerializableReference, but after about 2 hrs I came to the realization that Odin has been hand-holding me. So... I somehow already had a kind-of serializableReferenceDropdown.
Now, it's not the exact solution I wanted, but I can instance an object of the desired class, and edit the values using a button (I didn't mention it but I wanted to have the constructors for the different TransitionFilters with some parameters, but I can always just instance it and modify it post).
So... yeah, apparently I had all the tools I needed. Only tiny issue I have right now is that the "label" is bloody long lol
https://github.com/spiney199/Subclass-Selector is what we use with Odin
Gonna check it out tmr. Thanks mate!
!code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ 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.
Hi im having an issue with movement. My character always moves along the cardinal directions, but I want my character to move based on the direction theyre facing(1st person camera). https://hastebin.skyra.pw/exapayapar.pgsql
<@&502884371011731486> AI bot^
!softban 775082234507427890 bot spam
.remmy was softbanned.
that should work just fine assuming the rigidbody is actually being rotated to match the camera's rotation
although using ForceMode.Impulse for regular movement is suspect ๐ค
Yeah I would say your rb is not actually rotating if this doesn't work
And yeah deltaTime with the force is wrong
ah yeah that too
But that's cancelling out impulse (sort of)
I ran into a problem and wound up switching from yours to another package. I cannot remember what the problem was.
I hope this is useful feedback โจ
lol
i'll have to figure it out again tomorrow
i hope it wasn't just "i don't like how it uses two rows"
honestly, ive been replacing everything to try and brute force it, so some things are left over from those experiments. I figured the rb might not have been rotating, but when i tried changing the rb's rotation, it didnt work so i figured i might as well ask.
should " rigidbody.rotation = camera.transform.rotation;" in the first line work?
That will indeed rotate it but probably not exactly how you want if your camera looks down at an angle
๐คท no need. I know there are issues and I would probably go about implementing it differently now. There's another implementation that would make it much more robust that I'd like to do at some point
Would there be a better way to rotate? Im still having the same issue with the line added
here's the input settings, that could also maybe causing the issue
I tried changing the rb rotation to match the player's last night, didnt work. I added the new line 15mins ago, didnt work. I spent those 15 min changing and testing different debug logs, and now it works. Character flies now, but it works ๐
oh it was the " * Time.deltaTime" change into " * Time.fixedTime". ๐
Neither is appropriate, and adding the force from an input callback isn't either really. Adding the force belongs in FixedUpdate
Thank you! Would you have any suggestions on way to do the dynamic loading best?
You can also swap the mesh portion of the mesh render. Just use shared mesh to keep from making duplicates.
Is there a way to get a point on a collider but keep said point on the outside?
ClosestPoint is near what I want but it's not quite because if the point it inside then it just returns the point
Is this a trigger collider?
I think I might just have to do something hacky like multiplying the direction from the collider to the point by a huge number then getting the closest point to that
Nah normal collider
primitive or mesh?
Primitive right now but at some point I want to support mesh
cus for sphere or cube its simple but for mesh the only way i can think of is find the closest edge (2 verts) and project onto the line between them ๐ค
im thinking 2d here derp, not sure what works for 3d
Yeah it's a bit of a nightmare I'm a bit upset Unity doesn't have something for this considering it has a lot of usecases
usually need some type of intersection if you want that accuracy
Hmmm I would give the point a small collider use https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Physics.ComputePenetration.html to compute the depenetration and then call closest point from that new point
Tbf that works in my favour it's a climbing game so the hand is gonna have some form of radius
I'll give it a try. Thank you very much guys!!
I'm not too sure what the name of this issue might be called, but notice in the video how the object rotates in one direction then immediately flips to the opposite direction. The problem seems to be like the image shows, where the joystick is on one side, but once the joystick crosses over a 180-degree angle, the rotation immediately starts to turn in the opposite way.
The code responsible for that is here:
float currentAngle = Mathf.DeltaAngle(0f, transform.eulerAngles.z); // current angle with range [-180, 180]
float targetAngle = -Mathf.Atan2(targetDirection.x, targetDirection.y) * Mathf.Rad2Deg;
// the two angles, to calculate a difference
float angleDifference = Mathf.DeltaAngle(currentAngle, targetAngle);
RBody.angularVelocity = angleDifference;```Even though I get what the issue is, I dont really have an idea for how I'd fix it
Hello, i am trying to create a development build for my project. It doesnt work and i get following error: System.BadImageFormatException: Format of the executable (.exe) or library (.dll) is invalid. at Mono.Cecil.PE.ImageReader.ReadImage()
if i make a non development build its works fine. Does anyone have any idea what the reason could be?
DeltaAngle is shortest angle between 2 angles so it is not what you want is it?
How to make a box editor like what we have on BoxCollider2D?
I'd like to create a game object in which I define a box similar to how I define box collider and then divide that box into regions like this:
This is for visualization and debugging. In this case this box would define the playing area for my game with regions inside it for AI to use. It's not a collider.
The issue is that if the joysticks angle is -179.999, it rotates to the left, but if the joystick changes every so slightly to the right, the angle wraps around to 180.01 so that causes the body to start to rotate right. Even though from the players perspective, they still intend to be moving to the left
yes that is what deltaAngle will do if you look at difference between forward and down-left vs down-right
My crappy fix to this is just remap the angle if you're not expecting negative value for a rotation
you dont need float currentAngle = Mathf.DeltaAngle(0f, transform.eulerAngles.z); just use the eulerAngles.z - then get delta to the target
then debug log what is coming out
You can also use quaternions and just slerp it oh nm you're using rigidbodies
Quaternion currentRot = transform.rotation;
Quaternion targetRot = Quaternion.LookRotation(Vector3.forward, targetDir);
Quaternion delta = targetRot * Quaternion.Inverse(currentRot);```
That will ditch the trig stuff if you wanted
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Quaternion.ToAngleAxis.html
I think this would be what you need to then calculate the shortest rotation there after. I forget
otherwise quaternion Angle and cross product probably
eh, I'll worry about it later. I cant get it behaving any different
the movement is fine overall anyway, I'll just put it on my kanban board for later
GCHandle.Alloc == fixed() in unsafe burst function im i right?
"t:material shader:Universal Render Pipeline/Lit"
i want to search for materials that are lit , how can i do this in editor ?
this doesnt seem to work
What's the best for performance way to get average color of render texture in MonoBehaviour script?
Probably, run several passes of a downscaler shader on it.
It depends on if you're constrained by time or not. Like, is it fine to do that over several frames?
I think so, I am trying to make smooth auto exposure in URP, and there is clearly a better way, but for now I am trying to regulate exposure from average brightness of main camera's render texture
this does make sence, but I don't really know how to do this in script, not a compute shader
Well, you won't be able to do it fast enough on the CPU if you need to do it every frame
Maybe with jobs and burst, but even then GPU solution would be faster probably
You technically don't need to transfer the data from the GPU to the CPU to implement auto exposure. It can stay on the GPU, saving the cost of transferring the information. Even if you only send one float, it can still take 1 or 2 frames to get it.
I don't know if HDRP keeps everything on the GPU or not. There might be some benefit of knowing what exposure level you have in script, so you can modify it further, add progressive adjustment, etc.
Some custom engine I'm working on at work does several downscaling passes on the render target. In the end you have 1 pixel wide texture with the desired color. Then you can just read it on CPU if you really need to. Usually it's just used in other shaders.
Yes, you are right, and I did make it entirely in compute shader (using ShaderGraph), but it changes exposure instantly, since you can't storage values from previous frames to compare with current one, so I can smoothly interpolate exposure, or maybe I am missing something?
//Get random upgrades
int[] randomUpgrades = new int[4];
for (int i = 0; i < randomUpgrades.Length; i++)
{
bool upgradeIsUnique = false;
while (!upgradeIsUnique)
//for (int j = 0; j < 4; j++)
{
//Get upgrade to set
int numToSet = Random.Range(0, upgradeManager.GetComponent<UpgradesGeneral>().upgradeList.Count);
//Check if upgrade has already been chosen
upgradeIsUnique = true;
for (int u = 0; u < randomUpgrades.Length; u++)
{
if (numToSet == randomUpgrades[u]) { upgradeIsUnique = false; }
}
if (upgradeIsUnique) { randomUpgrades[i] = numToSet; Debug.Log("Upgrade Is Unique"); }
}
}
Must be a better way to do this than a for loop inside a while loop inside a for loop. Plus it's crashing due to an infinite loop. Any help appreciated, thanks in advance
Have a list of available upgrades, as well as a list of chosen upgrades. Every time you randomize one from the available list, remove it from the available list and add it to the chosen list.
What are you trying to do
Damn that's a good idea, will give it a go. Thanks mate
Tryna chose a random upgrade but make sure it hasn't already been chosen before
Just shuffle a list
Imagine a deck of cards. You shuffle it then just pull from the top as many as you need
Yeah yeah that sounds perfect, exactly what I need. Thank youuuu
I either do a pool that i remove items from and re fill when empty (to avoid duplicates) or a single loop item swap.
You can totally store a value from the previous frame. I assume you're already storing the value somewhere, in a structured buffer or texture. You can just read from that buffer/texture before overwriting it, moving it towards the calculated exposure.
Hey, so I have a simple setup,
One object has a rigidbody and collider2d, second object has only collider2d set to trigger.
When first object enters the area of the second collider it should trigger this
private void OnTriggerEnter2D(Collider2D collision)
{
//do stuff
}
but it doesn't, why?
Loll literally, this is the best way to learn tho bro haha
Which object is the script on?
on the one with rigidbody
Is it a Rigidbody or Rigidbody2D
2D
How do you know the code isn't running?
Did you put a log statement as the first statement?
yes I did
they are on the same, Default, layer
okay im just stupid... the second object had Collider and not Collider2D
//Get random upgrades
int upgradeCount = 4;
List<Upgrade> upgradesToChose = new List<Upgrade>();
upgradesToChose.AddRange(upgradeManager.GetComponent<UpgradesGeneral>().upgradeList);
List<Upgrade> upgradesChosen = new List<Upgrade>();
for (int i = 0; i < upgradeCount; i++)
{
int upgradeToChose = Random.Range(0, upgradesToChose.Count);
upgradesChosen.Add(upgradesToChose[upgradeToChose]);
upgradesToChose.Remove(upgradesToChose[upgradeToChose]);
}
Don't think it's perfect but so much better now, thanks for the help guysss
I'm refactoring my code to use IDragHandler instead of OnMouseDrag and am running into problems. old code : https://hastebin.skyra.pw/zoterepojo.csharp
new code : https://hastebin.skyra.pw/izovuwesed.csharp
The old code works just fine with some minor bugs in clicks with the ui going through. The new code I cannot even get to show debug logs. I have a Mesh collidger on the object I want to drage. I have a physics2d raycaster on the camera. I also have an event system setup. Could you please take a look and give me a resource to look at to get Idraghandler to work?
Looking for feedback on this API design for drawing lines at runtime, this is an example of consuming code:
public class TestLines : MonoBehaviour
{
private LineHandle _lineHandle;
private void Start()
{
_lineHandle = LinesManager.AddLine(new float3(0, 0, 0), new float3(0, 1, 0), Color.cyan);
}
void Update()
{
float3 startPos = new float3(currentIndex, 0, 0);
float3 endPos = new float3(currentIndex, 1, 0);
if (currentIndex % 2 == 0)
{
_lineHandle.SetValues(startPos, endPos);
}
else
{
_lineHandle.SetValues(startPos, endPos, UnityEngine.Random.ColorHSV());
}
currentIndex++;
}
}
in an editor script in edit mode, on OnInspectorGUI, i am not being able to save the state of my object, i am using:
serializedObject.Update();
serializedObject.ApplyModifiedProperties();
what am i missing?
btw i have a monobehaviour with some fields one of which is a [Serializable] model this is the object that is not being saved
Calling Update() will discard any locally modified properties that have not yet been applied.
serializedObject.Update() is usually called at the beginning of OnInspectorGUI to update the serializedObject's state from the actual object instance.
serializedObject.ApplyModifiedProperties() is usually called at the end to apply serialized state to the actual object instance
Update should be used if the original object has changed (i.e. you went and modified the C# object)
are you meant to construct the SerializedObject once and then hang on to it for a while?
I've always just constructed a new one every time ๐ฌ
If it is a script inheriting from Editor you don't need to construct one at all, it is just a property on the class
ooh, I see
I've mostly been writing EditorWindows as of late
I actually haven't written a custom editor in a while
i am not quite sure, but i had misunderstood the update function, i am revitalizing an old project so i am still getting acquainted
But otherwise yes if you need to construct it in an editor window for example, you usually don't reconstruct every redraw
so yes, i am not constructing a new serialized object i am using the default
(along with scripts that do one-off modifications of serialized data, which definitely need to construct the SerializedObject each time)
SerializedObject, not ScriptableObject (:
i tried removing the update but it didnt change anything really
Share the entire script.
I have a "parts" array and when those parts change i will modify the object to accomodate the new(or remove a) part and then i add GUI for that part to edit some values, finally i apply the modified properties
UI toolkit has less pitfalls in this regard in my opinion, only downside is if you are making an asset / package that you want to target older editor versions, but UI Toolkit has been in the editor for quite a few versions now
values just get bound and you don't have to really worry about calling those methods at all
its long, complex but is as i said, i check for changes on the object i do some modifications on the object via code and add gui to the inspector, everything is working except that if i reload the scene the changes are not set
"some modifications on the object via code" -- are you talking about the SerializedObject, or is this something else?
no i am talking about the model i mentioned
Failure to persist after a scene reload suggests that you are directly modifying a prefab instance without calling this method https://docs.unity3d.com/6000.0/Documentation/ScriptReference/PrefabUtility.RecordPrefabInstancePropertyModifications.html
But that would only be a problem if you weren't using SerializedObject/SerializedProperty to make changes
I'm going to need to see the code.
its not a prefab
there is no prefab
i have a component (monobehaviour) with a field that is a model serializable class, that field is not being saved, that is the object i am modifying along with the GUI of the component to reflect that model instance
post your editor code
See if using UnityEditor.EditorUtility.SetDirty() on it will let you save changes correctly
We need to see what you're actually doing. I don't want to try to debug this via a game of 20 Questions
That shouldn't be needed if everything is being applied through SerializedObject / SerializedProperty
its 300 lines i wont post it sorry, i apreciate your help but i wont share in this case since its generic issue not bound to one particular method
Correct. Everything should Just Work, with no further fussing.
That is completely fine. Share it.
We won't die.
!code
you are right but i dont know if its being done correctly ๐คทโโ๏ธ
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ 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.
It really depends on many factors tbh. It can be just a simple as storing the prefabs and instantiating them or using something like Addressables. It comes down to the needs of the project
I don't know in which channel to ask that,
WHY IS VSYNC TAKING 11MS?????
because it's waiting for the appropriate moment to continue rendering
That's the entire purpose of vsync. It fills up the remaining frame time so that fps stays constant.
If you want vsync then it's doing its job
You might want to profile without VSync on to getter a better representation
well I feel like it's a bit unfortunate that 80% of frame time would be spend on it
but I don't know how it would go on a lower end machine
okay, how do I uh... how do I disable vsync?
You can do it in code or the player settings
I mean if you want 100% of frame time to be used by the game itself then disable vsync and let it run on max fps
I can't find it in the player settings
its actually under ProjectSettings-> Quality -> Rendering. Use the search bar you should see it
yes

