Change material rendering mode in runtime

Hi, I’m trying to change the rendering mode of material to transparent when my player is near the object. Here is what I got so far.

using UnityEngine;
using System.Collections;

public class ChangeAlpha : MonoBehaviour
{
    public Renderer targetObject;
    public float alpha = 0.25f;

    Color newColor;

    void Awake ()
    {
        targetObject = targetObject.GetComponent<Renderer> ();
        newColor = targetObject.material.color;
    }

    void OnTriggerStay (Collider other)
    {
        if (other.gameObject.tag == "Player")
        {
            targetObject.material.SetFloat("_Mode", 3f);
            newColor.a = alpha;
            targetObject.material.color = newColor;
        }
    }

    void OnTriggerExit (Collider other)
    {
        if (other.gameObject.tag == "Player")
        {
            newColor.a = 1f;
            targetObject.material.SetFloat("_Mode", 0f);
            targetObject.material.color = newColor;
        }
    }
}

This code is not working, but when I change the material rendering mode to transparent before run time and remove the material.setfloat, it was working. but I want the material to be opaque when not trigger. So how can I do this?

Directly setting the variables on the Standard shader is a mixed bag - for the most part, it’s not designed for this kind of functionality. You’d be much better off writing 2 stripped down versions that do the things you want them to, and then swapping the shader on the material with this script.