Question by
williamsze · Mar 15, 2016 at 04:13 PM ·
scripting problem
Beginner script problem
please tell me what is the problems in my script?
AudioSource audio;
float distance;
public Transform A;
public Transform B;
// Use this for initialization
void Start () {
audio = GetComponent<AudioSource>();
A = gameObject.CompareTag("Player");
B = gameObject.CompareTag ("ghost");
}
// Update is called once per frame
void Update () {
float distance = Vector3.Distance (A.position, B.position);
if (distance <= 5) {
audio.PlayOneShot (impact3, 0.7F);
}
else{
audio.Stop(impact3);
}
} }
Comment
Best Answer
Answer by Positive7 · Mar 15, 2016 at 05:50 PM
Solution 1 : Sound will play continuously while you're closer to the target then 5.0f
using UnityEngine;
public class asd2 : MonoBehaviour
{
AudioSource _audio; //renamed it to _audio
float distance;
public Transform A;
public Transform B;
public AudioClip impact3; //Assign this in Inspector or Initialize it in Start() / Awake()
void Start()
{
_audio = GetComponent<AudioSource>();
//A = gameObject.CompareTag("Player"); //CompareTag returns bool
//B = gameObject.CompareTag("ghost");
A = GameObject.FindGameObjectWithTag("Player").transform; //FindGameObjectWithTag returns GameObject
B = GameObject.FindGameObjectWithTag("ghost").transform;
}
void Update()
{
distance = Vector3.Distance(A.position, B.position); //removed float as it is declared above
if (distance <= 5.0f && !_audio.isPlaying)
{
_audio.PlayOneShot(impact3, 0.7f);
}
}
}
Solution 2 : Sound will Play once
using UnityEngine;
public class asd2 : MonoBehaviour
{
AudioSource _audio; //renamed it to _audio
float distance;
public Transform A;
public Transform B;
public AudioClip impact3; //Assign this in Inspector or Initialize it in Start() / Awake()
public bool audioPlayedOnce = false; //Check if Audio has been played
void Start()
{
_audio = GetComponent<AudioSource>();
//A = gameObject.CompareTag("Player"); //CompareTag returns bool
//B = gameObject.CompareTag("ghost");
A = GameObject.FindGameObjectWithTag("Player").transform; //FindGameObjectWithTag returns GameObject
B = GameObject.FindGameObjectWithTag("ghost").transform;
}
void Update()
{
distance = Vector3.Distance(A.position, B.position); //removed float as it is declared above
if (distance <= 5.0f && !_audio.isPlaying && !audioPlayedOnce)
{
_audio.PlayOneShot(impact3, 0.7f);
audioPlayedOnce = true;
}
else if(distance >= 5.0f)
{
audioPlayedOnce = false;
}
}
}
Note: Sent from tablet so above code is not tested. I hope I didn't make any mistake :D Let me know if it doesn't work...
Thank You~! Can you answer me ~ how to play the sound once when the distance <=5!? The condition for now , when the distance <=5 , the sound play more than one time,the sound mix together and that not my expectation. $$anonymous$$y expectation is that when distance <=5, the sound play each time separately!~ Please tell me ^3^!!
I'll check it once I got home and update the answer above