- Home /
Coin collecting with prefabs
Hi all,
In a level of a game I'm currently making, the player (which is a prefab object) has to collect coins (prefabs also). The script I'm trying to get working will ideally destroy the coin on collision. Basic enough.
However, the current code I'm using will (when altered) destroy the player on impact, but not the coin (when I change it back to read 'Coin' instead of 'Player'; this was merely to see if it was working).
Anyone know why the devil this'd be happening? I can't find out, no matter what boxes I tick/untick.. it just won't work. Is it a double prefab thing?
Thanks again, any suggestions welcome.
using UnityEngine;
using System.Collections;
public class AsteroidCollision : MonoBehaviour
{
void OnCollisionEnter(Collision other)
{
if(other.gameObject.name == "Coin")
{
Debug.Log("Congratulations - You Collected 1 / 10 Coins!");
Destroy(other.gameObject);
}
}
}
I've tried attaching it to both, but to no avail. Would you recommend attaching this to the player?
O$$anonymous$$, I've tried a few other collider combinations, and I've gotten it to a stage where the player passes through the coin with no destruction, or physical interference from the coin. Its like the player is a ghost..
Does this help shed any more light on the problem?
Can you try adding a Debug to your OnCollision method to see see what's going on:
void OnCollisionEnter(Collision other){
Debug.Log(other.gameObject.name);
Debug.Log(gameObject.name);
}
I added the Debug to it - nothing co$$anonymous$$g up in the console.. but I messed around with the Is Trigger thing again - its either the coin passes through the player, or it knocks the player object completely off course. I have a (nearly) identical script for Application.Quit on collision that works perfectly. NO idea why this is being such a pain!
Answer by johnmadden1989 · Aug 19, 2014 at 03:44 PM
AH!!! Thanks a bunch Scribe you absolute beast! The tag trick worked fine! That must've been it. You're an absolute legend man.
Answer by RedDevil · Aug 19, 2014 at 01:26 PM
Does the coin have a collider set with IsTrigger?
Nope, I've never used that style of collider before. Do you mean in the code, or have I ticked the box that says 'Is Trigger'?
The tick box. and only attach the script to one object. If you attach it to the coin for example, have the script check if the inco$$anonymous$$g collision is the player. And do its stuff.
Your answer
Follow this Question
Related Questions
Javascript Detecting a prefab's child's collision 2 Answers
Flying Controls Collision Issues 0 Answers
Issues with instantiated prefabs 1 Answer
Tilemap Collider 2D preventing objects from moving 2 Answers
Spawn Prefab at Particle Collision 0 Answers