How can I decrease opacity in unity? - c#

I see this subject in stack over flow but I think it is false
Making an object 'transparent' so it cannot be seen is not the most efficient way to do things. What you rather want to do is make the renderer inactive when you don't want to see it, and active when you do.
If you click on your gameObject in the editor, there should be a Mesh Renderer as one of the components.
To set it to inactive from a script attached to this same gameObject, you can do this...
gameObject.GetComponent<Renderer> ().enabled = false;
If you really want to use transparency, you can do this...
gameObject.GetComponent<Renderer> ().material.color.a = 0;
Although if you are setting transparency, you need to make sure the shader the material is using supports transparency. I would suggest using the Legacy Shaders/Transparent Diffuse shader.
How I can use:
gameObject.GetComponent<Renderer> ().material.color.a = 0;

For those who might still come across this question, gameObject.GetComponent<Renderer> ().material.color is not a variable. Create a variable as such:
var trans = 0.5f;
var col = gameObject.GetComponent<Renderer> ().material.color;
Then assign your value:
col.a = trans;
Also be aware that not all shaders have a _Color property. In my case, I had to use:
var col = gameObject.GetComponent<Renderer> ().material.GetColor("_TintColor");

How I can use:
gameObject.GetComponent<Renderer> ().material.color.a = 0;
As you already stated in your own question, the object you call this on must have a shader which supports transparency. In Unity5, when using the standard shader, you must explicitly set it to "Transparent" to be able to manipulate the alpha value.
It should also be clear to you that the alpha value is a float which goes from 0.0f to 1.0f, so e.g. setting
gameObject.GetComponent<Renderer> ().material.color.a = 0.5f;
will make the object 50% transparent.

Select your material and change its Rendering Mode to Transparent.
Then, add the below script.
using UnityEngine;
public class MakeTransparent : MonoBehaviour
{
public GameObject currentGameObject;
public float alpha = 0.5f;//half transparency
void Start()
{
currentGameObject = gameObject;
}
void Update()
{
ChangeAlpha(currentGameObject.GetComponent<Renderer>().material, alpha);
}
void ChangeAlpha(Material mat, float alphaVal)
{
Color oldColor = mat.color;
Color newColor = new Color(oldColor.r, oldColor.g, oldColor.b, alphaVal);
mat.SetColor("_Color", newColor);
}
}
Change the alpha value in the inspector on runtime.
Here is the video explanation.

Try in this way
var other : GameObject;
other.renderer.material.color.a = 0.5f; // 50 % transparent
other.renderer.material.color.a = 1.0f; // 100% visible

Related

Trying to change 2D sprite colors with a list and nothing renders

I'm a new to programming and I'm trying to change the sprite color of a gameObject using a list that contain colors in Unity. When I spawn a new object each time, the inspector shows a different color for the object (which seems to show that the code works) but nothing render in the scene when the game is on. It's like the code works but is missing something.
Here's the code
[SerializeField] private List<Color> _listeCouleurs = new List<Color>();
// Start is called before the first frame update
void Start()
{
SpriteRenderer spriteRender = GetComponent<SpriteRenderer>();
Color c = _listeCouleurs[Random.Range(0, _listeCouleurs.Count)];
_listeCouleurs.Add(spriteRender.color);
spriteRender.color = c;
}
Hope someone can help me cause I don't see any solution to this and there's nothing on the internet that can help me fix this bug.
When you added colors to the list with the "eyedropper", the transparency is set to 0, set it to opaque (255 in the RGB range, 1 in Color.a scale) and everything will be visible:
Color c = _listeCouleurs[Random.Range(0, _listeCouleurs.Count)];
c.a = 1.0f;
_listeCouleurs.Add(spriteRender.color);
spriteRender.color = c;

Unity 2018.3 HDRP - Change material color programatically?

I am using the new HDRP/LitTesselation shader.
I would like to change the Base Color + Opacity at runtime:
I added this code to the game object's script:
void start()
{
Color color = new Color(100, 50, 100, 150);
//Fetch the Renderer from the GameObject
Renderer rend = GetComponent<Renderer>();
//Set the main Color of the Material to green
rend.material.shader = Shader.Find("_Color");
rend.material.SetColor("_Color", color);
}
But it generates an Hidden/InternalShaderError error in the shader. Can anyone point me in the right direction?
I got it working by modifying these lines as follows:
rend.material.shader = Shader.Find("HDRenderPipeline/LitTessellation");
rend.material.SetColor("_BaseColor", color);
This is for HDRP/Lit:
private Material _mat;
void Start()
{
Renderer nRend = GetComponent<Renderer>();
_mat = nRend.material;
}
void Update()
{
Color nNew = //do whatever you want here
_mat.SetColor("_BaseColor", nNew);
}
I once read that "sharedMaterial" should be used instead of "material".
However, I think that was just a typo. "sharedMaterial" would affect ALL HDRP/Lit materials, I think.
The issue is most likely with this line:
Color color = new Color(100, 50, 100, 150);
According to the Unity docs, colors should be initialized with values from 0 to 1 instead of with larger numbers. My guess is that if you change the value of your color variable accordingly that will solve the issue. The rest of your code seems to follow the form found here.
Try out the following:
Color color = new Color(0.39f, 0.196f, 0.39f, 0.588f);

