Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Playing sound while watching to an object

Discussion in 'Scripting' started by OptimistPruim, Dec 17, 2015.

  1. OptimistPruim

    OptimistPruim

    Joined:
    Dec 17, 2015
    Posts:
    1
    Hello,

    Our project is an Google Cardboard application. We created an sphere and put a photo on it.
    The camera is inside the sphere and has two lenses for each eye.

    I want to create a C# script to make an object make a sound when you look at it, via the camera.

    This is our code now:

    usingUnityEngine;
    usingSystem.Collections;

    publicclassbanaan : MonoBehaviour {

    publicAudioClip[] audioClip;

    voidStart ()
    {
    //hoifritsdoedingenhierdie@startmoetengebeuren
    AudioSourceaudio = GetComponent<AudioSource>();
    }

    voidUpdate ()
    {
    //hoifritsdoedingenhierdieelkeframemoetengebeuren
    }

    voidOnMouseDown()
    {
    //hoifritsditiswhatsgonnahappenalsjekliktopdecube
    Debug.Log ("sicke ouwe je hebt geklikt mad respect", gameObject);
    PlaySound(0);
    }

    voidPlaySound(intclip)
    {
    //hoifritshierspeelthijdesoundaf
    Debug.Log ("komtie", gameObject);
    GetComponent<AudioSource>().clip = audioClip[clip];
    GetComponent<AudioSource>().Play ();
    }




    }

    Hopefully you can help me,

    OptimistPruim
     
  2. CloudKid

    CloudKid

    Joined:
    Dec 13, 2015
    Posts:
    207
    Firstly, please use code tags so we can read your code http://prntscr.com/9f7yjl
    Secondly, I think you want to research Raycast and find the variation that suits you

    Official tutorial:
     
    OptimistPruim likes this.
  3. troyfury

    troyfury

    Joined:
    May 15, 2015
    Posts:
    19
    You can use raycasts or you can check if the object is within the fustrum planes of the camera, depends on which is more suitable for your project. To use the fustrum method try something like this, keep in mind you need to tag one of the cameras as MainCamera, and this script is attached to the picture frame:

    private bool visible;

    void Update(){
    if (GeometryUtility.TestPlanesAABB(GeometryUtility.CalculateFrustumPlanes(Camera.main), gameObject.GetComponent<Collider>().bounds))
    {
    visible=true;
    }
    else
    {
    visible=false;
    }

    if (visible) {
    GetComponent<AudioSource>().clip.Play();
    }

    else{
    GetComponent<AudioSource>().clip.Stop();
    }
    }
     
    OptimistPruim and CloudKid like this.