I created a script that uses RayCasting for detecting two Prefabs - One prefab has a tag called "target" and the second prefab has a tag called "unTarget". On click on prefab 1 with "Target" tag its supposed to increment count and when clicking on prefab 2 with "unTarget" tag its supposed to decrement the count. This seems to work when only one Prefab is in the scene. It will increment/decrement when only one is added and clicked. When both prefabs are in the Scene both prefabs will increment. I am not sure why this is happening. Any Help or Ideas? Sorry if my code is a bit messy.
using UnityEngine;
using System.Collections;
public class clicks : MonoBehaviour
{
public int score;
void Start()
{
score = 0;
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown (0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit,200))
{
if (GameObject.FindGameObjectWithTag ("target"))
{
score++;
}
else
{
score--;
}
}
}
}
The GameObject.FindGameObjectWithTag
method is going to look at your entire scene for an object with target
as the tag. Since you have one in the scene that will always return true, if you hit something.
You need to look at the properties on the RaycastHit and pull the tag from there.
if (hit.collider.tag == "target")
{
score++;
}
else
{
score--;
}