Hi, i modified a script to make objects invisible on collision for a top down game, for roofs and stuff.
using UnityEngine;
using System.Collections;
public class ScriptFade : MonoBehaviour
{
public Material baseMaterial;
public Material fadeMaterial;
void OnTriggerEnter2D(Collider2D collider){
if ( collider.gameObject.tag == "Player") {
GetComponent<Renderer>().material = fadeMaterial;
}
}
void OnTriggerExit2D(Collider2D collider){
if ( collider.gameObject.tag == "Player")
{
GetComponent<Renderer>().material = baseMaterial;
}
}
}
the method is switching between two materials, and made one of those invisible with a custom shader.
Is there a way to make this switch smoother?
nevermind, made a modification of another script using coroutines, this is it
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Roof2 : MonoBehaviour
{
private void OnTriggerEnter2D(Collider2D collider) {
if ( collider.gameObject.tag == "Player")
{
StartCoroutine(fadeOut(GetComponent<SpriteRenderer>(), 1f));
}
IEnumerator fadeOut(SpriteRenderer MyRenderer, float duration)
{
float counter = 0;
//Get current color
Color spriteColor = MyRenderer.material.color;
while (counter < duration)
{
counter += Time.deltaTime;
//Fade from 1 to 0
float alpha = Mathf.Lerp(1, 0, counter / duration);
Debug.Log(alpha);
//Change alpha only
MyRenderer.color = new Color(spriteColor.r, spriteColor.g, spriteColor.b, alpha);
//Wait for a frame
yield return null;
}
}
}
private void OnTriggerExit2D(Collider2D collider) {
if ( collider.gameObject.tag == "Player")
{
StartCoroutine(fadeIn(GetComponent<SpriteRenderer>(), 1f));
}
IEnumerator fadeIn(SpriteRenderer MyRenderer, float duration)
{
float counter = 0;
//Get current color
Color spriteColor = MyRenderer.material.color;
while (counter < duration)
{
counter += Time.deltaTime;
//Fade from 1 to 0
float alpha = Mathf.Lerp(0, 1, counter / duration);
Debug.Log(alpha);
//Change alpha only
MyRenderer.color = new Color(spriteColor.r, spriteColor.g, spriteColor.b, alpha);
//Wait for a frame
yield return null;
}
}
}
}