setting all objects active

hi i am new to coding with c# and unity and i am trying to build a little game, i implemented some coins and to destroy them i used the SetActive (false) when the collision is triggered, but I don’t know how to make them all respawn after I die (I already have a respawning system and that functions well); is there an easy way to make all the coins reappear?

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Coins : MonoBehaviour
{

[INDENT]private int money;

private void OnTriggerEnter(Collider other)
{[/INDENT]
        if (other.gameObject.layer == 7)
             {
             other.gameObject.SetActive(false);
[INDENT]      money += 1
      }
}[/INDENT]
}

If your coins all have a particular component on them, you can get all the coins and loop through them. You can use FindObjectsOfType() although this only finds active objects, so for this you’d need to get that at the start and then store it.

Another approach, which I’d recommend, would be to maintain a static list of coins:

public class Coin : MonoBehaviour {
   public static List<Coin> allCoins = new List<Coin>();

   void Awake() {
      allCoins.Add(this);
   }
   void OnDestroy() {
      allCoins.Remove(this);
   }
}

// anywhere
foreach (var coin in Coin.allCoins) {
coin.gameObject.SetActive(true);
}

thank you i tried the list method and it functioned but is there a way to add all the coins in the list without doing it manually for each one of them in the code?

Either add the coin to the list when originally instantiated, or have the coin add itself to the list in an attached script’s Start() method.

I’m not sure I follow? Having it in Awake() is pretty much as automated as it gets. You could use FindObjectsOfType, but keeping that list up to date (especially when the list includes inactive objects) would be much more work. The code as posted above will always have an up-to-date list, and it does so very efficiently.

1 Like

ok thank you very much