- Home /
destroy gameObject when in range?
I made a script for my game, it basically allows you to "Harvest" whatever you put the script on and "drops" what you put into an ItemDrop transform. this is the script
#pragma strict
var itemdrop : Transform;
function Update ()
{
if(Input.GetMouseButtonDown)
Destroy (gameObject, 5);
Instantiate(itemdrop, transform.position, Quaternion.identity);
}
My only problem is due to the Input.GetMouseButtonDown, the prefab destroys itself as soon as i click play. I need it to only destroy itself when i am in range of it. How would i go about doing this? I would try RayCast but i don't know how. I prefer Javascript and any help is appreciated
Answer by Woj_Gabel_FertileSky · Sep 01, 2014 at 10:59 AM
You can do it by checking collisions in OnCollisionEnter(Collision collision) method. [code not tested]:
void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.tag == "someTag")
{
Harvest(collision.transform);
}
}
void Harvest(Transform obj)
{
Destroy (obj.gameObject);
Instantiate (objectToInstantiate, obj.transform.localPosition, Quaternion.identity);
}
Your answer
Follow this Question
Related Questions
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Setting Scroll View Width GUILayout 1 Answer
Destroying assets is not permitted to avoid data loss.? 3 Answers
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
OnTriggerEnter to Destroy Objects not working Correctly 1 Answer