简体   繁体   中英

Update Shader on Runtime in Unity

I have an object which has a diffuse shader and on runtime I want the shader to switch to Diffuse Always Visible but this should trigger only if the unit is behind a specific object within the layer named obstacles.

First I tried to switch the object shader with the following code and the shader is changed in the inspector but not in the game during play. I tried placing and calling the shader from the resources and also created seprate materials but its not working.

Here is the code I am using in C#

Unit.renderer.material.shader = Shader.Find("Diffuse - Always visible");

As for the rest I was thinking of using a raycast but not sure how to handle this.

Thanks in advance

I only need the other concept now where the shader changes if a unit is behind an object!

For the trigger, how to handle it will depend a lot on how your camera moves.

To check in a 3D game , raycasts should work. Because whether or not something is "behind" something else depends on the camera's perspective, I would personally try something like this to start:

  1. Use Camera.WorldToScreenPoint to figure out where your object is on the screen.
  2. Use Camera.ScreenPointToRay to convert this into a ray you'll send through the physics engine.
  3. Use Physics.Raycast and check what gets hit. If it doesn't hit the object in question, something is in front of it.

Depending on your goals, you might want to check different points. If you're just checking if something is more than halfway covered by an object, doing a single raycast at its center is probably sufficient. If you want to see if it's at all occluded, you could try something like finding four approximate corners of the object and raycasting against them.

If it's a 2D game or the camera is always at a fixed angle (for example, in a side scroller), the problem is potentially a lot simpler. Add colliders to the objects, and use OnTriggerEnter or OnTriggerEnter2D (along with the corresponding Exit functions). That only works if the tiniest bit of overlap should trigger the effect, and it only works if depth doesn't really matter (eg in a 2D game) so your colliders will actually intersect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM