Striar
Striar

Reputation: 235

Changing the opacity of a transparent texture

I have a transparent texture of a chain link fence. I want the fence to fade in as the player approaches from the z direction. The problem I am having is that because the fence is transparent the opacity slider disappears and uses the image transparency. (I want the transparent texture to fade in) My current code:

public class WallFader : MonoBehaviour {


public GameObject wallone;

private Vector3 wallonetransform;

private Color wallonecolor;


public GameObject player;
private Vector3 playerposition;

private float PPX;
private float PPZ;

// Use this for initialization
void Start()

{
    wallonetransform = wallone.GetComponent<Transform>().position;
    wallonecolor = wallone.GetComponent<Renderer>().material.color;

}

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


    playerposition = player.transform.position;
    PPX = playerposition.x;
    PPZ = playerposition.z;

    // Distance to the large flat wall
    float wallonedist = wallonetransform.z - PPZ;

    if (wallonedist > 10)
    {
        wallonecolor.a = 0;
    }

    else
    {
        //fade in script
    }

  }

The fence never fades or disappears when wallonedist is > 10

Upvotes: 0

Views: 95

Answers (1)

Programmer
Programmer

Reputation: 125245

Color is a struct which means that changing it won't change the instance of of the Renderer. It is a copy of a color from the Renderer. If you change the color, you have to re-assign the whole color back to the Renderer for it to take effect.

public class WallFader : MonoBehaviour
{
    public GameObject wallone;

    private Vector3 wallonetransform;

    private Color wallonecolor;
    Renderer renderer;

    public GameObject player;
    private Vector3 playerposition;

    private float PPX;
    private float PPZ;

    // Use this for initialization
    void Start()
    {
        wallonetransform = wallone.GetComponent<Transform>().position;
        renderer = wallone.GetComponent<Renderer>();
        wallonecolor = wallone.GetComponent<Renderer>().material.color;
    }

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


        playerposition = player.transform.position;
        PPX = playerposition.x;
        PPZ = playerposition.z;

        // Distance to the large flat wall
        float wallonedist = wallonetransform.z - PPZ;

        if (wallonedist > 10)
        {
            wallonecolor.a = 0;
            renderer.material.color = wallonecolor; //Apply the color
        }

        else
        {
            //fade in script
        }
    }
}

Upvotes: 1

Related Questions