- Home /
Clicking again does not place object
Left clicking once "grabs" the object and you can freely move it without needing to hold down the left click. What doesnt work is placing the object when hitting left click again.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ClickandDrag : MonoBehaviour
{
public GameObject road;
private float startPosX;
private float startPosY;
private bool isBeingHeld = false; //check to see if object is being clicked by mouse
private bool canBeHeld = true;
private bool pressed = true;
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); //just put a 0 for the "z"
} //these-->mousePos.x - startPosX and mousePos.y - startPosY also had to been added in this line to also make the object not move when clicking in a spot
//-----------------------------------------------------------------------------------------
//this section was all about getting the mouse position and setting the variable
private void OnMouseDown()
{
if (Input.GetMouseButtonDown(0)) //"0" is left button, "1" is right button
{
pressed = true;
}
if (pressed && Input.GetMouseButtonUp(0))//this sets it up so later on in the code when its placed, it cant be moved
canBeHeld = true;
{
Vector3 mousePos; //xyz of mouse position on scree of the whole computer
mousePos = Input.mousePosition;
mousePos = Camera.main.ScreenToWorldPoint(mousePos); //converting screen point of the mouse to the world point (the ingame point)
startPosX = mousePos.x - this.transform.localPosition.x; //these two lines makes it so the object doesnt move from clicking in a certain spot
startPosY = mousePos.y - this.transform.localPosition.y;
isBeingHeld = true;
pressed = false; //"false" means we can't move it after being placed
}
//the code below tried to get it so when clicking left again, the object is placed
if (Input.GetMouseButtonDown(0))
{
{
if (pressed)
{
isBeingHeld = false;
}
pressed = !pressed;
}
}
pressed = false; //when we let go of the mouse button, its saying we are letting go
}
}
Answer by Ady_M · Jan 07, 2020 at 02:20 PM
Maybe it's caused by the placement of the line:
canBeHeld = true;
It's between "if" and the open curly brace which means that everything inside the braces will execute regardless of the if-statement.
Thats in there to enable you to move it after clicking on it once. I got rid of that line and I could no longer move it.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Unity - destroy clone child object (button) 1 Answer
Instantiate and Scale with Mouse Click. 1 Answer
How to fire gui button on mouse right release 2 Answers
Distribute terrain in zones 3 Answers