How to change the alpha of every GameObject with the same Tag ?
Hi, I have a problem with my script. Visual told me there is an error in the FOREACH. But i don't understand.
I want to make every GameObject with the tag "AR-Obj" translucide by changing the alpha of their own material. The alpha will be a public variable that we must change when we want before the game. For that i use the "FindGameObjectsWithTag" to create a List of thoose GameObjects.
public class AR_Renderer : MonoBehaviour {
public GameObject[] Ar_Obj_Tags;
void Start()
{
if (Ar_Obj_Tags == null)
{
Ar_Obj_Tags = GameObject.FindGameObjectsWithTag("AR_Obj");
}
foreach (GameObject Ar_Obj_Tag in Ar_Obj_Tags)
{
Renderer r = Ar_Obj_Tag.GetComponent<Renderer>();
Ar_Obj_Tag.r.material.color.a = 0;
}
}
}
Any help please ?
Answer by Landern · Apr 21, 2017 at 01:20 PM
On line: 15.
You are iterating through each item/element in your Ar_Obj_Tags array. On line 15 after finding the Renderer that you called "r", you try and gain access to a member of Ar_Obj_Tag which is a GameObject which doesn't have a definition for a variable called "r". Also the type Color is a struct and so you can't directly modify Color
Change the foreach to:
foreach (GameObject Ar_Obj_Tag in Ar_Obj_Tags)
{
Renderer r = Ar_Obj_Tag.GetComponent<Renderer>();
Color newColor = r.material.color;
newColor.a = 0;
r.material.color = newColor;
}
and remove the Ar_Obj_Tag. from the beginning.
Thank you, I understand better.
I have no more error but when the game is running, the array AR_Obj_Tags stays empty. I have checked and my GameObject has weel the tag "AR_Obj". I thought that the following part of my code fills automatically the array Ar_Obj_Tags :
Ar_Obj_Tags = GameObject.FindGameObjectsWithTag("AR_Obj");
Like it's explained here : https://docs.unity3d.com/ScriptReference/GameObject.FindGameObjectsWithTag.html
EDIT :
The following code works well, sorry.
public GameObject[] Ar_Obj_Tags;
public float alpha = 0.0f;
void Start()
{
Ar_Obj_Tags = GameObject.FindGameObjectsWithTag("AR_Obj");
foreach (GameObject Ar_Obj_Tag in Ar_Obj_Tags)
{
Renderer r = Ar_Obj_Tag.GetComponent<Renderer>();
Color Aph = r.material.color;
Aph.a = alpha;
r.material.color = Aph;
}