- Home /
How do I check if an object has a tag
I'm trying to make a selection system using tags on objects to identify if they can be selected or not. However, with my current code, it doesn't seem to be working
this is my script, if anyone knows what the problem is, please correct me; However, if There is a better way to do this, please tell me.
void Update() {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
//Ray from camera to mouse position
RaycastHit HitInfo;
//Hitinfo is being created to store info from objects hit by the ray
if (Physics.Raycast(ray, out HitInfo))
{
IsObjectSelectable();
}
else return;
}
void SelectingCounters()
{
if (Selected == false)
{
Hovering += SelectionCounter;
Debug.Log(Hovering);
}
else Hovering = 0;
ObjectSelected += SelectionCounter;
void ObjectSelector()
{
if (Hovering > 1)
{
Debug.Log("Selected!");
Selected = true;
Hovering = 0;
}
else if (ObjectSelected > 1)
{
Debug.Log("Deselected");
Selected = false;
ObjectSelected = 0;
}
}
void WasButtonPressed()
{
if (Input.GetMouseButtonDown(0))
{
ObjectSelector();
}
else return;
}
void IsObjectSelectable() { Selectable = GameObject.FindWithTag("Selectable"); DoesObjectHaveTag();
}
private void DoesObjectHaveTag()
{
if (HitInfo.collider.gameObject.CompareTag("Selectable"))
{
HoverTimer();
SelectingCounters();
WasButtonPressed();
}
else return;
}
void HoverTimer()
{
if (Hovering > 500)
{
Debug.Log("HoverOver Message");
Hovering = 2;
}
}
if (HitInfo.collider.gameObject.CompareTag("Selectable"))
Where is HitInfo declared? You are using it in the Update but it is a local variable declared in the Update. So the global one is most likely never assigned.
It seems your issue is not related to tag but null reference exception and variable scope.
Answer by YoucefB · Oct 03, 2017 at 05:17 PM
Probably HitInfo.collider.gameObject is returning a null reference , so you should check first if the gameObject is not null
if (HitInfo.collider != null && HitInfo.collider.gameObject.CompareTag("Selectable"))
{
//...
}
And if you want to know if an object has a tag use:
if(gameObject.tag != "Untagged")
Answer by Topthink · Oct 02, 2017 at 10:56 PM
Click on the object (in the scene, etc).
At the top of the inspector you will see a "Tag" field that initially is set to "Untagged".
You can change the tag of the object here to anything you want including adding a new custom tag of your own.
Good Luck.
I did that, and I still get the error:
NullReferenceException: Object reference not set to an instance of an object $$anonymous$$ouseController.DoesObjectHaveTag() (at Assests/Scripts/$$anonymous$$ouseController.cs:79)
Your answer
Follow this Question
Related Questions
Enemy wont react to bullets 2 Answers
OnTriggerEnter CompareTag not Working 1 Answer
Multiple object clicks in OnMouseDown script? 2 Answers
Kill object after time 1 Answer
Why wont my raycast compareTag properly? 2 Answers