I just finished the 3D platformer tutorial and now I am trying some of the next steps. I am trying to remove the dead robot guard in the EnemyDamage.js.
I thought “Destroy(deadModel, 2)” would work nicely but I am getting this:
Can’t remove component.
Can’t remove Transform because BoxCollider, SphereCollider, AudioSource depends on it
I tried removing the rigidbody and then the model but that didn’t work either. How should I be removing this dead robot guard?
The Destroy function is indeed what you need here, but it will destroy the specific object you pass to it. In this case, you are passing a transform, but you actually need to pass the GameObject it is attached to:-
…what you are actually doing is creating a new, empty GameObject and then immediately destroying it (which is why you don’t see anything). If you want to destroy the object to which the script is attached, you should use:-
but I am trying to do something similar but with a sound;
Can’t remove Transform because AudioSource depends on it
I also tried the audio.PlayOneShot(shotSound); but had no idea how to destroy it on the GetButtonUp. Is it better to make it a prefab like I did or make it an AudioClip instead of a prefab?
You are instantiating a new object but destroying the original prefab. You need to keep a reference to the instance and destroy that when you’ve done with it:-
var windSound : Transform;
var windInstance: GameObject;
function Update()
{
if( Input.GetButtonDown("w") )
{
windInstance = Instantiate(windSound, gameObject.transform.position, Quaternion.identity);
}
if( Input.GetButtonUp( "w") )
{
Destroy(windInstance);
}
}
A bit late, but I might as well put info here for future capsulers(Yes im an Eve fan)
Here’s how I did it.
I just copied some of the code from the respawn script and made a new one called DestroyMe.js
just add the new script to your copperDead prefab, then link the copperDead prefab to your new script’s GameObject.
here’s the complete code:
/*
DestroyMe.js
This script checks if the player is out ofrange. If so, the enemyPrefab is automatically destroyed.
*/
var triggerRange = 0.0; // the distance within which the enemyPrefab should be destroyed.
var enemyPrefab : GameObject;
// Cache variables, used to speed up the code.
private var player : Transform;
// Called on Scene startup. Cache a link to the Player object.
// (Uses the tagging system to locate him.)
function Start ()
{
player = GameObject.FindWithTag("Player").transform;
}
// Called at least once every game cycle. This is where the fun stuff happens.
function Update ()
{
// how far away is the player?
var distanceToPlayer = Vector3.Distance(transform.position, player.position);
// is he out of range?
if (distanceToPlayer > triggerRange)
Destroy(enemyPrefab); // kill the prefab...
}
@script AddComponentMenu("Third Person Enemies/DestroyMe")
Im not an programmer so i dont know if this is the right way to do it, but it works.
note: don’t forget to set an initial value to triggerRange.