Hi all,
I´m doing a project in which I have to instantiate several instances of the same object.
I´d like to destroy the object which I´m pressing with the mouse. And I can do this with this script (it´s attached to my prefab)
void Update ()
{
if (Input.GetMouseButton(0)) { Destroy(this.gameObject); }
}
But, when I press over one of my instantiated prefabs, every one in the scene is destroyed.
I think that it occurs because this script is fired in every gameobject, but how can I destroy only the one I want?
Thanks in advance!
cast a ray from your cam and use your MouseInputs for x,y nd add a z -
maybe Mathf.Infinity…your mouseinput will only give you x and y because it´s working juston 2d so you have to change these values from ScreenToWorld or something like that…
well, whats going to happen: if the ray hits an object it shoult turn it into your var target: GameObject → and on Input.GetMouseButton(0) you can call back your “DestroyFunction();” by using target.sendMessage(“DestroyFunction”);
i used this way to setup a missile target (like a heat seeking missile), works well!
found it abd modified it, but it´s not tested but this way should work
//attach this to your camera
private var ray: Ray;
private var targetRange : float = 150.0; // set it to Mathf.Infinity if you like to
private var rayHit : RaycastHit;
private var closestEnemy: GameObject;
function Update(){
ray = Camera.main.ScreenPointToRay(Vector3(Input.mousePosition.x,Input.mousePosition.y,0));
Debug.DrawRay(ray.origin, ray.direction * targetRange, Color.yellow);
// used some code from the ducumentation
var Enemies : GameObject[];
Enemies = GameObject.FindGameObjectsWithTag("YOUR_TAGGED_OBJECT");
var closestEnemy : GameObject;
var distance = Mathf.Infinity;
var position = transform.position;
for (var Enemy : GameObject in Enemies) {
var diff = (Enemy.transform.position - position);
var curDistance = diff.sqrMagnitude;
if (curDistance < distance) {
closestEnemy = Enemy;
distance = curDistance;
}
if(Physics.Raycast(ray, rayHit,targetRange) rayHit.transform == Enemy.transform){
LoggedTarget = Enemy ;
}
if (Input.GetMouseButton(0)){
LoggedTarget.sendMessage("DestroyFunction");
}
}
}
/// this part is attached to you instatianted prefab
function DestroyFunction(){
Destroy(this.gameObject);
}
I´m trying to do it, and I´ve almost got it. Thanks a lot PressAnyKeyToPlay!