Im currently having problems destroying or possibly hiding an object after picking up a certain amount of coins.
Heres my code:
public GameObject coin;
public GameObject castleEntrance;
public int Coins = 0;
public Text coinText;
private void OnControllerColliderHit(ControllerColliderHit hit)
{
if (hit.gameObject.name == "coin")
{
Debug.Log("Picked up " + hit.gameObject.name);
Destroy(hit.gameObject);
Coins = Coins + 1;
coinText.text = "Coins: " + Coins.ToString();
if (Coins == 3)
{
Destroy(castleEntrance);
}
}
}
What i want is for it to destroy or if possible hide the entrance due to the required coins being picked up however it doesnt let me destroy the entrance. Need help asap as I cant wrap my head around it
When you write code, wrap it in [ code ] and [ /code ] tags (without the spaces) so it keeps its formatting.
When you say it “doesn’t let you destroy the entrance”, what does happen? I would start by putting a Debug.Log(“Destroying castle”); in there to see if it’s even reaching that branch.
With your current display, does it ever show 3 coins?
One note, even if it’s not your problem now, I’d look at this…
if (Coins == 3)
… because checking equality at the edge of ranges like that is problematic. When checking the end of ranges you want to use >= (greater than or equal) or <= (less than or equal) instead, as they’ll catch values past the end of your range and thus support cases where the exact value may be skipped over.
Apologies for the bad formatting im very new to unity. My display does show the coins and it does track the correct amount when they are collected. The limit on the map is 3 coins so you cant go over which is why I set it to equal.
With my code I get the error “Destroying assets is not permitted to avoid data loss” I created a prefab for the entrance but that hasnt helped either.
No worries. It’s more a convenience thing for the future than anything else. When code gets complex stuff like indentation levels are really important to someone trying to follow it so they can help you out.
It sounds like you’re trying to destroy the entrance using a reference to the prefab rather than the object in your scene.