informative
informative

Reputation: 53

Unity 5 constantly check for a collider in line of sight using raycasts

I am working on a unity 5 game. When I walk through a certain collider audio starts playing. I am trying to make a script so that while the audio is playing and my center of vision hits the collider perimeter the audio will stop playing or for that case, play a different sound. Here is my script:

using UnityEngine;
using System.Collections;

public class Raycast: MonoBehaviour {

 private RaycastHit hit;
 private float range = 300;

 // Use this for initialization
 void Start() {}

 // Update is called once per frame
 void Update() {
  checkforinput();
 }

 void checkforinput() {
  if (Input.GetButtonDown("Fire1")) {
   if (Physics.Raycast(transform.position, transform.forward, out hit, range)) {
    print(hit.transform.name);
    //source.Stop();
   }
  }
 }

}

So how would I constantly do this without clicking my fire1 button?

Upvotes: 0

Views: 605

Answers (1)

AminSojoudi
AminSojoudi

Reputation: 2016

Change this

if (Input.GetButtonDown("Fire1")) {
    if (Physics.Raycast(transform.position, transform.forward, out hit, range)) {
    print(hit.transform.name);
    //source.Stop();
    }
}

To this :

if (Physics.Raycast(transform.position, transform.forward, out hit, range)) {
    print(hit.transform.name);
    //source.Stop();
}

Note that

if (Input.GetButtonDown("Fire1"))

Is checking for mouse input . if it was true then whatever inside "if" block will run .

Upvotes: 1

Related Questions