Question by
TrusT96 · May 23, 2017 at 10:16 AM ·
c#2dgameobject
Set One GameObject Inactive If Another GameObject Is Active?
hello :D I'm currently building a simple 2D game and what i want to do is before the player have collected all the coins the key will be inactive, but once the player have collected all the coins the key will be active :)
how would i do this?
Comment
Best Answer
Answer by Bad_Irbis · May 23, 2017 at 03:11 PM
There are so many ways how you can do it.
Here is a one of many ways. It is proposed that all coins already placed on scene with tag "coin". This example is not so good, i would use events instead of link to GameManager from all coins, but this example is easier to understand.
public class GameManager : MonoBehaviour
{
// Attach this script anywhere on a scene
// Set here the link to your KeyGameObject on scene
public GameObject keyGameObject;
int coinsTotalCount;
int coinsCollected = 0;
void Awake()
{
// Disable your KeyGameObject
keyGameObject.SetActive(false);
// Get how many coins on scene
coinsTotalCount = GameObject.FindGameObjectsWithTag("Coin").Length;
}
// Call this method from CoinScript each time you collect coin
public void CoinCollected()
{
coinsCollected++;
// If you collected all coins - show KeyGameObject
if (coinsCollected == coinsTotalCount)
keyGameObject.SetActive(true);
}
}
public class Coin : MonoBehaviour
{
// Attach this script to coin prefab
// Set this link in prefab to your GameManager on scene
public GameManager gameManager;
void OnCollect()
{
gameManager.CoinCollected();
Destroy(gameObject);
}
}