- Home /
Delete object only when a certain cursor is enabled
I have a default cursor in the game, I do not want that cursor to delete my game objects when I click on it. I only want the object deleted after the cursor changes to the delete cursor.
Below are two scrips: Changing cursor back and forth between the delete and default one. And the other script is the destroy object when clicked script.
I know lines 10-15 in the "destroy" script is deleting the object with any cursor, not sure how to change it so its only the delete cursor
using System.Collections; using System.Collections.Generic; using UnityEngine;
//CHANGE MOUSE CURSER
public class ChangeMouseCursor : MonoBehaviour
{
public Texture2D cursorDefault; //this will be used right when game starts. our default cursor
public Texture2D cursorDelete; //our delete cursor after we click on the delete icon
public GameObject DeleteCursor;
//CHANGE CURSOR TO OUR DEFAULT ONE RIGHT WHEN THE GAME STARTS
void Start()
{
Cursor.SetCursor(cursorDefault, Vector2.zero, CursorMode.ForceSoftware);
//changes our mouse cursor right when game starts
}
//CHANGE DEFAULT CURSOR TO THE DELETE CURSOR AFTER CLICKING THE DELETE ICON
//THIS SCRIPT IS ATTACHED TO THAT ICON
void OnMouseDown() //after clicking, the cursor changes to the delete cursor
{
if (Input.GetMouseButtonDown(0)) //left click
{
Cursor.SetCursor(cursorDelete, Vector2.zero, CursorMode.ForceSoftware);
}
else if (Input.GetMouseButtonDown(1)) //right click to return to the default cursor
Cursor.SetCursor(cursorDefault, Vector2.zero, CursorMode.ForceSoftware);
}
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Destroy : MonoBehaviour {
//LEFT CLICK TO DESTROY GAME OBJECT WHEN THE MOUSE CURSOR IS CHANGED TO THE DELETE CURSOR
public Texture2D cursorDelete;
public GameObject CursoDelete
void OnMouseDown() //left mouse button for this
{
if (Input.GetMouseButtonDown(0)) //left mouse button
{
Destroy(gameObject);
}
}
}
Answer by DevManuel · Apr 29, 2021 at 08:43 AM
Try this:
In your class "Destroy" add a boolean called "destroy":
public bool destroy;
Then in your class "ChangeMouseCursor" change this value:
public Destroy _destroy;
// ...
void OnMouseDown(){
if (Input.GetMouseButtonDown(0)){
Cursor.SetCursor(cursorDelete, Vector2.zero, CursorMode.ForceSoftware);
_destroy.destroy = true;
}
else if (Input.GetMouseButtonDown(1)){
Cursor.SetCursor(cursorDefault, Vector2.zero, CursorMode.ForceSoftware);
_destroy.destroy = false;
}
}
Now go back to your class "Destroy" and add this:
void OnMouseDown() //left mouse button for this
{
if (Input.GetMouseButtonDown(0) && destroy){
Destroy(gameObject);
}
}
Hope it fixs your issue.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Enemy Spawner help 1 Answer
how to destroy enemy 1 Answer
Destroy () vs nulling an object created in script - c# 1 Answer