Z
Z
Zefirot2021-11-07 11:50:14
C++ / C#
Zefirot, 2021-11-07 11:50:14

How to change mass properties of elements?

I now need to change the alpha slowly for several elements, I do this

Update(){
  ActiveAlpha();
  }
private void ActiveAlpha(){
float alf += Time.deltaTime;
  for(int n = 0; n < ArrayObj; ++n){
    ArrayObj[n].gameObject.GetComponent<SpriteRenderer>().color = new Color(1f, 1f, 1f, alf);
    }
}

But maybe there is some method in the unit that is easier to change the properties of several elements?
but it’s like iterating over the array with each update ....

(this issue was raised in another topic, but I think it’s worth a separate topic)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Ente, 2021-11-07
@Zefirot

You create a script AlphaChanger.cs, it contains the following code

private SpriteRenderer spriteRenderer; //Кэшируем компонент
[SerializeField] private float speed = 1; //Скорость фейдинга
        
private void Awake()
{
  spriteRenderer = GetComponent<SpriteRenderer>();
}

public void Show()
{
  StartCoroutine(SetVisibility(1));
}

public void Hide()
{
  StartCoroutine(SetVisibility(0));
}

private IEnumerator SetVisibility(float finish)
{
  var color = spriteRenderer.color;
  while (true)
  {
    color.a = Mathf.MoveTowards(color.a, finish, speed * Time.deltaTime);
    spriteRenderer.color = color;
    if (color.a == finish) break;
    yield return null;
  }
}

You hang this script on all sprites that will fade. If you need to call it on the children of gameobjecta, start another AlphaChangerManager script, write such functions in it.
private AlphaChanger[] alphaChangers; //Кэшируем компоненты детей
private void Awake()
{
  alphaChangers = GetComponentsInChildren<AlphaChanger>();
}

public void ShowAll()
{
  alphaChangers.ForEach(a => a.Show());
}

public void HideAll()
{
  alphaChangers.ForEach(a => a.Hide());
}

The advantage is that you can call both a separate fade for any sprite, and all at once, through a common script

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question