0
\$\begingroup\$

I make s shader file and drop it on object with material. I wrote this script to run shader when press Space button. All is good except that script not load shader when run the game !! I have to do it manually only !

public Material _shader;
public float timer = 0;

// Start is called before the first frame update
void Start()
{

    _shader = gameObject.GetComponent<Material>(); // Not setting shader !!
    _shader.SetFloat("Vector1_F92326F1", timer);

}

// Update is called once per frame
void Update()
{

    if (Input.GetKeyDown(KeyCode.Space))
    {
        timer += 0.1f;
        _shader.SetFloat("Vector1_F92326F1", timer);
    }

}
\$\endgroup\$
2
\$\begingroup\$

A Material is not a Component, so you can't get it with GetComponent.

Did you mean to ask the attached Renderer component for (a local copy of) the material it's using to render?

 Material material = GetComponent<Renderer>().material;

Don't forget to Destroy() this copy of the material when you're done with it, or it leaves extra garbage for the engine to clean up during scene loads.

Also, watch out that a Material and a Shader are two different things. A Shader is the GPU code — you might draw lots of different materials with one set of GPU code. A Material is a bundle containing a reference to a shader together with the collection of parameters (textures, colours, intensities etc) that describe its its unique look.

\$\endgroup\$
  • \$\begingroup\$ Thank you for your comment and solve my issue. What i'm trying to do is making my enemy dissolving when his HP is zero. There are around 20 enemies "clone" on the scene. Hope this will not eat GPU later. \$\endgroup\$ – user43474 Jan 12 at 19:05
  • 1
    \$\begingroup\$ Have you considered using Material Property Blocks for this purpose? They're a little lighter-weight than copying materials for each one. \$\endgroup\$ – DMGregory Jan 12 at 19:08
  • \$\begingroup\$ MPB, no. My idea is to make one single enemy" with one shader file" in my scene. Now, make several clones of it. Like, many "tower defense" game style. In my case, if i will use MPB ? Do I need to change the script only or do other things also ? \$\endgroup\$ – user43474 Jan 12 at 20:30
  • 1
    \$\begingroup\$ Sounds like you should read the docs linked above, and post a new question if you're still unsure. \$\endgroup\$ – DMGregory Jan 12 at 20:34
  • \$\begingroup\$ Great to refer to this MPB. I will read more about this. Thank you so much. \$\endgroup\$ – user43474 Jan 12 at 21:04

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.