- Home /
OnMouseDown - if statement
Hello. I hope you can help me. I am trying to disappear an object when I click another one. I want to distinguish between two different objects. This is my code, but it doesn't work out.
public GameObject boyGP2, dogGP2;
void Update () {
}
void OnMouseDown(){
if(gameObject.name=="boyGP2"){
Destroy(dogGP2);
}
if(gameObject.name=="dogGP2"){
Destroy(boyGP2);
}
}
Answer by Cains · Nov 04, 2013 at 02:15 AM
Some things to check:
Is this script attached to both GameObjects in the editor? Otherwise the script isn't running
In order for this to work you'd have to go to each GameObject's inspector in the editor and fill the two variables with GameObjects. Otherwise the dogGP2 and boyGP2 variables will be blank.
Another way to solve the second tip is to define the variables at scene start like below:
// Attach this script to both objects
public GameObject boyGP2, dogGP2;
void Start() {
boyGP2 = GameObject.Find("boyGP2");
dogGP2 = GameObject.Find("dogGP2");
}
void OnMouseDown() {
if(gameObject.name=="boyGP2"){
Destroy(dogGP2);
}
if(gameObject.name=="dogGP2"){
Destroy(boyGP2);
}
}
I always code in UnityScript, but I'm pretty sure I got something as simple as this right.
I've added the code to a terrain object; also I've used the inspector. First, I tried to associate a single code to each gameObject but it didn't work, too.
If you're attaching this script to a terrain, realize that the On$$anonymous$$ouseDown() will only be called when the player clicks on the terrain, and not the objects. And since I'm assu$$anonymous$$g the terrain's name is neither boyGP2 or dogGP2 the On$$anonymous$$ouseDown() function runs but doesn't do anything whenever you click the terrain.
The On$$anonymous$$ouseDown() function is called whenever the player clicks on the object the script is on, in this case the terrain.
If you attach the script I posted above to both GameObjects ins$$anonymous$$d and not the terrain I believe it will work as you expect it to.
Answer by alok1974 · Nov 04, 2013 at 03:08 AM
First, make sure you have colliders on your game objects or else OnMouseDown() will not be called.
This script should be able to take care of it. Just attach it on both the game objects.
using UnityEngine;
using System.Collections;
public class DestroyOther : MonoBehaviour
{
private GameObject other;
void Start ()
{
switch (gameObject.name) {
case "boyGP2":
other = GameObject.Find ("dogGP2");
break;
case "dogGP2":
other = GameObject.Find ("boyGP2");
break;
}
}
void OnMouseDown ()
{
Destroy (other);
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613121208im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How do I destroy my player on contact? 2 Answers
OnMouseDown() function 0 Answers
Enemy does not destroy player in 2D 1 Answer
How do I destroy an object after giving the player a point? 2 Answers