- Home /
Destroy Prefab using Javascript
Hi, I'd like to ask how can I destroy a prefab using Javascript. What i am trying to achieve is that when a bullet or projectile is fired the prefab will be removed from the scene during gameplay. This is working until the second I have the prefab as a gameobject in the scene but when it is spawning from a certain coordinate they're immune to the destroy command. This is the code I am using:
function OnCollisionEnter(collision : Collision)
{
if(collision.gameObject.name == "EnemyUnit")
{
Destroy(gameObject.Find("EnemyUnit"),0);
}
}
I have a capsule collider attached and a rigidbody component to the prefab of "EnemyUnit". I don't know how to call a prefab in java to be targeted by the command. Could anyone help me please? YouTube and Google seem to be stuck on this one as well.
Answer by instruct9r · Feb 21, 2014 at 09:11 PM
Since you are using OnCollisionEnter, there is no need to use the Find, to have the object, because "Find" is taking a lot of resources from your CPU to search for that object.
function OnCollisionEnter (collision : Collision)
{
if (collision.gameObject.name == "EnemyUnit")
{
Destroy(collision.gameObject, 0);
}
}
you allready have the object stored in the collision variable, so just use it :).
Anyway, if i understand correct you want to shoot at certain object and destroy it, when the bullet hits that object correct? If so, it's better to use Raycast because if the bullet is moving too fast Unity might skip the collision because of the FrameRate. If you use raycast you will simply destroy, what's infront the ray and there will be no way to miss it.
I applied the change as you recommended but nothing is happening. The "EnemyUnit" just bounces off the projectiles ins$$anonymous$$d of getting destroyed. I attached the script to the projectile and the EnemyUnit separetely but no change.
What I am essentially trying to do is the character of a prefab gets destroyed upon contact with a bullet. But I've been siftin through several YouTube tutorials and google researching and of course unity forum and unity wiki but their method seem to be functional and working. But when I try to do the exact same thing nothing is happening. I've spent over twenty hours to find a solution but nothing.
Answer by whydoidoit · Feb 22, 2014 at 04:08 AM
If you are instantiating the EnemyUnits their name will not be EnemyUnit it will be EnemyUnit(Clone). Using tags for this would be a preferable approach.
BTW it's Javascript or Unity Script not Java - Java is a very different language that shares pretty much just the first part of its name with Javascript. I've modified your question to help out future visitors.
Your answer
Follow this Question
Related Questions
Instantiate prefabs just before it comes into view 2 Answers
Instantiate prefabs before it comes into view 0 Answers
Rigidbody2D getting destroyed in the inspector 2 Answers
Destroy a GameObject 2 Answers