How to fade out / disapear a GameObject slowly?

I have a function where I have to dispear some GameObjects, at the moment I use SetActive(false) but it should not disapear instantly, it should disapear slowly in 2 or 3 seconds. I guess opacity should go slowly to transparent or something like that...
public void SlotCheck(string gemColor,GameObject slotColor,GameObject
puzzleStuk,ref int scoreGem,ref bool Visibility)
{
if (DragHandler2.itemBegingDragged.name.Contains(gemColor)
DragHandler2.itemBegingDragged.transform.parent.name == "green_small_b")
{
Visibility=false;
puzzleStuk.SetActive(Visibility);
slotColor.SetActive(false);
DragHandler2.itemBegingDragged.SetActive(false);
scoreGem--;
}
}
This is my approach using coroutines.
void Awake()
{
StartCoroutine(FadeOutMaterial(1f));
}
IEnumerator FadeOutMaterial(float fadeSpeed)
{
Renderer rend = objectToFade.transform.GetComponent<Renderer>();
Color matColor = rend.material.color;
float alphaValue = rend.material.color.a;
while (rend.material.color.a > 0f)
{
alphaValue -= Time.deltaTime / fadeSpeed;
rend.material.color = new Color(matColor.r, matColor.g, matColor.b, alphaValue);
yield return null;
}
rend.material.color = new Color(matColor.r, matColor.g, matColor.b, 0f);
}
You can get the Renderer component of a GameObject and then change the alpha of the color gradually in Update().
Ex:
Renderer renderer;
void Start() {
renderer = GetComponent<Renderer>();
}
void Update() {
Color oldCol = renderer.material.color;
Color newCol = new Color(oldCol.r, oldCol.g, oldCol.b, oldCol.a - 0.01f);
renderer.material.color = newCol;
}
Of course you shouldn't use hard coded values like 0.01f, but instead a value from the inspector. This should also be multiplied by Time.deltaTime as to not make the fade speed FPS-based.
Some of the names or the like might not be 100% correct in this example, but it should give you an idea of which part of the Unity API documentation to look around in.
You can use a Coroutine combined with Color.Lerp to reduce the alpha value of all materials over time.
(I'm assuming you mean meshes with Renderers here not UI stuff but this would work in similar ways as well)
// How long should fading take (in seconds)
public float fadingDuration = 1;
// For storing Renderer components
private Renderer[] renderers;
// For storing original color data
private List<Color> originalColors = new List<Color>();
// For storing FadeOut color data
// (= Original data with alpha=0)
private List<Color> fadeOutColors = new List<Color>();
private void Awake() {
// Get all renderers, own and children
renderers = GetComponentInChildren<Renderer>(true);
// Run through renderers
foreach(var rend in renderers)
{
// Run through all materials
foreach (vat mat in rend.materials)
{
// Get original color
var color = mat.color;
// Add to original list
originalColors.Add(color);
// Get fadeout color (alpha 0)
var fadeoutColor = new Color(color.r, color.g, color.b, 0);
// Add to fadeout list
fadeoutColors.Add(fadeOutColor);
}
}
// Call this to start fading
public void StartFadeout()
{
StartCoroutine(FadeOut());
}
private IEnumerator FadeOut()
{
var timePassed = 0;
while(timePassed < fadingDuration)
{
// Get factor between 0 and 1 depending on passed time
var lerpFactor = timePassed / fadingDuration;
// Run through all renderers
int colorIndex = 0;
foreach(var rend in renderers)
{
// Run through all materials
foreach (vat mat in rend.materials)
{
// Set color interpolated between original and FadeOut color depending on lerpFactor
mat.color = Color.Lerp(originalColors[colorIndex], fadeOutColors[colorIndex], lerpFactor);
// Count up index
colorIndex++;
}
}
// Add time passed since last frame
timePassed += Time.deltaTime;
// return to render the frame and continue from here in the next frame
yield return null;
}
// In the end just to be sure apply the final target values (FadeOut colors)
// Alternatively you could also deactivate/destroy the object here
// Run through all materials
int colorIndex = 0;
foreach(var rend in renderers)
{
// Run through all materials
foreach (vat mat in rend.materials)
{
// Set color to final FadeOut value
mat.color = fadeOutColors[colorIndex];
// Count up index
colorIndex++;
}
}
}
Note that for transparency to work at all your materials have to use a shader supporting transparency.
This might however not be the best solution regarding performance. Especially since multiple Renderers might reference the same Material so in the current example there are maybe some redundancies.
But if you anyway have only one Renderer with one Material you could adjust the code a bit and skip all the loops ;)
As mentioned by previous answers, you can do it easily manipulating
meshrenderer.material.color=new Color (,,,x);
One important detail to add is that material needs to be set up in the transparent queue (and supports transparency). This is achieved via a dropdown in the material inspector, for Standard Surface shaders, but has to be dealt with in custom shaders by using one minus alpha blending mode and transparent queue in custom shaders
Tags {"Queue"="Transparent" "RenderType"="Transparent" }
Blend SrcAlpha OneMinusSrcAlpha

Change sprite color in unity using GUI button

I'm creating a Unity program where I want to use a GUI button to change the color of a sprite. I have the following code in my script but I'm not sure how to change the color.
public GameObject WantedSprite;
private void DrawWindow(int windowID)
{
if (GUI.Button(new Rect(50, 150, 100, 50), "Change the Ball's color"))
{
var component = WantedSprite.GetComponent<Color>();
component.g = Random.Range(0, 255);
component.r = Random.Range(0, 255);
component.b = Random.Range(0, 255);
}
I'm learning Unity so that's a little of my background, thank you!
You're on the right track..
The component you want to reference is the SpriteRenderer on the game object. This has access to, and controls the color property.
Make a new instance of Color and assign it's values (note: you may need to set .a (alpha) property as well to 255, if the sprite goes transparent).
Once you've constructed the color, you can then assign the SpriteRenderers color to the new one.
SpriteRenderer component = WantedSprite.GetComponent<SpriteRenderer>();
Color newColor;
newColor.r = Random.Range(0.00f,1.00f);
newColor.g = Random.Range(0.00f,1.00f);
newColor.b = Random.Range(0.00f,1.00f);
newColor.a = 1;
component.color = newColor;

Unity3D: Change skybox color via script?

I am working on a game in the engine Unity, and am trying to make the skybox change color based on the time of day, but I can't seem to find out how to get it working.. What I want to do, I think, is to change the color of the material I use for the skybox in render settings, and be able to set it using one variable for red, one for green and one for blue.
I am using C#.
Thanks in advance for all answers :)
From the code you displayed in the comment:
RenderSettings.skybox.SetColor("_Tint", 0, 0, blue)
I think you mean
RenderSettings.skybox.SetColor("_Tint", Color.blue)
no need for extra zeros and remember that the color "blue" is a member variable of the Color class.
Next you would have to develop a time system and based on the time var you pass to the script controlling the skybox renderer you would then use a Lerp function to smoothly transition from one color to the next... like this
using UnityEngine;
using System.Collections;
public class example : MonoBehaviour {
public Color colorStart = Color.blue;
public Color colorEnd = Color.green;
public float duration = 1.0F;
void Update() {
float lerp = Mathf.PingPong(Time.time, duration) / duration;
RenderSettings.skybox.SetColor("_Tint", Color.Lerp(colorStart, colorEnd, lerp));
}
}
Then you could write a function to change the colorStart and colorEnd...
Hope this helps...
We can change Skybox color using the _Tint property. RenderSettings is the base class used to change the render properties at run time. For ensuring the attribute is existing in the skybox is done by the HasProperty(). SetColor() is used to set the color of the skybox.
if (RenderSettings.skybox.HasProperty("_Tint"))
RenderSettings.skybox.SetColor("_Tint", Color.red);
else if (RenderSettings.skybox.HasProperty("_SkyTint"))
RenderSettings.skybox.SetColor("_SkyTint", Color.red);
you can make your own skybox too in unity by changing texture shape into a cube one then apply for those changes it will create a cube mesh which you can simply drop it into your unity editor scree.
and if you want to load multiple skybox materials on run time by click on button
I have that code for that i hope it will help you for building a project in which you want to change skybox by some time or by using other input method.
enter code here
public class skybox : MonoBehaviour {
enter code here
public Material[] secondSkybox;
public static int i = 0;
public void skyboxOn()
{
if (i == 0) {
RenderSettings.skybox = secondSkybox[0];
i++;
}
else if(i==1)
{
RenderSettings.skybox = secondSkybox[1];
i++;
}else if(i==2)
{
RenderSettings.skybox = secondSkybox[2];
i=0;
}
}
}
and if you want too change the color of skybox which can be done by using this line of code
RenderSettings.skybox.SetFloat ("_Exposure", Mathf.Sin (Time.time * Mathf.Deg2Rad * 100) + 2);

Categories