I have 2 coins in my scene both of them called “Coin” (shared the same script below) if the ship Triggered the coin the coin Destroy by calling
Destroy(this.gameObject);
I also have a lander which is NOT activated (by unchecking the check mark next to the object name in inspector)
So when both coins are destroyed I want the lander to be active. I’ve done that and working by this code in the coin script :
var landing : GameObject;
function OnTriggerEnter2D (other : Collider2D) {
Destroy(this.gameObject);
if(Coin){
Debug.Log("Object exist");
} else {
landing.SetActive(true);
}
}
The result am having is the coin destroys when I hit the first coin (That what should happen) but when I hit the next coin it destroys but without making the lander active so how can I make the lander active only if no coin exist on the scene
Checking if nothing exist is inherently more difficult then checking if it does exist. To prove existence you just have to find one copy. To prove nonexistence you have to check every single GameObject and prove none of them are coins. This is expensive.
There are a couple of tricks to get around this
If you know the number of coins at the start you count each coin as it is destroyed. When the target is hit take action.
Each coin can register and deregister itself with a manager script. The manager script can simply count coins remaing
All of the coins can be parented to the same GameObject. Then you can simply use Transform.childCount.
You could also brute force it with GameObjec.Find
Let me know if you need specific code examples to implement each one.
I would instantiate the coins from a master script (sorry i use c#)
public int currentCoins;
public GameObject coinPrefab;
public GameObject landing;
void spawnCoins(int amount)
{
GameObject coinTemp = new GameObject();
for(int i = 0; i < amount; i++)
{
coinTemp = Instantiate(coinPrefab,new Vector3(0,0,0),Quaternion.Identity) as GameObject;
}
currentCoins = amount;
}
void Update()
{
if(currentCoins <= 0)
{
landing.SetActive(true);
spawnCoins(100); //choose your amount, increment it by level whatever, it's your choice
//or whatever function you choose to run after the landing.SetActive has been called.
}
}
public void removeCoins(int amount)
{
currentCoins -= amount;
}