- Home /
Instantiate only certain objects within a prefab
I am making a level platformer, and want all coins to respawn when you fall down into the void. I currently have the entire level being deleted and reinstantiated using a prefab, but this is just not working for a variety of reasons. Obviously it's taxing, escpecially when bigger levels get involved, and now, I don't want certain elements to do that (get reinstantiated - or, for that matter - deleted), like heart containers. SO... my solution that I am pursuing in the moment is to just reinstantiate the coins, which seems easy, but I can't access them, since they are no longer there (the player has collected them). This means that I have to access them through being children of the level prefab. The levels are stored in a array, and I access them only when they need to be instantiated or deleted. I also use a variable called _currentlevel to store the current one. So any solution is very much accepted. You have no idea how grateful I will be.
Edit: Maybe doing something with childCount could work? Is childCountWithTag a thing? :)
Another Edit: All the coins have the layer "Coins" and tag "Coin", and are triggers (obviously). Also ignore the "-1" after in the Instantiation line. I assure you it's necessary
Video Clip: https://drive.google.com/file/d/1ZExAJrAedoaB45sJkgjoUMjMU65AiDv4/view?usp=sharing
Thanks! Code Below.
if(Character.transform.position.y < -10)
{
playerRigidbody.velocity = new Vector3(0, 0, 0);
Character.transform.position = new Vector3(0, 0, 0);
Lives -= 1;
Score = 0;
PlayerController.Player.superJumps = 0;
_currentLevel = Instantiate(levels[Level-1].transform.GetChild(0));
}
Answer by Caeser_21 · Mar 17 at 09:02 AM
Instead of destroying them, you could make them 'Inactive' and add 1 to the coin counter...
Then when the Player falls down just make them 'Active' again
I has also posted this on stack overflow, because that tends to be more active, and both threads came up with this answer. Thank you so much!