I have a script that sends out a raycast from the player to test if it hits a specific object (a battery). I have a mesh collider on the battery and a tag called “battery” assinged to it. Here is the script that I have on the player, however it doesn’t work:
using UnityEngine;
using System.Collections;
public class ObjectInteract : MonoBehaviour {
public RaycastHit hit;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Ray ray = Camera.main.ScreenPointToRay (new Vector3(Screen.width/2,Screen.height/2,0));
if (Physics.Raycast (ray, out hit, 2)){
if (hit.collider.tag == "Battery"){
Debug.Log ("Hit Battery");
}
}
}
}
Any ideas?
You need to check your case. One is “battery” with a lowercase b and you are checking for an uppercase b “Batter”.
If this happens often you may want to do something like:
if (hit.collider.tag.ToLower() == "battery")
try changing the ray length and testing it that way cause two is a short value try setting it to 10 then adjusting the length of the ray later depending on how far out the item is that you want to interact with, 2 may be too short for the main camera to actually cast a ray out and hit it
try the below code
using UnityEngine;
using System.Collections;
public class ObjectInteract : MonoBehaviour {
public RaycastHit hit;
public float RayLength = 10;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Ray ray = Camera.main.ScreenPointToRay (new Vector3(Screen.width/2,Screen.height/2,0));
if (Physics.Raycast (ray, out hit, RayLength)){
if (hit.collider.tag == "Battery"){
Debug.Log ("Hit Battery");
}
}
}
}