Title is a little confusing. What I want is, after placing an object, you cannot drag it again after taking your finger off the mouse button. Right now, you can drag it again after taking your finger off.
The following code makes it so you can drag it each time when you click on it, idk what to add to it/modify it to make it so the object is no longer draggable after taking your finger off the mouse button:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ClickandDrag : MonoBehaviour
{
GameObject road;
private float startPosX;
private float startPosY;
private bool isBeingHeld = false;
void Update()
{
Vector3 mousePos;
mousePos = Input.mousePosition;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
if (isBeingHeld == true)
this.gameObject.transform.localPosition = new Vector3(mousePos.x - startPosX, mousePos.y - startPosY, 0);
}
//-----------------------------------------------------------
//this section was all about getting the mouse position and setting the variable
private void OnMouseDown()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 mousePos;
mousePos = Input.mousePosition;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
startPosX = mousePos.x - this.transform.localPosition.x;
startPosY = mousePos.y - this.transform.localPosition.y;
isBeingHeld = true;
}
}
private void OnMouseUp()
{
isBeingHeld = false;
}
Add another variable; e.g. bool canBeHeld = true. Set it to false when the object is picked up, and then don’t allow the object to be picked up if it is false.
Setting it to false under line 45 should be enough if you have correctly incorporated it into the condition on line 35 (and assuming nothing else is setting it to true).
I don’t see any place in your code where you are testing whether the variable is true; you are only setting it to true, then setting it to false.
Variables don’t do anything on their own, they’re just a way for your program to remember stuff. You also have to tell the program what you want it to do based on the stuff it remembers.
The simplest way to do that is to say
if (something is the case) then (do this thing)
Your OnMouseDown function already has a condition that says “only do this if mouse button #0 is down”. You need to modify it to also say “only do this if canBeHeld is currently true”.