Hi, I’m very new to Unity and C#. I started off with a script almost the same as the one below, except with a single Raycast instead of a SphereCast, and it worked great. Now, I’m trying to edit it to make a shotgun weapon that works by sending out a SphereCast and damages everything in the SphereCast’s path, but it’s not as simple as I thought. Nothing happens when I run this code in-game, which means Physics.SphereCast is never true, although previously Physics.Raycast worked just fine. The only things I changed were making Raycast into SphereCast and adding the spread variable. How do I get this to work?
public class ShootScript : MonoBehaviour
{
public float damage = 10f;
public float range = 100f;
public float fireRate = 15f;
public float spread = 10f;
private float nextTimeToFire = 0f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetButton("Fire1") && Time.time >= nextTimeToFire)
{
nextTimeToFire = Time.time + 1f / fireRate;
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.SphereCast(ray, spread, out hit, range))
{
Debug.Log("test");
if (hit.transform != null)
{
Target target = hit.transform.GetComponent<Target>();
Debug.Log(hit.transform.name + " has been struck");
target.TakeDamage(damage);
}
}
}
}
}