How to check for tags?
My current code allows for all objects in the scene to be clickable. How do I make it so only gameobjects with a tag be clickable?
public class InputManager : MonoBehaviour { private bool draggingItem = false;
private bool mouseDragging = false;
private GameObject draggedObject;
private Vector2 touchOffset;
void Update()
{
if (LeftClick)
{
mouseDragging = true;
}
if (mouseDragging)
{
DragOrPickUp();
}
if (RightClick) {
mouseDragging = false;
DropItem();
}
}
Vector2 CurrentTouchPosition
{
get
{
Vector2 inputPos;
inputPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
return inputPos;
}
}
private void DragOrPickUp()
{
var inputPosition = CurrentTouchPosition;
if (draggingItem)
{
draggedObject.transform.position = inputPosition + touchOffset;
}
else
{
RaycastHit2D[] touches = Physics2D.RaycastAll(inputPosition, inputPosition, 0.5f);
if (touches.Length > 0)
{
var hit = touches[0];
if (hit.transform != null)
{
draggingItem = true;
draggedObject = hit.transform.gameObject;
touchOffset = (Vector2)hit.transform.position - inputPosition;
}
}
}
}
private bool LeftClick
{
get
{
// returns true if either the mouse button is down or at least one touch is felt on the screen
return Input.GetMouseButton(0);
}
}
private bool RightClick
{
get
{
// returns true if either the mouse button is down or at least one touch is felt on the screen
return Input.GetMouseButton(1);
}
}
void DropItem()
{
draggingItem = false;
}
}
Answer by Positive7 · Sep 28, 2017 at 05:09 PM
Your question has the answer. Replace if (hit.transform != null)
with if (hit.gameobject.tag == "clickable")
or add both , but hit.transform will be always true.
Thanks! When I went to replace it, I was given the error "Raycast 2D does not contain the definition for 'gameObject'"?
$$anonymous$$y bad if (hit.transform.tag == "clickable")
I ended up going with if (hit.transform.gameObject.tag == "clickable") but thank you for your help!
Your answer
Follow this Question
Related Questions
tagged objects problem 0 Answers
Having problem with scoring system., 0 Answers
Tag Editor is all grayed out 0 Answers
How to change another object's Tag 1 Answer
Tag an gameobject at runtime after a condition completed 1 Answer