Search Unity

  1. If you have experience with import & exporting custom (.unitypackage) packages, please help complete a survey (open until May 15, 2024).
    Dismiss Notice
  2. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice

destroy when mouse click

Discussion in 'Scripting' started by cybertree, Jun 23, 2015.

  1. cybertree

    cybertree

    Joined:
    Jun 19, 2015
    Posts:
    100
    I want a cube to be destroyed when i click it,but my script has these following problems.
    1-The cubes it is attached to(2) destroy all at a time.
    2-It gets destroyed when i click anywhere not only when it is on top of the cube.
    I have 2 different codes,let me post them both.
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class checkifclick : MonoBehaviour {
    5.  
    6.     public int points = 0;
    7.  
    8.     void OnMouseDown () {
    9.         Destroy(gameObject);
    10.         points = points + 1;
    11.     }
    12.  
    13.     void Update() {
    14.         Debug.Log (points);
    15.     }
    16.  
    17. }
    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. public class checkifclick2 : MonoBehaviour {
    5.     public static int points = 0;
    6.     void Update() {
    7.         if (Input.GetMouseButtonDown(0)) {
    8.             points = points + 1;
    9.             Destroy (gameObject);
    10.         }
    11.         Debug.Log (points);
    12.     }
    13. }
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    first one should work, although trying to the "points" thing in the same script isn't going to work beyond since you are destroying the gameobject and all the scripts attached to it, and if you have multiple of this script on multiple objects they all have their own points total...

    Second one doesn't check what the mouse is over, that will destroy every things with the code attached to it when the mouse button is clicked, and again, the points thing is redundant.


    edit: and posting multiple threads for the same thing really isn't useful.