- Home /
I am using this script to drag/move gameobjects with the mouse. I need the script to ONLY recognize objects with a TAG, like "Painting", How can I fix this?
using UnityEngine; using System.Collections;
public class DragAndDrop : MonoBehaviour { private bool _mouseState; private GameObject target; public Vector3 screenSpace; public Vector3 offset;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
// Debug.Log(_mouseState);
if (Input.GetMouseButtonDown(1))
{
RaycastHit hitInfo;
target = GetClickedObject(out hitInfo);
if (target != null)
{
_mouseState = true;
screenSpace = Camera.main.WorldToScreenPoint(target.transform.position);
offset = target.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z));
}
}
if (Input.GetMouseButtonUp(1))
{
_mouseState = false;
}
if (_mouseState)
{
//keep track of the mouse position
var curScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z);
//convert the screen mouse position to world point and adjust with offset
var curPosition = Camera.main.ScreenToWorldPoint(curScreenSpace) + offset;
//update the position of the object in the world
target.transform.position = curPosition;
}
}
GameObject GetClickedObject(out RaycastHit hit)
{
GameObject target = null;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray.origin, ray.direction * 10, out hit))
{
target = hit.collider.gameObject;
}
return target;
}
}
Answer by SavageX370 · Nov 17, 2018 at 12:14 AM
Hey! Thanks to both of you for your replies! I realized with your help that this was the proper line needed to make it work: if (target != null && target.tag == "Painting") Thanks a lot!
Answer by hexagonius · Nov 14, 2018 at 07:20 PM
Add a check for the tag of the hit.collider.gameobject within your if Raycast and only choose it as a target if it matches. Use CompareTag method on the gameobject.
Hey! as a new-ish unity/scripting user, i'm not sure how that check looks in C-Sharp.
Answer by arbazgillani · Nov 15, 2018 at 06:06 AM
On line 16 add if (target != null&⌖.tag=="Painting")
Your work will be done.
Hey thanks for the reply! Unfortunately the script does not recognize "⌖" as a valid expression term. Is that a typo? or am I screwing something up.
Your answer
Follow this Question
Related Questions
Head shoot and body shoot not working with realistic fps characterDamage 0 Answers
Right Click to Ignore All But Terrain, How? 1 Answer
Ray cast affects all colliders in scene if mouse button is not releasesd. 1 Answer
How to make ray hitting only game objects with tag from list 2 Answers
Reacting to terrain height changes without a rigidbody component 0 Answers