- Home /
Raycast hits and affects all items within the same tag
So I am using raycast to detect player interactions in the world, and I am using tags to separate the different types of objects you can interact with. This seemingly works fine in separating the different types of objects, but my issue is that is I have more than one object in the same tag the raycast affects all of the items in that tag instead of the single object that I want it to.
Here is the code:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class HungerAdd : MonoBehaviour {
public GameObject self;
public GameObject EatMeGUI;
public GameObject Audio1;
public Slider slider;
public GameObject GunCheckIntObj2;
public GameObject gameOverMan;
void FixedUpdate()
{
if (gameOverMan.activeSelf == false) {
Ray mouseRay = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit rayHit = new RaycastHit ();
if (Physics.Raycast (mouseRay, out rayHit, 2) && (rayHit.collider.gameObject.tag == "Food") && (GunCheckIntObj2.activeSelf == false)) {
EatMeGUI.gameObject.SetActive (true);
} else {
EatMeGUI.gameObject.SetActive (false);
}
if (Input.GetButtonDown ("Fire1") && (Physics.Raycast (mouseRay, out rayHit, 2)) && (rayHit.collider.gameObject.tag == "Food") && (GunCheckIntObj2.activeSelf == false)) {
EatMeGUI.gameObject.SetActive (false);
slider.value += 10;
self.gameObject.SetActive (false);
Audio1.gameObject.GetComponent<AudioSource> ().Play ();
}
}
}
}
The only thing I can think is that the "new RaycastHit" only creates one call per script so is multiple items use the same script it affects all of those items. Am I missing something here, and how would I fix it?
Answer by JigneshKoradiya · Jun 30, 2016 at 06:48 AM
if (Physics.Raycast (mouseRay, out rayHit, 2) && (rayHit.collider.gameObject.tag == "Food") && (GunCheckIntObj2.activeSelf == false))
{
EatMeGUI.gameObject.SetActive (true);
}
else
{
EatMeGUI.gameObject.SetActive (false);
}
in this if condition add rayHit.collider.gameObject.name=="yourplayrname" in OR condition so it will only work if your game object has same name
Answer by giorashc · Jun 30, 2016 at 07:33 AM
Yes, if your script runs on more then one object then you will have several ray casts in the scene per fixed update. Since you are using the referenced objects (instead of the object that was actually hit by the ray) you see all "Food" items affected.
To solve your two problems:
Use only one game object (an empty) which runs a script with ray collision detection for these "food" objects.
When you detect a hit use the
rayHit.collider.gameObject
to perform the logic you need on that specific object.