- Home /
A little help?
I tried this but the object will not appear on the screen, what did I do wrong? My game is where you are a ball and you have to roll around to collect coins that spawn in random places.
void OnTriggerEnter(Collider collider)
{
if (collider.gameObject.name == "Player") {
Destroy(this.gameObject);
SpawnCoin();
}
}
void SpawnCoin()
{
Vector3 position = new Vector3(Random.Range(-10.0F, 10.0F), 1, Random.Range(-10.0F, 10.0F));
Instantiate(coin, position, Quaternion.identity);
}
Answer by Invertex · May 17, 2017 at 11:53 AM
You are destroying the object this script is on before you call SpawnCoin();
. When you destroy a GameObject, all components attached to that GameObject are destroyed as well, so the SpawnCoin();
method no longer exists and doesn't get called. Move that function to before the Destroy();
Also, with this code, the coin will only spawn when the Player actually collides with whatever object this script is on, assuming the object has a collider on it.
Your answer
![](https://koobas.hobune.stream/wayback/20220612122013im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Spawn origin point!! 0 Answers
Spawn random enemies in 2D 1 Answer
2d spawn across screen 1 Answer
Spawning prefabs randomly on top of existing tiles 2 Answers
I'm having problems with my code 1 Answer