- Home /
How can I change the transparency of gameobjects with a dictionary?
I am trying to change the transparency of gameobjects based on their position using a dictionary. I am getting the correct float transparency value, but the actual transparency is not changing. Also, the renderer is not turning off for the gameobjects that have a transparency less than or equal to zero. In the inspector, I have set the Renderer Rend to Mesh Renderer of that gameobject. Here is my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Valve.VR;
public class AssignTransparency : MonoBehaviour
{
public GameObject obj;
public Renderer rend;
public Color color;
public float transparency;
public myDictionary m_Dictionary;
public SteamVR_Action_Boolean Trigger;
// Start is called before the first frame update
void Start()
{
rend = GetComponent<Renderer>();
rend.enabled = false;
color = this.GetComponent<MeshRenderer>().material.color;
m_Dictionary = obj.GetComponent<myDictionary>();
transparency = myDictionary.data[transform.position];
}
// Update is called once per frame
void Update()
{
if (Trigger.state && transparency > 0)
{
rend.enabled = true;
color.a = transparency;
}
}
}
Answer by CmdrZin · Jan 14, 2021 at 06:22 PM
Move these two lines to the beginning of your Update method.
rend.enabled = false;
transparency = myDictionary.data[transform.position];
else once your rend.enabled is set to true, it never goes false and your transparency per distance never updates.
That did not work. Also, my gameobject is not moving so I shouldn't have to update the transparency value. I have multiple clones of a prefab with this script instantiated at start at different positions. In the inspector, the transparency value is correct and the public color in the script is set to the correct transparency, but the actual transparency of the object doesn't change. Also, the renderer is turned off for all of the gameobjects, even when the transparency value is greater than zero.
because you are not changing the object's color. You're only changing the copy of it in a Color variable. Use
this.GetComponent<$$anonymous$$eshRenderer>().material.color.a = transparency;
or make a $$anonymous$$eshRanderer variable to have a reference to the object.
Your answer
Follow this Question
Related Questions
Unity making existing shader partially transparent 1 Answer
How to sort draw order on transparent character puppet. 0 Answers
Object transparency separate from shader? 0 Answers
Help understanding transparency in Deferred Rendering? 0 Answers
Standard shader - fade mode renders texture in wrong order 1 Answer