- Home /
Question by
fiixed · Mar 03, 2017 at 06:23 PM ·
c#raycastsendmessage
Performance issues with SendMessage in FixedUpdate using Raycast
Hi,
in my app I'm trying to get a slide to play and pause audio based on whether or not the camera is looking at the slide. I'm running into performance issues (its on Android/Google Cardboard), and the audio sound broken and sluggish. I'm guessing using SendMessage within FixedUpdate is causing the issue and there must be a better way to architect this.
Firstly, this is the Raycast script attached to the Main Camera:
public class VideoControl : MonoBehaviour {
bool rayHit = false;
GameObject tempGameObject;
int layer_mask1;
private void Start() {
layer_mask1 = LayerMask.GetMask("Player");
}
void FixedUpdate() {
Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 1, layer_mask1) && rayHit == false) {
tempGameObject = hit.transform.gameObject;
tempGameObject.SendMessage("HitByRay");
rayHit = true;
} else {
if (rayHit) {
tempGameObject.SendMessage("Pause");
rayHit = false;
} else {
return;
}
}
}
}
Then it sends a message to the "slide" object which has a GVRAudioSource attached:
public class AudioPlayer : MonoBehaviour {
bool isPlaying = false;
private GvrAudioSource audioSource;
void Start () {
audioSource = GetComponent<GvrAudioSource>();
}
void HitByRay() {
if (isPlaying == false) {
audioSource.Play();
isPlaying = true;
}
}
public void Pause() {
if (isPlaying) {
audioSource.Pause();
isPlaying = false;
}
}
}
I know SendMessage is expensive, but I've tried calling the method directly using GetComponent and its still just as sluggish. I'm guessing I've just coded this badly. Any suggestions would be greatly appreciated.
Comment