Probably works. But just accessing .material is enough. Unity generates an instance automatically.
https://docs.unity3d.com/ScriptReference/Renderer-material.html
#archived-shaders
1 messages · Page 75 of 1
Im already acessing the .material.
Some some reason, my enemies need the GPU instancing no the material to have different properties, but the player doesnt. Even tho they have the exact same material and im getting all their materials in the same class
EDIT: The player (lighted object on the scene) actually had a different material, but yeah i need GPU instancing to actually get per instance variables. But how do i set them actually be affected by post-processing/light?
i think i've fixed it, ill just multiply the color at the end and should be fien
can anyone please provide me a simple unlit shader with 2 passes including the ForwardAdd lightmode, which does its lighting properly for lightsources other than directional light...just for learning purpose
hello, i have a tree that i want to react to wind in unity, and i want to store a float value in the vertices of my model, that holds how much each vert gets affected so that i can use it later inside of my wind shader graph.
is it even possible to store this info in my verts and then use it in shader graph?
Yes, shadergraph can access Vertex Color or values stored in UV (first four channels)
so if i paint the parts that i want to have wind, white, and then export an fbx file, the data will still be present in unity?
Would anyone happen to know why calling Graphics.Blit() on a RenderTexture with a Material generated from a ShaderGraph would always produce a red value? The ShaderGraph is set to only output black and 0 alpha, but the resulting RenderTexture has a red value. I made a thread that has a bit more context + images if that helps: https://forum.unity.com/threads/graphics-blit-always-outputting-1-on-red-and-alpha-channels.1576584/
You should use the function overload that has the pass index param. i.e. Graphics.Blit(null, this.wetnessTexture, this.paintMaterial, 0);
Graphs have multiple passes like ShadowCaster, DepthOnly, DepthNormals etc that you don't want rendering here.
(If this answers your question please update the forum post too)
It did, was testing it. I had no idea that overload existed. I'll update the thread. Thank you 
I have tried this method but with no success, it was always a little bit off. I have also tried a number of different combinations of the method on the screen but I think what happens is, the seed value returns to 0 as quick as the sine value goes below 1. Do you know any way to turn this Branch from if (value == 1) {true} else {false} into a trigger? Something like if (value == 1) {true} but without this false return
Shaders don't store values between frames so no this comparison/branch can't act like a trigger. You could handle that in C# and pass the offsets and t value in through properties though I guess.
But should still be possible with just Time & Floor. You need to take into account that sine uses a 0-tau (2pi) range though. A setup like this should work :
Here's a similar setup but with a triangle wave instead of sine
So uhm can someone help me make
hey guys?
i try now a very long time to create a buitifull water shader with Foam, Waves and some more...
but nothing what i try wont work 😦 i tryed to follow youtube videos, i tryed to follow a KI Chat Bot...nothing work...
maybe anyone here have a nice waterShader for free?
I'm trying to create a UI blur shader for a world space canvas in HDRP. Now sampling the hd scene color node with a higher lod works great, but I need to discard objects that are between the UI and the camera obviously. I cant figure out how to use the scene depth to do the check. Can someone point me in the right direction ?
I guess you can't really :
- Obviously, when objects are between the camera and the UI, the UI pixels behind those objects are not visible, so that's not the issue ?
- But because the scene color node LODs are a blurred version of the whole screen, it contains blur of objects that are in front of the UI. Including on pixels where the objects are not directly in front (because, blur)
- The two only ways to get around this would be to :
- Have a dedicated color buffer with objects only behind the UI, and the blurred version in LODs
- Do a custom multi-tap blur (costly) in the UI shader on the scene color LOD0, and discard samples where the matching depth buffer value is in front of the UI
How would I achieve 1? The UI can be anywhere in the world. I can make a custom pass that only renders objects that are behind the UI in terms of position but some larger objects may have their pivot in front of the ui while most of the geometry is behind it.
A scripted custom pass with a modified camera near plane ... or even "worse" because the UI is probably not always parallel to the camera : a custom oblique matrix
This is starting to go into not worth it category. I should have mentioned it is for VR and the UI is floating to follow the head of the player
But just for my own learning how would the discard of samples for option 2 work ?
You could also make a custom pass that copied the color buffer to a new one (and probably at lower res), filter out the pixels in front of UI, and blur.
Less heavy than rendering the objects againg.
- Sample multiple times the color buffer around the current pixels screen space UV
- Sample also the depth buffer with same UVs
- Add up the color values if the sampled depth is > than the current pixel depth
- Divide by number of (valid ?) samples to average
How do I get the current pixel depth ?
It's the view position Z value 🙂
Right. And to sample the color buffer I need its texel dimensions no ?
To offset the screen pos uv’s
Yep
You can use the screen node to get the resolution 🙂
I must be doing something wrong. With 4 sample like this I get simply a missaligned result that shifts with the camera
What do you mean "misaligned" ?
You should multiply the values after the division to get the offset by pixel.
By adding 0.1 on Y, and then adding it to the screen position, you are offseting the sample byt 10% of the screen vertical size
1/screen.width for example is the texel.x of the color buffer yes ? My original idea was that adding +1 to that and then sampling would in fact sample the pixel on the right
1/screen.width is the uv value of 1 pixel.
If you have 1000 pixels width, this is 0.001.
If you add 0.1 to this, you are offseting by 100 pixels (0.101).
If you want to offset the screen uvs by, let say 6 pixels, you do :
uv += 6 * 1/screen.width
=> uv += 6 * 0.001
Hello, im making a tryig to make a wind shader that offsets the verts of my tree models and i was wondering. Is there a way to have unitys built in wind sones affect the models using this material?
Like, is there a way to get the amount of wind that should be applied to this object via windzones, inside of my shader graph?
Thanks I got a box blur going. I think it’s called a box blur at least
There is nothing out of the box.
You can pass the wind zone(s) data to you shadergraph through a script and shader global variables if you wanted to.
Its a wind ZONE tho. I suppose ill have to create a material instance for each tree i have. Right?
You make a script that gets the windzone component https://docs.unity3d.com/ScriptReference/WindZone.html and then set global shader variables from it in Update
Like windMain pulseFrequency etc
anyone? 😦
Not enough information.
What kind of style are you trying to create? (realistic? cartoon? anime?)
What is your current progress look like?
i try to create stylized water...so iam think its a mix of cartoon and anime? idk...
i followed alot videos on youtube and delete all after that, bcs some i just get a pink plane...some i get water but the foam dont work...some i get water but the flow dont work...some i get water but the foam und flow dont work...
How do I get Canvas to show up as a shadergraph type?
I am on unity 2023.3 and shadergraph in the package manager has no updates avaliable but as far as I can tell I should be on or above a version that supports this feature
ah its URP thats the problem. I am on URP 14.0, it needs 16.0
hrm actually im on latest LTS so I am a little confused where/why I don't have this 🤔
trying to figure out what I need to update when/where to get it
like 6 months old videos are showing Canvas shaders are in 2023.2 and I am in 2023.3
Oh Im dumb and blind I am in 2022
Using render graph, is it expected that DrawRenderers() for objects on the AfterRendeirngTransparents render event will prevent any ztesting from occurring? My objects are rendering on top of all of my geometry!
Have you configured the depth attachment? I think it's builder.UseTextureFragmentDepth (or builder.SetRenderAttachmentDepth in 2023.3)
Also if you're in 2023 versions you may want to use RendererLists rather than DrawRenderers too (as that's obsolete iirc)
Interesting, no I haven't - I've called builder.SetRenderAcctachment() for the activeColorTexture only
On 2023.3
Oh sorry I meant that I'm using DrawRendererList()
Edited my above, sorry mentioned the wrong functions
Thank you that fixed it!
I'm trying to apply fog to a shell based shader in the URP and while I appear to have made some amount of progress it is still not working properly. I'm also getting really hard, pitch black shadows. Any idea what I might be doing wrong?
Not sure the right channel - feel free to redirect. If I have a large mesh, is there a way to apply different materials to different faces? Or should I break that into separate meshes? Is this what submeshes are really for?
That's what submeshes or "material slots" are for indeed
to the googles.
I have some more submesh questions:
- If I have a large mesh, does unity automatically make it into submeshes or do I need to do that manually? I am making meshes at runtime
- Is the vertex limit of 2^16 vertices at the mesh or submesh level?
- If I want to make a huge mesh with different rendering graphics, is it best to just make each different rendering target a submesh?
- To be more clear: I'm making a golf game. I make a "bunker mesh" and am trying to stitch it together with a generic "rough mesh" and am having problems. It would be much easier to just make a huge mesh and put certain vertices in a submesh so they can render different (sand vs grass)
- Can I have triangles between submeshes?
- No, you handle it manually. For procedural meshes, SetTriangles
- See the
baseVertexparam in the above function, I think it allows you to specify an offset so you can go over the overall 65535 vertex limit. Can also instead override the indexFormat to use 32-bit indices. - The point of submeshes is so you can apply different materials. So yes for your golf scene, you could assign sand to the bunker submeshes and grass elsewhere. Or could look into using a "terrain-like" shader that already allows you to paint multiple textures (via a splatmap or vertex colors)
- Submeshes have their own separate triangle arrays. They can share vertices though (probably assuming you don't use that baseVertex offset)
Thanks Cyan. Given that each submesh would need a different Physics interaction as well (obviously rough is different than green or bunker)... how would you store an entire hole's geometry? Any advice? Thanks for your time.
For further context: I am auto-generating holes... so I will create unique bunkers/greens/fairways each time, e.g.
Current plan is a bit odd.... I would draw a generic mesh with noise of rough at some resolution per unity unit... then each feature (biome vegetation, fairway, green, etc.) - have a spline that defines that area. If I'm within a spline, I'll let that unit draw its own geometry... otherwise, I will connect a triangle to the nearest point to that spline. Then within a unit, I will use terrain shaders/splatmaps to do things like draw dirt on the walls of bunkers or something.
I'd probably split them into entirely different meshes/gameobjects, so you can use separate MeshColliders too if you need the physics interaction
Otherwise you'd probably need to generate separate trigger areas. Not sure.
I can't use a different collider then on a SubMesh?
Afaik no, it's only on the whole mesh
Okay, so basically same plan and then just make them different GO/MeshFilters instead of SubMeshes... I'll just have to duplicate some triangles I suppose
And vertices
Unity forums seem to imply that meshes can be split automatically - would really simplify my mesh code
tahnks
Guys, how do you use mask and thickness textures? I'm in the shader graph right now.
Mask textures have no universal standard, so it entirely depends what maps are packed in them
Any way to figure that out?
Where did you get it?
Thickness must be supported by the shader, it'd likely be used for translucent or subsurface scattering
Well I dunno then. The grass looks funny without those maps
This doesn't tell us where the textures come from
How funny or unfunny the grass looks depends entirely what you use the mask map for in the shader
I don't know what to show you
Where did you get the asset from
Its unitys terrain sample
it includes a bunch of grass
Is there a way to go in the shader and check?
Then it's either URP mask map that has metallic map on the R channel and smoothness on the A channel
Or more likely it's HDRP mask map which also has AO on green channel and detail mask on blue channel
If it's for HDRP that means the thickness map could be used for HDRP's "translucent" or "transmission" material types
In a custom shader graph the support for those features must be enabled in the graph settings
I don't remember if HDRP lets you use all the special material types in shader graph though
I am in URP
To use the mask map correctly you'd use the Split node to split the color channels out, and connect them to the appropriate inputs
No idea what the asset was designed for, asset store it's compatable with all
Then you can ignore the thickness map, unless you're interested in implementing translucency by yourself
Nope
None of those conflict with eachother
What nodes go into what?
You can Split the mask map's Sample Texture node's output (which you've collapsed out of sight) to get metallic from Split's X, Ambient Occlusion from Y and smoothness from W outputs
You can then connect those to Fragment block's corresponding inputs
Unity's mask maps don't conflict with each other but non-Unity mask maps could
I mean you said "if it's for URP..." with 2 outputs and then for HDRP with 2 different outputs, nothing that you said conflicts with itself
green looks to be AO, it looks right
I dunno about any others
Does the detail mask not apply to me? HDRP online?
It looks totally off, center grass is the normal one
Smoothness and metallic 0 looks like the normal model
I'll just leave it like that
Any smoothness above 0 will add reflections
If you've set the material to two-sided it'll get incorrect shading like this
This is not a problem that can be fixed by tweaking the values of mask maps because it's unrelated to them
0 smoothness can conceal only by removing all specularity which isn't how the material is meant to look
It looks like the original model
It's not supposed to have 0 smoothness, even if have a different issue that makes smoothness look weird
So what do you suggest?
The weird sheen should be fixed if you instead negate the normal with the help of Is Front Face node
Flipping it "manually"
Can probably use the Sprites/Default shader as a basis.
But replace the #include line by copying the contents of UnitySprites there instead.
Then change the SpriteFrag function at the end to return fixed4(1,1,1,c.a);
Why is it that in the intersection of these 2 meshes, I get a black band?
Looks like ambient occlusion. If you're in URP, check the renderer features on the Universal Renderer Asset.
Is it related to ambient occlusion?
If it's gone by disabling said renderer feature, it was screen space ambient occlusion
Which is different from the ambient occlusion you may see in shader graph or in lit materials
u mean replace this?
That does seem to have done it.
Actually on a side note, normals are not altered by a mesh's scale factor, right?
Their direction I mean.
Like if you made an object's scale (0.1, 1, 1), would the normals adjust?
i'll take this
why do i get this error?
i dont think i modified Default UI Material
im pretty certain i didnt
Ah, I should've suggested using the UI Default shader as a basis instead of the sprites one actually. The sprite one doesn't have the stencil stuff.
Again probably changing the fragment to return fixed4(1,1,1,color.a);
yeah but i deleted the shader
and i still get the error
the one i made
this is the code
That also isn't suitable for UI. Should copy the UI default one I linked above instead and make changes.
can you help me make it identical to what i had?
Copy the UI default shader, swap frag function out for something like this
fixed4 frag(v2f IN) : SV_Target {
half4 sample = tex2D(_MainTex, IN.texcoord) + _TextureSampleAdd;
half4 color = IN.color * half4(1, 1, 1, sample.a);
#ifdef UNITY_UI_CLIP_RECT
color.a *= UnityGet2DClipping(IN.worldPosition.xy, _ClipRect);
#endif
#ifdef UNITY_UI_ALPHACLIP
clip (color.a - 0.001);
#endif
return color;
}
yeah it works man
thank you so much
but why am i still getting the error?
i only get it when i enable the dropdown template
Not sure, might just have bugged out a bit. Maybe try reloading the editor
that also worked
thanks so much man
i appreciate it
heya, is anyone aware of a better way to do this?
i'm trying to do worldspace uvs for this sample mountain made in probuilder, but i'm having a tough time getting it to look right
i use x & z for the top (flat, which is fine), x & y for one side, and y & z for another. problem with this is that i want to be able to just put one material on all vertical sides and have it tile correctly, so i've been trying to "assume" which to use based on the normal vector
as you can see though it produces weird stretching
atm i'm lerping between x and z based on the x component of the normal vector, i'm positive there's a better way though
ok so I have a gas planet shader that I made in unity shadergraph, there is this seam that runs through the planet, how do I fix this?
open up images for full view*
Anyone know why my material is full and simply transparent instead of patchy like this?
maybe it takes the entire shader and averages the transparency?
It's hard to help you if you dont show your current progress, and where are you having trouble at.
But tbh, I dont think you can find a shader that support all that feature easily. It's usually smoke and mirror, a combination of assets, shaders, and particle system.
make sure alpha clipping is disabled in the graph's settings
I have a new shader with the same issue, alpha clipping is off
also not sure if you're understanding me right, but I it seems like I want alpha clipping on, since I do want it to cut out the dark areas of the noise
That's because of the seam in the UVs; you need the textures to match at the end-points
(so sampling (0,y) should give the same value as sampling (1,y))
well with alpha clipping off, I don't see any difference, it all looks like one colour
with alpha clipping on it has the same effect ^, until I set clipping to around above 0.5, then it just goes completely blank
Ah I get it, the UVs aren't set up
I assume this is a procedural mesh or something?
funnily enough my procedural meshes work fine XD but these aren't
I'll look into the UVs
thanks
If it's procedural, you just need to do mesh.uv alongside everything else
nah these aren't
is it possible to rotate these things?
No
Probably caused by the UV coords. If you're using textures that can repeat seamlessly, make sure to use integer tiling values on the horizontal, (assuming the planet UV is also unwrapped in the 0-1 range)
Anyone know how to resolve this lighting issue Im having with RenderBoth sides of a plane in shadergraph URP?
In the images I have shown a light on either side of the 'front' faces of a mesh. Light seems to only be calculated for the front face and duplicated/mirror onto the backfaces. I would ideally like the light to be calculated for both sides without having to add extra geometry explicitly
And yes I have tried that trick everyone shows online (see image for reference) where you use a 'is front facenode' and invert the normals, when I do this it just flips which faces are considered the 'front' faces so doesnt really heap much with what I want to do
How, precisely, does this not work?
It should fix the initially described problem so maybe you're observing a different one
It seems to just flip which face is considered the front face, instead of handling the normals seperatly
IM using the built in Lit shader in URP
Some of the examples I saw online where people used that fix they were using PBR, so maybe it has something to do with that
Can you show what you are connecting this to
Okay. So you're using World space normals in a Tangent space port. You should change the normal output space under the Graph Settings
Unless you actually need tangent space for normal maps. In which case I think you should only be negating the Z axis
Yeah that was just me trying every combo of normal type 😂
When I change them both to world the backfaces receive no lighting at all
Im gonna try a different method anyway and just just the magnigtude of the main light source to light foliage
It's simplest to use object space
I know this isn't what you're asking but often for foliage a hack I'll use is to use the normals of the surface underneath them. Usually that means just pointing them up.
Hi, i'm trying to figure out why my Tranpsarent Cube is still visible in the scene. It's hard to see but certainly visible 🤨 . Is this normal?
Hi, I have a PNG image being rendered and I'd like to switch the shader from UI/Default to something else. How do I un-gray the shader options?
UI/Default shader cannot be modified
You would have to assign a material with your UI shader into the Material slot and modify that material asset
Oh, the 3rd line in the photo? That makes sense thx
anyone knows what might be the cause of these errors? this is URP2d unity 2023 project, almost new, barely touched shaders
It's not an error but a warning
Doesn't look like the type to be breaking anything
So basically I have a planet shader but there is a ugly seam on the planet sphere. Its a bit complex with a moving storm that passes around the planet, If you can help me that'd be great and it'd help me a ton. DM me please if you can help, You would need to watch my screenshare for myproblem to be clear.
Is the problem not bad UVs?
After scouring this channel history and the webs, it looks like SM 6.6 features like InterlockedAdd(float) are still not supported? Just double-checking.
what would be the unity equivalent of vertex position in UE?
If you mean in shader graph, the Position node. (That can be vertex or interpolated position depending if the chain is connected to the vertex or fragment stages)
Probably with space set to Object specifically
yes i mean shader graph, ill try this out, but if i want emission based on my vertex position would this still be possible?
because the emission is in the fragment stage
im using hdrp btw
do made shaders for Built-in Render Pipeline work well in mobile devices ?
You can then just simple use the position node also. In Object Space. It's vertex position when connected to the vertex stage, and "interpolated vertex position" in the fragment stage
Unless you do something fancy, like deformation in the vertex shader but still want to use the original vertex position in the fragment, you just have to use the position node
Hi guys i have a Color in my shader and on the material when i change the color it stay on white color, i use 2022.3.0 version someone know something on this problem ?
you using shader or shader graph?
Shader graph
Are you using hdr color for the base color or the emmision color?
this color is for the emmision and its in Hdr yes
I see it now on top. it doesn't even change on the inspector I guess
can you show the color panel
I mean show it all
like that ?
I meant the color wheel panel
are you using urp or hdrp?
hdrp
in hdrp you must give the emmision very high value to be able to see it
i know that not the problem
the problem is when i change the color there is no change the color stay white
so i can't put it blue or red
can you show the object too
scene or inspector ?
scene
Do you maybe have a script somewhere overriding the value? If not, I'd just try restarting the editor
i can't change on scene, game not runing
They can work. But you may need to measure performance yourself. There are shaders under the Mobile heading which are cheaper
I mean, it's still possible for scripts to run during edit mode, i.e. if they use [ExecuteInEditMode] attribute on the class.
ok, no i don't have any script
Probably a bug then. I'd try restarting unity
already try
can you try multiplying the emmision color with a float and set the value to a high value like 20-30?
the emission is not the problem
no that the problem
If you create another color property, can you change that one?
When i select blue that do nothing so the color is white again
that work lmao wtf
thx
having this weird bug where the shader outline for my slimes disappears behind my water shader. any ideas?
I'm trying to make a simple outline for an object, taking the position of the vertices and scaling them out, rendering only the back to create a sort of outline, however it's position isn't working how I'd expect. With the scale and colour set, it just positions itself far away from the object itself
May need to change the sorting order / render queue on materials. Or "Queue" tag in shader if code-based.
is the origin of the object placed at the center? you could also move along the normals but with flat shaded objects, that will split the edges
Yeah I tried messing with that and it didnt work :x
Unless I did it wrong
https://youtu.be/Bm6Bmcjd1Mw?si=qZ4ZuKV2yZe9uWBr
here is a tutorial for getting outlines in unity that I did - it does the same thing you're doing. took me a bit to do it correctly, is hard
Hey Guys! Welcome back to another CG Smoothie Video! In this video I'm bringing you guys a new Unity Game engine tutorial! This time, we're learning how to use the unity game engine to make 3d outlines around characters and objects in your game using the Unity Shader Graph! I think this is one of the BEST Outline tutorials out there! If you guys...
Yeah the origins seem to be in order. Although having done a bit of experimentation I can manually set the materials and it works fine, but it only seems to break when i try the outline at runtime thing I put in #archived-urp .
I just had to check "write depth" ajfhjashfjasl
and now when i run the game the outline material just vanishes...
yippee. head hurts :/
Ah okay. Yeah RenderObjects takes things out of the regular rendering order. In this case it's set to "After Rendering Skybox", so the outlines are drawn before the transparent water.
Having the outlines write to the depth would indeed stop the water rendering over.
yeah to get an outline I had to mess with the render pipeline. that is why I linked that video instead of giving a simple solution
does it get farther when you increase the value?
yeah, lowering it brings it closer to world centre and reduces the size, raising does the inverse
but, when I just apply the material as normal it works fine
so it's the way i'm doing it dynamically that it doesn't like
does it happen with all the object? can you try default untiy cube?
I can give you my outline shader if you want. you using URP or HDRP?
@regal stag love your website btw
Static batching is breaking things here, as that combines meshes/vertices and shifts the origin of the mesh
just because i've ticked static?
good catch
Yes, static batching falls under that tickbox. You can use the dropdown next to it if you need to disable batching but keep statics for lightmapping etc.
https://docs.unity3d.com/Manual/StaticObjects.html
gotcha, that'll come in handy
although I think I'm going to resort to your idea of having a separate object since even with that fixed, it's not switching materials properly
is that normally the approach you'd take for something like this? When highlighting objects for selection?
should you make objects which have a custom shader but dont move like rocks static?
Any object that doesnr move should be static by default (as in you should enable it on everything unless specific reasons). As for moving objects, use GPU instancing on the material shader if possible.
Dynamic batching for low end mobile devices though. Still, always profile and compare.
"affects" how?
Hmm I don't quite understand what kind of effect you're describing
The light can illuminate specific sorting layers
How can I make this in a shader?
This is the shader,I want the glow effect to affect layer behind it
ok but for example i have a tree, should the trunk be declared static and the leaves gpu instanced since they move around a bit?
Yeah, that sounds fine. There's also LOD groups you can throw into the mix on the topic of trees.
yes i did that
Not entirely sure how static batching with groups work, but ive read stuff that it's still ideal to flag statically.
If anything, more to cache but mem is cheap
As for dynamic stuff. I find using urp that gpu instancing has been a frame increase beyond some situations
I don't think that'll work
Shaders don't have knowledge of layers and can't affect other materials besides themselves
The 2D lighting system isn't just a shader so it works by different rules
Is it very difficult to convert this shader from standard to urp?
Shader "Custom/Stencil Object" {
Properties {
_Color ("Color", Color) = (1,1,1,1)
_MainTex ("Albedo (RGB)", 2D) = "white" {}
_Glossiness ("Smoothness", Range(0,1)) = 0.5
_Metallic ("Metallic", Range(0,1)) = 0.0
}
SubShader {
Tags { "RenderType"="Opaque" }
LOD 200
Stencil {
Ref 1
Comp equal
}
CGPROGRAM
// Physically based Standard lighting model, and enable shadows on all light types
#pragma surface surf Standard fullforwardshadows
// Use shader model 3.0 target, to get nicer looking lighting
#pragma target 3.0
sampler2D _MainTex;
struct Input {
float2 uv_MainTex;
};
half _Glossiness;
half _Metallic;
fixed4 _Color;
void surf (Input IN, inout SurfaceOutputStandard o) {
// Albedo comes from a texture tinted by color
fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
o.Albedo = c.rgb;
// Metallic and smoothness come from slider variables
o.Metallic = _Metallic;
o.Smoothness = _Glossiness;
o.Alpha = c.a;
}
ENDCG
}
FallBack "Diffuse"
}
Somewhat difficult. URP doesn't support surface shaders.
But if you just need stencils, you may not even need a custom shader. If you use the RenderObjects feature it has stencil overrides.
thank you so much
When doing custom function in HLSL, how do you control conversion/non-conversion casts?
I'm using one of Unity's batch API, and it only allow to transfer float - including for stuff that could fit in a byte, which has a sizeable effect on data transfer speed.
EDIT:
Nevermind, found it.
int MyInteger = asint(MyFakeFloat);
is there a way to suppress warnings from default shaders that come with URP?
other than editing package files which isn't a solution because not only it will get overwritten it also only changes stuff on my end
I really hate pointless warnings on every build because that obscures warnings that might actually be relevant to me
I have a question about using shaders and time. (Using shadergraph)
Let's say I'm using a material with a shader that gradually brightens a sprite over time, or dissolves an object over time, or some similar effect. This works fine if I only have one object and only want the effect to occur once, but how do I re-trigger it or reset the timer for multiple objects?
For example if an enemy dies and I want their body to dissolve using the normal Brackeys dissolve shader, this only works for one object and only once
👋 Hello there, I'm not sure if I'm on the right channel but I'm having issue with LWRP and transparency, I have a PNG but Unity refuse to render it correctly
I'd really prefer to not have one material instance per object with my material
Post a full question with illustration in #archived-urp
Even if I'm not using URP? 🤔
LWRP is URP
Ok 👌😊
hello, i dont know if this channel is the right way, but i suppose it's shade related thing:
How is the feature called where a part of a object that is inside a completly invisible cube is hidden? I would like to hide parts of the objects inside a cube, but not behind or in front
short explaination, in this image i want the green drawn part to be hidden while the cube is hidden
i have found something similar, but it's when it's in front, not in area
i have found this picture, i need to do this
My texture is colored but why the output is black and white?
it's a regular urp lit shader and I didn't change anything
you can try searching for "see through" or "cutout"
You should be using the Sample Texture 2D node, not Gather Texture 2D
yeah I noticed it just now thanks
Hey, I have an issue with my unity foliage wind shader graph where I am trying to simulate "wind" based on a windspeed variable using UVs currently, it works perfectly when windspeed is a positive integer however, as-soon as it becomes negative (to blow the other direction) it starts vertically stretching as the image below shows (assuming I can send images haha). If anyone has any idea as to what would be causing this I would be extremely appreciative, thanks!
my suspicion is that the multiply is just darkening the UV therefore stretching it, as it looks a lot different with positive integers.
I had a bandaid fix for it, where I'd just flip the uv conditionally based on the sign of windspeed, however that flips the entire asset and looks really weird when the wind speed is rapidly dancing over and under 0 "windspeed". If anyone has any ideas as to how to prevent the stretching based on the darkening I am quite new to shader graphs and would be very appreciative of any insight that could help me out, thanks!
just between the last "add" and "Multply"
add a 'Vector2' node
the out of multiply goes to x and the Y is 0
and out of the Vector2 to Add
such as this
it stops it from stretching in the Y
I'll try that when I get home thanks so much!!
What am I missing here?
You have _EmissionMap marked as a fixed4, not a sampler2D
thanks!
Hi. i wanted to ask how to convert world space position to view space position.
sounds easy enough, shader graph or shader code?
shader code
also could you please tell me how to get object space position ?
is there any documentation that tells all of this basic stuff ?, because googling doesnt gets me any concrete resource
this seems to cover the topic in hand https://www.codinblack.com/coordinate-spaces-and-transformations-between-them/
You multiply by transformation matrices to convert between spaces. For world->view, use the camera/view matrix
mul(UNITY_MATRIX_V, float4(positionWS, 1.0)).xyz
For positions, w component of float4 is 1. But for directions, you'd use 0.
Object space is what the vertices are already in (whatever is using the POSITION sematnic in the vertex input struct, usually v.vertex)
Also note that the transformation should preferably be done in vertex shader and then transformed into the fragment shader. The vertex position is no more in object space in the fragment shader
Yeah, if you need object space in fragment you'd need to pass into your own interpolator (e.g. an unused TEXCOORD channel) - same for the other spaces too.
That would probably be preferred when you need the positions in multiple spaces, passing every position in their own interpolator most likely wouldn't be as fast as only passing the object space position and doing the transformation in the fragment shader. Not something you need to really worry about at this stage though
Personally I'm also not a fan of the .vertex style naming, I prefer positionOS/positionCS etc like the SRP code uses as it's much clearer.
But iirc some Built-in RP macros might not like that.
Yeah, I don't think they do. At least some shadow handling macros don't want anything else than .vertex. But again, I wouldn't care about that at this point, rarely you need the macros when doing more basic shaders
After doing all of this, my outline is still not emissive, what am I missing?
What kind of emission do you expect, precisely
the kind that gets affected by bloom
Post processing bloom includes every pixel of the rendered image based on brightness, whether officially emissive or not
hmm, so maybe i can just change outline color for an hdr color and that would get affected by bloom?
now i'm confused what emission actually is
i guess it would be nice if the outline also affected the lightmap
i like how standard shader emission behaves and i guess i was trying to replicate that
but seems like it's less straight forward than i imagined
HDR colors help
They're not a special type either, just a color value that's not clamped to 0-1 range, so values above 1 will get more bloom as long as your project has HDR enabled
I think it's just a handy term for any color output applied after the lighting calculations so it ignores shadowing
Probably more straightforward than you imagine
where would I get started?
i thought that's what i was doing tbh haha
i think worst case just hdr on the color prolly gets me half of the way there
If you have a color output that's unaffected by light shading, then you already have emission
Why it's not blooming is then because of your bloom settings or post processing setup
other emissive lights are blooming
anything else could affect it?
Lights don't bloom by themselves, but surfaces lit by lights can receive such high exposure that they bloom quite a bit
here's an example exagerating the bloom
in purple is my outline which doesnt seem affected while the intensity is much higher (in white the standard shader emission)
tbh it seems like all the emission code i added does nothing at all
Bloom has no knowledge about what the shaders are doing
Is the outline meant to be magenta? That colour usually means the shader can't compile, there might be a syntax error
yeah bad choice of color to test i guess :p
also emission is just white
but doesn't do much, seems like nothing
here's the full code here
hmm wait
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
basically i took some outline shader and tried modifying it to add emission to it
You're doing calculations in the vertex shader here, but your fragment is just returning _OutlineColor, not using input.color
You could get emission intensity even simply by multiplying the color result by any number above 1
Emission for bloom doesn't require that much, but by default the bloom threshold cuts off values below 1 or 0.9 or so
thanks
I guess. The fragment is responsible for outputting the colours of pixels/fragments. You can do calculations in vertex shader and it's interpolated across the triangle though.
It was like you're calculating & setting a variable but not actually using it.
Thank you! Sorry for late response...
Hi, Im trying to make a "selection outline" material, I am complelety new to shaders and dont know what I'm doing tbh im getting the desired outcome kinda but I just want to know if there is a way to invert this? I want where the object is white to be transparent and where the object is transparent to be white or whatever colour.
In render graph, what's a simple way of storing a TextureHandle from a previous frame's render pass?
Setting texture handles as global is the only solution I know of, but I would prefer not to create any RenderTextures asset files.
Looks like you can add textures to a frame data to be accessed by other render passes, but I assume that it's cleared by the next frame?
I would prefer not to create any RenderTextures asset files.
you could create rendertexture on the fly
copy or blit to a rendertexture that you store in your assets or make this rt exposed somewhere
can you show your graph settings?
I think i have a question that is too simple, and that is why i cannot find the info. In Shader Graph, i just want to change the Color/Hue of an albedo texture, with an exposed slider/color wheel. I can change the color by multiplying while in the shader graph, but i want that color changer to be exposed in the inspector
NM, just found it
Instead of a separate Property, like a Vector or a Float to control it, you Convert the Color node itself into a Property :/
You can create a Color property that can be controlled via inspector by hitting the plus symbol in the top left of shader graphs and selecting "color"
Then you have to plug that property into the graph itself
Hi all!
I'm struggling a bit with getting my reflection to show up without the surrounding white box -- might anyone happen to have any insight as to why this may be happening?
I'm attaching screenshots of my shader, the render texture, and how it looks like in a game view.
Any help is appreciated, thank you!
Is it possible for an unlit shader to sample URP reflection probes? In render graph, there doesn't seem to be a way to pass in the reflection probe atlas to a material
Was this meant for me?
Sorry wasn't sure haha
You'd want to connect the A output of the sample texture node to the Alpha port in the Fragment block.
If a camera is rendering to the render texture make sure it's background type is set a Color with alpha of 0.
Oh no just a seperate question
Ah mb! 🙂
Ah thanks for the heads up!
I'm thinking this is what you meant?
Looks like that resolved it!! :))
Would probably need to test it. Might be easiest using an unlit graph with the Reflection Probe node.
I believe I tried that, and it doesn't output anything
In the frame debugger, I noticed that the Reflection Probe Atlas was being passed in for lit shaders only, so I was hoping that passing it in manually would fix it?
How do you do vertex lighting on URP?
If I needed to render literally millions of points, each at a specific position, what would be the go-to strategy?
Is there a way to hook into something like the VFX graph and specify the position/color of each particle?
You can read from a GraphicsBuffer in a VFX Graph, which can contain all your positions and colors.
I just got this working actually 😛
Second question.
Is there any way to click a particle?
Or some way to know that the mouse is close to some particle in particular, and pull unformation out?
Like imagine I am mapping the nearest 10,000 stars.
I click a star particle, and then I get to see data about the star.
There's nothing built-in to VFX Graph that makes that easier. Since you have the star data on the CPU, you can try putting them all in a spatial tree, like an octree or k-d tree, and raycast against that. There are a few libraries on GitHub that can do that.
I'm trying to use the VFX graph to render likely a few hundred thousand of these guys.
Or at least, pushing to see what I can do.
Associating the visual representation with the data is the tough part here.
Can someone please help me? I currently have a outline+shadow shader on my TextMeshPro fonts, it works but when i try to change the alpha the outline colors accumulate on overlapping areas, here's a picture of it:
And here's my shader code
Is there anything i can do so those overlapping areas alpha doesn't accumulate when changing the alpha of my text?
Another picture that's easier to see this overlapping
Hey I simply wanted to create a shader material which changes the color based on uv height of my procedual generated terrain. It works on a cube, however, it's not working on my terrain correctly. Does anyone has an idea why this is happening?
It sure works as correctly, ”uv height” though definitely isn’t what you think it is. I’d assume you would want to use the position, not the uvs
Yes you are right indeed. But the applied material colors aren't accurate towards the set gradient in the shader graph as you can see here. Do you have any idea about that problem?
The gradient goes from 0 to 1, the mountains y position goes from 0 to 20 or something, you need to remap the positions to that 0 to 1 range
Now the gradient is showing between the y positions between 0 and 1
I tried clamping the height between 0 and 1 to match the gradient however it changes nothing. Am I on the wrong way? Which node should I use for it? Sorry it is litterally my 1st day using shader graph.
you want to remap the height
roughly (min height, max height) -> (0, 1)
Theres million ways to do it though clamping is not one of them
Yep, the remap node could be used
So could inverse lerp or simple multiplication in this case
Remap would be the most flexible of them for the future (I think inverse lerp should work just as well though)
Remap Node works for me, I highly appreciate it and thanks to @karmic hatch as well! Because my MaxHeight can be different at every game start I created a Vector2 and set it to "In Min Max". Can I change the Vector2 of the material via my C# Script at terrain generation now?
You indeed can if you created it in the blackboard (are those called properties? Cant remember yes they are)
Yes they're called properties. I'll look it up now how to edit them via script
You can reference to that Reference name starting at underscore to change that when calling .SetFloat/.SetVector/.SetColor etc. methods for the material
So materialVariable.SetVector(”_InMinMaxHeight”, new Vector4(somethingHere)). Note that SetVector wants Vector4 as input, if the vector in your shader has less components, the extra ones are ignored (in your case the z and w axes doesn’t matter)
It works perfectly thank you a lot.
#pragma kernel CSMain
struct BoidData
{
float3 pos;
float3 rot;
float3 flockPos;
float speed;
float nearbyDis;
float avoidDis;
float boidsCount;
};
RWStructuredBuffer<BoidData> boidBuffer;
float deltaTime;
float3 targetPosition;
float maxSpeed;
[numthreads(8, 8, 1)]
void CSMain(uint3 id : SV_DispatchThreadID)
{
BoidData boid = boidBuffer[id.x];
float3 targetDir = normalize(targetPosition - boid.pos);
if (isnan(targetDir.x) || isnan(targetDir.y) || isnan(targetDir.z))
{
return;
}
float distanceToTarget = length(targetPosition - boid.pos);
if (distanceToTarget <= boid.nearbyDis)
{
return;
}
float3 separationDir = float3(0, 0, 0);
int count = 0;
for (int i = 0; i < int(boid.boidsCount); i++)
{
if (i != id.x)
{
BoidData otherBoid = boidBuffer[i];
float distance = length(boid.pos - otherBoid.pos);
if (distance < boid.avoidDis && distance > 0.01) // avoid division by very small values
{
float3 diff = boid.pos - otherBoid.pos;
separationDir += normalize(diff) * (1.0f / max(distance, 0.1f)); // Scale influence inversely with distance
count++;
}
}
}
if (count > 0)
{
separationDir /= float(count); // Average the separation vector
}
float3 velocity = (targetDir + separationDir) * boid.speed * deltaTime;
if (length(velocity) > maxSpeed)
{
velocity = normalize(velocity) * maxSpeed;
}
boid.pos += velocity;
boidBuffer[id.x] = boid;
}
I am trying to create the boid separation logic using a compute shader but the separation vector is turning out to be zero
How do you know that?
using a debug buffer
What is a separationDir? I don't see a similar field in your shader struct.
So it's the pos?
@kind juniper basically I am trying to implement the separation behavior of boids, while following a target
Huh... It's in the shader?
yes the same struct is present both in the shader and inside a class
I don't see you writing anything to the debug buffer in the shared code..?
Posting code
📃 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.
@kind juniper
What values do you see printed?
zero all the vectors distance are zero
Everything is zero?
yes
Okay, then it's not just the separation vector that is the issue
but I removed the separation code , the zombies follow the target that part of the code is working, but when I re-add the separation logic then everything is 0
the red part and instead of velcoity just add a constant speed like 0.05 to the position vector
Ok, so the issue is the velocity calculation? Are you sure that target position and other shader variables are set?
yup i checked those one by one
Does it work if you keep it as is and only remove the separationDir from the velocity calculation?
Does it work if you comment out the returns in the shader?
@kind juniper ```
#pragma kernel CSMain
struct BoidData
{
float3 position;
float3 rotation;
float speed;
float stoppageDistance;
float avoidanceDistance;
float boidsCount;
};
struct DebugBoidData
{
float3 separation;
};
RWStructuredBuffer<BoidData> boidBuffer;
float deltaTime;
float3 targetPosition;
[numthreads(8, 8, 1)]
void CSMain(uint3 id : SV_DispatchThreadID)
{
BoidData boid = boidBuffer[id.x];
DebugBoidData debugBoid;
float3 targetDir = normalize(targetPosition - boid.position);
// Check if any of the components of targetDir are NaN
if (isnan(targetDir.x) || isnan(targetDir.y) || isnan(targetDir.z)) {
// Ignore the boid if targetDir contains NaN values
return;
}
float distanceToTarget = length(targetPosition - boid.position);
if (distanceToTarget <= boid.stoppageDistance)
{
// Boid has reached the target, stop moving
return;
}
// Separation among boids while following the target
float3 separation = float3(0, 0, 0);
for (uint i = 0; i < (int)boid.boidsCount; i++)
{
if (i == id.x)
{
continue;
}
BoidData otherBoid = boidBuffer[i];
float3 otherBoidDir = normalize(otherBoid.position - boid.position);
float distanceToOtherBoid = length(otherBoid.position - boid.position);
if (distanceToOtherBoid <= boid.avoidanceDistance)
{
separation -= otherBoidDir;
}
}
// Add the separation to the debug buffer
debugBoid.separation = separation;
// Move the boid towards the target and apply separation
targetDir += separation;
boid.position += targetDir * boid.speed * deltaTime;
boidBuffer[id.x] = boid;
}
now the two parts the seeking is working which just follows a target positoin, but the separation vector is 0 for some reason , nad i cant seem to find the reason
That would imply that either boidsCount is 0/1 or the distance between them is less than avoidanceDistance.
@kind juniper found the reason, I was reading and writing the data properly from the shader, RW buffer for the debug has not been defind as you can see 🥲
Huh. What about this screenshot?🤔
RWStructuredBuffer<BoidData> boidBuffer;
This should also be defind
RWStructuredBuffer<DebugData> debugBuffer;
But it is on that screenshot
How can i give my billboard shader a min/max size like in a particle system? I want the object to get smaller the further it is until a certain point after which it will stay the same size and vice versa with the max size
I think it was not initialized
Hi, i am trying to figure if i can create a shader for pixel grass 2d top down, and i am wondering how would i do that
Do you have some reference images that you could share with us? Really hard to help without actually seeing what style you are really trying to accomplish
If its 2D, why not just drawing it manually?
It’s pixel art very large ,
Hello people. A question about shader graph how can i combine two normal maps with a mask ? normal blend doesnt work
Anyone got any resources on or now how to morph a texture into another texture and back again with hlsl? I'm trying to make the small plant texture morph into the bigger one over time. (not just fade in/out) Getting them to fade in/out of/to each other is simple enough but true morphing is a bit more difficult and I'm not sure how to do it or where to start. With a mesh it would be relatively easy I think with just displacing the vertices but I'm attempting to do it on the actual textures here instead, like an ordinary 128x128 pixel texture.
Any tips for investigating why shaders working in unity on opengl don't work on vulkan when unity is started with -force-vulkan -force-gfx-mt?
"don't work" as in "shit's transparent, yo"
heya, I'm trying to do a build and this compute shader throws this error, which is pretty vague:
the shader looks like this, just some defines...anyone have any pointers?
A compute shader should always contain a kernel. For common files to be included, you should use .cginc or .hlsl.
sick, thanks! I knew it'd be something obvious
I'm on URP 2022.3.22f
Is it possible to extract surface data from what a decal is projecting on to so I can do something like height based blending?
I want to make some puddle decals, and it would be cool if I could have the water blend into the cracks of my floor material.
It's possible I think, using a camera and render texture maybe?
That sounds like a crazy performance hit
if the decal is static, you can just capture it once
And what if I have multiple puddles?
you can capture the whole puddles using one camera with exchange of larger texture requirement, or you can only capture puddles that getting in range (became visible).
Or you capture it every frame for limited area (and layer) near the camera
There are many possibilities on how it can be done...
Could someone help me make an image project on the skybox correctly? I'm trying to make a sun for my procedural skybox shader but it doesn't seem to be working
Any solution Ive found doesn't seem to work the right way, like it won't follow offsets correctly and/or the scale is messed up
Nvm folks. I figured it out. Our good old friends the flowmaps are a perfect tool for the job. Well, after you combine the shapes of of the starting and ending textures into one mask area based on pixel opacity. 
is it possible to change the color of a texture in unity?
in blender ive set it up to do so, how can i do the same in unity?
With only these two images it will be hard, you'll need more intermediate frames, and possibly also motion vectors, to make a "morphing flipbook" effect
Did you try to do a similar setup of shader nodes in Unity ?
Yeah, I was thinking that too. I'm going for more of a "melting" effect by the way. This shader will also be used for a lot of other texture combinations.
ye i tried but the masks did not want to change
in my setup, the Green channel is used to change allat, but when i try to use the green channel here, it uses the whole texture and changes it to whatever color, not the mask
can anyone tell me how to change the color of certain masks only
Could you show a screenshot of the whole graph, and the one you had in blender so we can get a grasp of what you are doing ?
ok
the ones i selected are how i change the colors: I take the green channel from masks texture, change it into my color, and then add it to the main diffuse
The closest match in shadergraph would be to use the "sample gradient" node, with the green channel of the mask as "t" input
like this?
Yes ! (sorry, it was "time", not "t")
And match the gradient to the one you have in blender
see it still changes the whole texture, instead of green channel
see this is the green channel
Because you are adding the output of the gradient to the base color, everything that is not black from the gradient node will be visible.
In blender the color ramp gradient starts with black, but in Unity it is red to white, that's why it is visible everywhere
Make it start with black, and end with the wanted color
oh ok
like this?
Yes
Strange, the preview clearly shows that the bottom right part stays black ...
That sample gradient node is directly connected to the add node, right ?
yes directly
You could try to tweak the masking effect by moving the gradient keys to the right (to mask more of it)
tried it
it just looks deep fried
wait
huh
I was more suggesting to move these :
oh
also btw
why whenever i click somewhere
it adds an adjustment slider
instead of doing nothing
That's how the gradient editor works
You can remove the key by "sliding them out" of the gradient
More up/down
so uh
ive got it like this
but there are holes
but if i do the inverse
one sec
there are still holes
which i dont want to change colors of
how to fix
@amber saffron hey (sory for ping)
ive got the clothes masked out, but when i try to add red color using maths "add" it changes the whole thing
Could you maybe send your base color and mask texture so I can doodle out with nodes myself ?
@scenic igloo ^
Non compatible image format ? Try to zip it ?
So, hum, isn't this what you'd want ?
Did you maybe use the wrong texture as mask ? 😅
yup lol
thank you so muych
wait
it always imports as this
not the transparent one
how did you get it like that
I just drag & dropped the mask texture in unity 🤷
Maybe you have bad import settings, can you show them ?
this?
It really doesn't look like the texture I have on my side :
how
Hey, this one is named "...Met..."
Isn't it the metallic texture, and not he mask ?
Ok, got it now, drag&drop from the browser "converted" it to bmp, if I do a right click / save as I get the same png ase you now
Here's the fix :
IDK why blender would act differently (maybe also a texture import setting on blender side, something like premultiplied alpha), but the issue here was that Unity doesn't "apply" the alpha value to the other channels when importing.
By multiplying the alpha and green channel you mask out alpha from green to match what I had previously
I've also changed the "sample gradient" to more lightweight nodes for better performances.
As an other benefit, you can controll the mask "sharpness" with the multiply B value, and you will be able to expose the color on the material with the color node (gradients are not exposed)
thank you so much
this is amazing
thank you
one last question, do you know how to fix this?
its transparent and idk why
Try looking from the inside. Flipped triangles maybe?
nop its correct in blender
checked
Sure it's not backface culling ?
If enabling double sided on the shader "fixes" it, then it's backface culling, and you have inverted triangles
hey can someone explain to me why I can't edit this shader
Like I wan't to change the shader from standard
yes
in blender i enabled it
its fixed
In shader graph, is there is a way to get local Position Y into percentage
percentage of what?
height of object. For example, I have 5 mountains with different heights. I want to make it so each mountain will have a 15% painted from the top
you may find the Bounds values of the Object node useful
Bounds refers to size?
Yes, kinda. Not the scale value you see in the inspector but rather the maximum and minimum values the object reaches on each separate axis. It's more like the actual dimensions in meters but it's good to note that if the object is rotated, the bounds may (and will actually except when the mesh is a cuboid) overextend outside of the mesh making it appear larger than it actually is (it expects the mesh to be a not rotated cuboid at (0, 0, 0) rotation)
Tbh, no idea how to use it. When I feed it to the lerpT for 2 different colors i actually changes the output color??? I thought I could use positionY and some calculations but now I am confused
Use inverse lerp with world position Y and min/max bounds Y. It will return a value going from 0 to 1 vertically along the object
thanks, kind of see how it works, although it still has some weird behaviors that I need to figure out yet
Hey, I'm not to sure where to ask this but does anyone know where to find the setting under graphics for a custom transparency sort axis for camera settings. I typed it in the search feature of unity version 2022.2.21f1 but it only pointed me towards the graphics settings. And the graphics settings are telling me >A scriptable render pipeline is in use and some settings are hidden " Should i disable the render pipeline and see if it appears?
I hope this won't mess w/ my renders if i do this. That's why i'm asking first.
If you're using 2D URP, I think there's a sorting axis setting at the top of that 2D Renderer asset. But others idk.
Wouldn't recommend removing the pipeline asset unless you actually intend to switch back to Built-in RP. Would require material/shader changes too.
built-in it's under graphics, but SRPs it's tied to the renderer asset
maybe the material values are controller by a material property block
Hey all.
Having a strange issue with 2d sprite textures with a shadergraph.
I'm not sure why, but my sprites and their output have this 'smearing' where the transparent pixels should be-
I've tried connecting the alpha of the 2d sprite sampler to the fragment output with no luck in fixing it.
The alpha looks correct when it's just the alpha channel, but the output is still weirdly smeared, generally to the bounds Unity created on my imported sprites.
I've tried a handful of fixes I can find for this problem, but not having much luck.
Afaik the smearing in fully transparent areas is intentional. I think unity does it behind the scenes when importing textures to avoid artifacts at the alpha edge (& particularly in mipmaps). You just usually can't see it, since those areas are fully transparent - assuming you have the alpha set up correctly as you mention.
In this case (similar to an outline?), you probably want to take the Maximum of both texture A outputs for the Alpha port.
And for Base Color, take your current Subtract -> Saturate to remove the negative side -> use in T input of a Lerp, with A as the texture RGBA and B as the color property
I figured out that my issue was that I had the Material setting under 'Universal' set wrong, which was making it output the alpha when it shouldn't have.
Can anyone direct me towards a shader I can use to show range?
This is what I'm using right now, I've been looking online but haven't found anything too good.
Drawing a circle on the ground would be nice too
Any resource I could use (built-in)?
Found something decent in the meantime
I am trying to write up the Decal that will project correctly and image into the floor, On the Right is the Shader Decal, I can't figure out what wrong I am doing, Any Ideas ?
does anytone know why I cant connect these two things
Normal from texture doesnt work on vertex shader I believe
so is there anyway I can make it possible to use a normal map?
Oh, I think you should just use Sample Texture 2D (LOD) instead if you want to sample a normal map. Normal from Texture is used to get normal information from hight map
hmm, doesnt seem to be working
ah nvm i had to change type
thank you
hard work
You sure it's not frozen?
No, I'm done, approximately 9 hours and 20 min, will variants be compiled, can the wait be improved or reduced?
They're usually only compiled once and cached. As long as unity can reuse that cache it shouldn't compile them. It might recompiled changed files though.
That being said, 9 hours on shaders is abnormal even in huge projects. You either use a crazy amount of different shaders, or there's some other issue(like building variants for several graphics apis..?)🤔
hi guys does anyone know how i can add the black part of the left side texture to the main right side texutre
like i want both the textures to be combined
so that i can use it for metallic texture
when i add the two textures this happens
If they're black and white and the black part is what you need, then try multiplying instead
okk thank u
Hey everyone I have a game basically 3d view but the game is 2d and only x and z plane are being used , I have a use case where if a resource ( anything ) is behind an object a tree for instance , that part of the resource would appear just a simple color with no texture, currently a shader is being used code here https://pastebin.com/kTGFxvQk , so how can i achieve this
here is the view
Pastebin
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.
hey people how can i blend two normal with alpha mask?
Probably lerp then normalise.
Or maybe Normal Strength node to control the strength of the overlayed normal, then Normal Blend. If you're using shader code those docs pages show what they do.
@regal stag normal blend doesnt have a mask it has two entry points for two maps to blend. Lerp can work imma use it see what is up
Hey everyone, does anyone here know how to enable the heat map in shader graph?
If using 2023.3/6000, it should be on the "Color Mode" dropdown at the top of the graph window
https://forum.unity.com/threads/2023-3-heatmap-color-mode.1507490/
Thanks!
Any clue why there is this difference between a png I have and texture I get in the shader graph?
Node previews don't show transparency, just the RGB data
I don't mean the white background. I mean these huge red/orange rectangles around the fire
Those parts are normally transparent so you dont see them.
And as Cyan said, alpha dosnt show up in preview
Yeah, that was the issue. Didn't think that disabled layers would go through when exporting
https://www.youtube.com/watch?v=GAh225QNpm0 Is this what you're looking to achieve ?
In this Unity game development tutorial we're going to look at how we can use URP Renderer Features to create a silhouette of a character when they're hidden by an obstacle.
We'll start looking at how to remove the rendering of the character completely by assigning it to a layer and removing this layer from the renderer.
Then we'll add two ren...
Btw, does anyone know what would be a great set up for distorted radial UVs ? I currently have this but it doesnt work as the center gets offset if I'm increasing my float Power 🤔
Noise outputs typically have a 0-1 range, so you can Subtract 0.5 to "center" it, then Multiply to adjust strength, and Add to the UV to apply the distortion
I think I misunderstood something OR, didnt do something in the correct order then ... :x
I didn't mean to change the Center port, leave that at (0.5, 0.5)
Awesome, working, tysm 🌺
so the time node is the only way to have an incremental value in shaders right? However, I have an issue where if I'm using time to modify something(like a UV offset), if I modify the time value to be something like slower or faster it makes the offset jump rather than change relatively. Is there any way around this?
Use a float property and control it from a C# script with material.SetFloat
if I'm using a material variant that means I only have to apply it to the parent material right?
Not sure. Material variants might be an editor-only kinda thing, idk if it affects properties set from C#
alright thanks, I'll give it a go!
If it's something that you need across multiple materials/shaders there are global properties too though. Set through static methods in the Shader class.
In shadergraph you untick the Exposed option under the property to read the global ones.
yeah I'm currently using that for my wind properties
oh yes I used Shaders of more than 10 types, for the visual composition I wanted. The thing is that if I modify the terrain or add a new object, it will start to take a while to compile again.
Hi, I want to be able to create cool visuals like what you see on shadertoy.com
I know programming and high school math. Im not good at computer graphics or linear algbera or physics.
Are there any tools that would help me create shaders easily without understanding the math really well?
I think something that would be cool, is if I could travel the frames one by one and for a very small res like 100x100, be able to see a value for each pixel that determines its color. Like the value for a function inside the shader
Hi did unity removed the shader graphs from Textmeshpro shaders? I can only see shader files.
Did it ever have graphs for TMP? Not something I've seen
I am not sure but here is a showcase video
https://youtu.be/oXdEjrm2ry4?t=158
In this video, I provide an overview of the new TMP SRP Shaders for URP and HDRP.
I have made these new shaders available on the Unity forum in the following post.
https://forum.unity.com/threads/plans-for-hdrp-compatibility-for-tmp.660598/page-2#post-7081120
The preview release of these shaders requires Unity 2020.3 along with the Unity URP a...
They have a package shared in the forums post linked in description. Might also be in the TMP package in newer versions but idk.
oh, i see thanks
how would you guys go about having a sky box within a stencil "window" thats different than the one from the scene?
also there are things between the stencil and the farclippingplane (or whatever it's called) so it can't be used inside the stencil (afaik)
Using a stencil shader, is it possible to cull pixels ONLY where the cube and sphere intersect? Or should I find another solution
That shouldn't be the case. Modifying the terrain or adding new objects shouldn't introduce any changes in the shaders. Unless the new objects are using shaders that are not compiled yet.
Yes, but the project is not using URP and it's not 3d , is 2d with y and z axis acting as the depth for rendering
Another solution. I think. Depending on your definition of "intersect". I mean, what you're showing is where the two intersect, you've discarded pixels. But I think you want to cut out the sphere where the shell of the sphere intersects with the cube, so you'd see a square-ish shape cut out of the sphere, not a cube silhouette.
Stencils will operate on a per-pixel basis for the shaders, but it won't be as programmable as you're looking for. As you've discovered. Stencil operations are settable, but not programmable.
You can probably do what you wish to do mathematically. I mean, look up an intersection test for a cube. And the intersection of the sphere is easy too, since it's a distance-to-center calc. You'd need a data buffer for the objects that you want to intersect, unless it's so special case that you can just directly pass the cube and sphere locations/sizes into the shader.
Yeah, stencil only works on screenspace, not in 3D space...
That's my first mistake on understanding how stencil works
wait dyk how to enable hsls intellesnse for visual studio?
Ahhh learning moment then. I'm just gonna modify the alpha which seems a little more appropriate for my use case. Thanks!
There's an hlsl extension, but that wouldn't help much, as a lot of the functions and macros you would be using are from unity headers, which you don't have access to normally(you could download them from the GitHub repo, but then I'm not sure if it's safe to include them in the project)
so i just p much gotta suck it up and code
Pretty much yeah.
Shader coding sucks. That's the reality.
😭
I guess real shader programmers just accept that as reality and look down on anyone crying about lack of intellisense
I wrote a ShaderGraph to make a blur effect on a 2D sprite by resampling it a few times and offsetting the sample down the y-axis. But for some reason it's moving them around the sprite as if it was a sphere, effectively cutting off the resamples in-game before they've moved very far. It's probably something dumb I should know by now but does anyone know what I would do to get the offsetting to just go down the y-axis, and not around like a sphere?
This video demonstrates how it looks in game. And you can see on the bottom right how the sprite has been spherized
im trying to follow a tutorial to make a grass shader
but i get a pink plane for some reason
and no triangle
Pink implies missing or broken shader.
Do you get any errors during the shader compilation?
seems like you've misplaced your vert function, it has to be inside cgprogram block
i put it in there and its still pink
select your shader and see in the inspector if there's still any error
🤔 I copased your shader and it works out of the box
so it seems like your gpu doesnt support your shader
are you sure its rtx? I'm not gpu savvy but iirc rtx starts at 2060
thats getting weirder since I'm on 1650 and 1660 technically should be able to do everything 1650 can
Are you using dual graphic card? Maybe unity run on integrated card
i made sure that unitys running on the 1660
try to build and run the game, and see if the shader shows properly, if it does, maybe the problem is unity doesnt run properly on your gpu
it doesnt even show 😭
No, I mean build to standalone app/game and run the built app
wait can i code this in urp?
it has nothing to do with urp, just hit Yes
yeah i did
it does nothing
i got an error saying "cannot build when importing assets or scripts"
I think that's not related to shader anymore, you can ask try to ask the question in #💻┃unity-talk
The preview window shows a sphere, but that's not what's happening to your sprite
Sprite Renderers draw the sprite on generated geometry, which conforms to the sprite's Outline in Tight mode, or draws a quad around it in Full Rect mode
this is probably a very simple question but im relatively new, especially to shaders
i made a shader network following a brackeys tutorial from 4 years ago, and apart from 1 little thing at the start there was no issue, i just had to download a package to get the right type of shader graph
after following the tutorial i got to the end and the shader previews fine in the shader network tab, but in the game scene its very slow and jenky, weird thing is it forces an update any time i do something in unity, so if i autoclick a dropdown menu it runs at a smooth 30fps or whatever my autoclicker is
does anyone know why this is happening or how to fix it
NOTE: i already looked up the issue and it said to make sure the "exposed" box is ticked for the color node cos that can sometimes cause the issue, but mine was already ticked, so thats not the issue
audio warning, bad audio on the video, mute
edit, i can get more screenshots of the shader network if you need to see close up, its no hassle
the rules say to include what render pipeline im using but i have no idea, as i said im new, so prolly whatever the default is
In scene view, there's an option (top right somewhere) to "refresh every frame" (or similar), otherwise it runs the shaders at a much lower fps
when you actually press to run the game it should run as normal regardless
okok thank you so much
Whenever i apply a shadergraph shader to a UI element it's transparent colour (alpha 0) turns into this weird red, any ideas why? The shader works perfectly fine with other ingame objects
I'm trying to make a shader for the eyes which use 2 layers of texture but the eyes are self-illuminated 😬
I'm new to Shader Graph so I'm not even sure what I'm doing 😅
Did you make a lit or unlit shadergraph?
It's unlit
This seems like your one is unlit, as in, it doesnt interract with lighting
therefore shading doesnt affect it
Try changing it to lit
Oh.. I was guessing was the contrary indeed 😅
Now I learn something more, thank you 🍻
If using 2023.2 there's a "Canvas Graph" that you're meant to use for UI.
For older versions, shadergraph didn't really have support - though unlit or sprite unlit can work if the canvas is set to Screenspace-Camera, but not Screenspace-Overlay.
Oh awesome, thanks for the tip
Maybe that's because I'm Italian, and for Lit I was thinking about Light and so, self-illuminated 😅
to RFTM prolly would help a lot 😁
when doing custom lighting is it possible for the shading/selfshadows to be affected by the shadow strength?
it's a bit weird having really soft shadows but objects with pitch black shading
With custom lighting shadows can be any color your want
Usually shadows are an absence of a light, so they're illuminated by ambient light instead
"Shadow strength" is a variable that interpolates the shadow/shade color to the light color itself, as if the shadow was partially not there at all
It's not realistic at all but useful in some situations
yeah, but I don't know how to actually sample the "shadow strength" value
You mean the property of the light? I think that comes from outside the custom functions when you sample the light's or main light's shadowAttenuation
I don't know for sure, but if you're getting pitch black shading it sounds like what you actually want/need is to take the ambient lighting into account rather than using shadow strength
Should be able to use the Baked GI node to handle that - even if the object isn't actually lightmapped / using GI, that node will also sample the ambient probe
hmm I'll have to take a look thanks
hello, i have a problem with the toon shader not working with other lights other than the directional any ideas how to fix ?
i get the issue here how do i make my flashlight the main light ?
The Main Light Direction node is always the directional light. Assuming URP, additional lights are handled with a loop - that can't be done in the graph itself but can with a Custom Function node.
This may provide an example - https://github.com/Cyanilux/URP_ShaderGraphCustomLighting
(mainly AdditionalLights_float and/or AdditionalLightsToon_float functions)
any easy way to ad a line to this red line I painted in to this yellow circle?
doesn't have to look like that I just want it to be the circle's radius and then I can rotate it to the players direction via code
https://youtu.be/yE6wXG3UTIE?si=AnqN4MnOyyTSJk_I
Town in a cubicle using original shader, outside is custom lightning shader to get 2 different lighting environment in one scene.
Developing for Apple Vision Pro.
Real life fantasy world in your dining table.
A miniature fantasy world on a tabletop. Players take on the role of a deity, manipulating time and weather while observing NPCs living within this spatially projected cubicle. It's an immersive experience blending AR technology with god-game mechanics.
I think im having trouble with my shader graph for grasses
whenever i add the grass material
my game gets really laggy and my gpu memory usaage slowly increases over time
so i think i have a memory leak
but idk how ot fix it
heres the shader code
Is there any way to get the local transform position in a sprite shader?
I know you can get the world position using the unity_ObjectToWorld matrix
But i specifically need the local pos
do you have any 2D art software?
Yes. I'm pretty good with photoshop. I could make the image I want very very easily. I just know that I made the circle itself using shaders. Are you telling me this whole time I could have just made a transparent image and stuck it under there lmao
yuuup, and probably should. Leave shaders for specific effects you need to be/want to be dynamically applied, think some VFX outside particles, outline, water etc. Or if you think it's easier to dynamically render something based off some conditions rather than create all possible ways it could look. Not sure if I explained it neatly enough but you hopefully get the point
altough people often push boundaries on what they make using shaders and sample textures, it does take some time to use efficiently
Back in my day, we coded shaders in a simple text editor, uphill, both ways....
😉
Actually, yes...
its good for practice
followed the same vid 5x just to realize that it works if i dont make the color blue lol
thats sad
yup
im 5 days in on unity tho and i almost have a full game ready to go
just level design/ui/polish left really
obviously downplaying how much is left
but i have everything in my prefabs for a fully built experience
feeling pretty good
day 5 and you're learning shader graph? nice
Knowing the fact that such a thing exists and even daring to use it is impressive enough for me
I teach unity at university and I only teched the shaders after a few months of basics
I've made this game in gamemaker twice
so converting it to 3d and unity both for the first time is weird but it's been pretty smooth
it's kinda annoying to say this but it's true. Last time I installed unity I quit 30s in to the first tutorial. This time chat gpt was a massssssive difference.
i would just tell it to code me something and then figure out why it works
kinda annoying but it's the truth of it
Does anyone know of a water shader that could interact with a boat to cause wake or foaming as it moves through it?
I would have thought using it as a tool would allow me to 'cheat' instead of learn but it's actually been wayy more helpful than not.
it's really good for learning if you use it right actually
yeah I was shocked
prefabs and parameters are kinda crazy strong too
might be the wrong place to ask but do you know the best way for me to add rocks to my game? like big boulders? They don't need to have a ton of variety. they're just going to stand in the way and if the player runs into them they die. simple for now
In this video, you will learn how to create a water surface ripple effect. This effect can be combined with the water surface shader we made previously to make the water look more realistic.
Links :
神奇的小阿飞 : https://space.bilibili.com/31839293/
GitHub : https://github.com/Parrot222/Unity-Water-Shaders
Previous Video : https://youtu.be/xJk8MKQDq...
Ooooo okay let me check this out, Thank You!!
what do you mean by the best way? what is the problem with adding rocks
Wasn't sure if there was a tool for it or I just need to find some models and import
right now my dilemma is trying to brighten my ice up but aside from bringing my occlusion all the way down I'm not seeing an answer.
Okay I watched it, I have a few questions/concerns, I'm not the best when it comes to shader graph but this one looks straight forward but I want implement this effect to a realistic water, the videos says you can combine this ripple effect with their other realistic water shader, I'm just not sure how they do it since they don't say how
I believe the same person had another video about it
Part 2 : https://youtu.be/xJk8MKQDq2o
Part 3 : https://youtu.be/7_jYWF8EjyQ
Unity Version :
2020.3.26f1
Link :
kMirrors : https://github.com/Kink3d/kMirrors
Normal Map : https://www.filterforge.com/filters/723-normal.html
Music :
Acoustic Guitar Background Music Guitar Background Music
Way Home_ by @Tokyo Music Walker
Cozy Place
0:00 Nor...
Yeah I know they have that video as well, but I don't believe they have the ripple effect in that video, so I'm not sure how I would combine the two together
I think only the part that he creates the water shader (after 4:52) changes
just do everything else but with other water shader graph and use that instead for the material
So let me get this right, do everything in that video up until 4:52 then swap to the ripple effect video and put those in the graph I started with the previous video?
watch the part 1 and 2 for the water shader that you want first
after you make the water right, watch the ripple effect
instead of creating new shader, add the thing in the ripple effect to the water shader that you made previously
Okay thank you for clarifying😅 I'm new to the whole writing shaders thing so I appreciate it, let me give this a try
@sour gale I do a have a quick question I just thought of, once I'm done with it and have it the way I want it, how would I go about exporting it to another project?
just the shader graph or everything that you made about it?
Everything, Including any textures I have set with it
Kinda like other shader packages I have seen before, you know
right click in the "Project" window and select "Export Package..."
there you can select everything you wanna export
it saves it as a file. you can click and drag the file to the other project or right click to the project window and select "Import package"
Oh alright, that's a lot easier than I thought, thank you!
is there a way to enable shader debugging in shader graph?
Like enable debug symboms for the generate shader ?
Any idea why this code produces really dark and contrasted pictures? Left is the output file, right is the render texture
var prev = RenderTexture.active;
RenderTexture.active = _camera.targetTexture;
var dimensions = new Vector2Int(_camera.targetTexture.width, _camera.targetTexture.height);
var texture = new Texture2D(dimensions.x, dimensions.y);
texture.ReadPixels(new Rect(Vector2.zero, dimensions), 0, 0);
texture.Apply();
RenderTexture.active = prev;
var bytes = texture.EncodeToPNG();
var path = Path.Combine(Application.persistentDataPath, $"{DateTime.Now:yyyy-MM-dd_HH-mm-ss}.png");
await File.WriteAllBytesAsync(path, bytes);
How can I add this on my basecolor?
Add a new color input and multiply the sampled texture color with that color
It won't look exactly like in the inspector of that standard shader though
Could add some emission perhaps
i am new to shaders i still cant understand anything
about the lightning fix
i want the toon shader interact with my spot light not with my main directional lighting
how to get TexelSize from a Texture2D
In shader code you define a float4 inside the CG/HLSL block but outside functions with name as (textureName)_TexelSize.
In graphs, there's a Texture Size node (2022.2+ I think. Prior versions had a Texel Size node instead, even though it just accessed width/height)
Probably a linear/gamma colorspace difference thing. Maybe this method works - https://gist.github.com/Santarh/899ed0914cf7c4517bdb36233be66c19
Or maybe create Texture2D with linear param set to true (see constructors), not sure how that interacts with converting to png though.
Hi! Shader graph beginner here, I have a question. Why is my output only taking in the bottom texture? Isn't "Add" supposed to literally add two values together, like if white (or blue-ish white in my case) is 1, then it should go 1 + X.... which should never reach 0 (black), the output I'm getting on the edges, right?
can you try maximum instead of add?
if the thing on the bottom goes negative, then adding something will still yield zero. You can try doing maximum or using a saturate node after the multiply
Ohhh ok that makes sense, I didn't consider negative values
just a simple voronoi node with lerp
and animated it with a time node
but tbh I'm just experimenting and seeing what works haha
that's cool
it's probably possible without two lerp nodes, but this works so I left it
woah
chagning step in value changes dots scale
it's even better
hello, I am trying to create an outline/rim shader on a quad but Im not sure what's going wrong. I have used ones that work on 3D meshes but none for quads.
what do you mean by quad
for 2D?
Is there a way to make this the shadow and the edge of the table look smoother? It looks a bit wonky right now
No I m trying to make an xcom like overlay for the movable area:
I am generating a mesh that it's flat is what Im saying
This probably involves generating a mesh of the outlines themselves, not the interior parts
I guess similar to a LineRenderer
i want the interior area to have a hue
Well still, if you want "outlines" you need to generate the mesh with appropriate UVs or vertex colours to tell the shader where the outer parts are
It's not something you can really do in the shader itself
yeah that's what Im trying as well
{
vertices.Add( cellCorners[ i ] );
vertexColors.Add( i == 0 || i == 3 ? new Color( 1, 0, 0, 1 ) : new Color( 1, 1, 1, 1 ) );
// Assign the UVs corresponding to each vertex
uvs.Add( new Vector2( i % 2, i / 2 ) );
}```
but Im not sure what Im doing wrong 😭
{
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
o.color = v.color;
return o;
}
fixed4 frag (v2f i) : SV_Target
{
// Check if the vertex color is at full intensity, meaning it's an edge
float edgeIntensity = i.color.r;
fixed4 color = lerp(_FillColor, _EdgeColor, saturate(edgeIntensity - (1 - _OutlineWidth)));
color.a = lerp(_FillColor.a, 1, saturate(edgeIntensity - (1 - _OutlineWidth))); // Adjust alpha for fill and edge
return color;
}```
basically this
If you're using color.r to determine the outline I'd expect the C# code to set the vertex colors red to 0 or 1. Both seem to be using 1 in the ternary though (new Color( 1, ... ) : new Color( 1, ... ))
Well yeah, it seems you're just setting the corners of each tile. You'd need to detect which tiles are actually at the edges of the mesh and use that to set the vertex color, not just i == 0 || i ==3
May be able to ask in a coding channel if you need help with that, it's somewhat outside the area of shaders
Also since this one (and yours) seems to follow more of a grid stucture, it could also be based on a tilemap texture (probably similar to "wang tiles" or the "blob tileset"). For each quad you could calculate UV coords to select which tile of the texture should used, by comparing neighbouring tiles. Again more of a coding thing.
oh interesting idea
but Im not that good with shaders to set it up. Calculating edges can be C# but setting the uvs properly to show the part of the texture is harder for me 🙂
maybe Im better off just doing a line renderer 😭
In terms of cycles, how fast is matrix multiplication?
on GPU
The thing is currently in my shader I have a function I am calling in a loop, and each invocation calculates some point p * matrix
to be more precise I sometimes have a dozen or so function like that, each doing a matrix multiplication
so for example 20 matrix muls per iteration per pixel, max iterations cap around 200
I think I found it, it's around 14 cycles for vec4*m4x4: https://shaderlabs.org/wiki/Shader_Optimization
This page gives you an overview of how to optimize shaders.
probably also depends on the type of GPU, nvidia with tensor cores can do m4x4*m4x4 in 1 cycle iirc
The above shows the situation.
We are using UV Projection onto 3D objects, so 2D Isometric Sprites behave like 3d objects.
Lighting is Good!
EXCEPT...
...when lit from behind.
What I'd like is a shader that can add a directional rimlight, like this example here.
Our shader knowledge is however lacking, being a team of artists and 3 engineers. The help of a Tech Artist is on our near term hiring wishlist, but in the meantime a quick solution would be helpful, if anyone knows one to exist for this problem.
yes
How do you get the scene depth node like functionality in lit shaders
Trying to recreate the water shader but not using shadergraphs
Sample _CameraDepthTexture to obtain raw depth
For Linear01/Eye modes, use Linear01Depth(raw) or LinearEyeDepth(raw) functions (for srp code add _ZBufferParams as second param)
does this work with surface shaders?
Should do
This might act as an example - https://forum.unity.com/threads/accessing-depth-buffer-from-a-surface-shader.404380/#post-2640297
Ahh Thanks, I will try this out
is there a better way to add outline to low poly models? I tried 2 type of outlines
usualy the best one for me was offsetting the normals
left one has empty lines between each face because it's low poly
right one looks okay with this one but because it's based on scaling, it looks bad when the pivot point is not on center or the object doesn't have a circular shape
Hi. I want to fade my enemy after death. I am using a Toon shader and try to use SetFloat on the material. Why is material.SetInt("_TransparentEnabled", 1); not working but when I open the dropdown of the material in the shader then it suddenly works. What could be the problem?
To be clear, the gaps are due to the "flat" normals not to do with poly count specifically. If you can bake smoothed normals into an unused UV channel then you can use those in the shader instead of the surface normals, then it won't have gaps
If the toon shader uses a ShaderGUI it might be setting a keyword or changing other data on the material, not just the property value
Ah, I thought about that too. So maybe I should output all the parameter values and compare them?
@sour gale two other solutions I would consider are to (in terms of performance what Cyan suggested might be the best):
- use two different meshes to begin with (one for the outline, one for the object itself. this would be the easiest solution I'd guess)
- use only the smooth shaded mesh and reconstruct the flat shading in the fragment shader of the main material (possible with partial derivatives. there may be few artifacts of using that approach though)
Maybe. But it could be easier to just have a separate transparent material set up and swap it (i.e. renderer.sharedMaterial = transparentMat;) rather than trying to set keywords, renderQueue etc.
And can still generate an instance of that transparentMat if required, using new Material(transparentMat);. Ideally cache it and destroy later when no longer needed. Or use some kind of material pooling to reuse them between enemies.
Thank you both
Hm, but then I need a second material for all my enemies. Not sure about that, since I just want to change values. Thanks for your help, though!
Could also try to locate what ShaderGUI script the shader is using. That should be able to tell you what values it changes when the _TransparentEnabled box is ticked.
It's likely changing some blend properties and renderQueue to 3000. Possibly more though.
Is there any shader setup that colors based on intersection with gameobjects?
Looking to create an emissive glow around the edges that connect into that plane, so I can move it up and down and tthe shader will do an emission base on the intersection
like this?
Thank you I appreciate it
are you using urp?
I am
🤔 When applying that to a material nothing seems to happen, I have offset, multi, and color. But nothing exactly happens at the edges / intersections
offset 0.8
multi 2
try with this values
I'm using toon shader by unity technologies, and i wanna make an object to change a color through a script.. is that possible with toon shader?
Get a reference to the material and set its color property
How do I get my world canvas to react to lighting? I'm using URP
I often make a lit shader graph for it. You should be able to use simple lit as well
Hmm, that works but weird stuff is going on with the lighting
Thats it is bright in 1 spot?
Unity up to date? In case it's a known issue.
Maybe try the simple lit shader?
Worst case use quads to do the backgrounds?
Didn't Unity 2022 have UI shader graphs?
Add normal, and maybe tangent, to additional shader channel in the canvas inspector
Ah thanks, that fixed it
is it possible to get size of uniform array from shader or do I have to hardcode size in both shader and code that uses shader?
I tried material.GetFloatArray(propertyId) but it returns null
or alternatively setting it for shader but that doesn't seem to be an option since size should be compile time constant
how to get access to CBUFFERs (UnityPerDraw for example) in shaderlab