When the game is first ran the raycast will pick up the collider however it will just stop at random ive tried 2 differnt ways of doing it and nothing has fixed it any help would be nice.
Physics.Raycast stops as soon as it hits a single collider. If you want the ray to not stop and return more than a single hit, use Physics.RaycastAll instead. Then iterate through the collection it returns and check for what you need there.
Here’s a sample based on what you provided:
using System.Linq;
using UnityEngine;
public class TestScript : MonoBehaviour
{
private void FixedUpdate()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit[] hits = Physics.RaycastAll(ray, Mathf.Infinity);
if (hits.Any(x => x.collider.tag == "Unit"))
{
Debug.Log("Bang");
}
}
}
Also an extra note regarding the Physics.Raycast. It returns a boolean. If you want to access the object the raycast found. Use the hit variable (example: hit.collider.gameObject).
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class test : MonoBehaviour
{
public List Highlit;
public List Selected;
private Transform Sunit;
private GameObject Curtuse;
public Material highlit;
public Material selc;
public Material unSelec;
private bool high;
private RaycastHit hit;
// Start is called before the first frame update
void Start()
{
high = false;
Highlit = new List<GameObject>();
Selected = new List<GameObject>();
}
// Update is called once per frame#
void FixedUpdate(){
Ray r = Camera.main.ScreenPointToRay(Input.mousePosition);
//RaycastHit hit;
LayerMask m = ~8;
if (Physics.Raycast(r ,out hit, Mathf.Infinity) == GameObject.FindGameObjectWithTag("unit")){
Debug.Log("Bang");
}
}
void Update()
{
if(hit.collider.tag =="unit"){
Curtuse = hit.collider.gameObject;
if(Highlit.Contains(Curtuse)){
Curtuse.GetComponent<MeshRenderer> ().material = highlit;
}
if (Highlit.Contains(Curtuse) == false){
Highlit.Add(Curtuse);
}
}
else
{
foreach(GameObject obj in Highlit){
Curtuse.GetComponent<MeshRenderer> ().material = unSelec;
Debug.Log("hit floor");
}
Highlit.Clear();
}
}
}