The RequireComponent attribute automatically adds required components as dependencies.
When you add a script which uses RequireComponent to a GameObject, the
required component will automatically be added to the GameObject. This
is useful to avoid setup errors. For example a script might require
that a AudioSource is always added to the same GameObject. Using
RequireComponent this will be done automatically, thus you can never
get the setup wrong. Note that RequireComponent only checks for
missing dependencies during the moment the component is added to a
GameObject. Existing instances of the component whose GameObject lacks
the new dependencies will not have those dependencies automatically
added.
using UnityEngine;
using System.Collections;
[RequireComponent (typeof (AudioSource))]
public class ImpactSound : MonoBehaviour
{
public AudioClip impact;
AudioSource source;
// Use this for initialization
void Start()
{
source = GetComponent<AudioSource>();
source.clip = impact;
}
// when collide with other with tag enemy play sound
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == "Enemy")
{
source.PlayOneShot(impact);
}
}
}
other way for prevent missing error that checking object have AudioSource component.in this example I use Property for checking it.
using UnityEngine;
using System.Collections;
public class ImpactSound : MonoBehaviour
{
public AudioClip impact;
AudioSource source
{
get
{
if (GetComponent<AudioSource>() == null)
{
gameObject.AddComponent<AudioSource>();
return GetComponent<AudioSource>();
}else
{
return GetComponent<AudioSource>();
}
}
set
{
source.clip = impact;
}
}
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == "Enemy")
{
source.PlayOneShot(impact);
}
}
}
if you don't like have error you can use AudioSource.PlayClipAtPoint , in this way your object Instantiate empty gameObject with AudioSource component in position that is easy way for play sound.
using UnityEngine;
using System.Collections;
public class ImpactSound : MonoBehaviour
{
public AudioClip impact;
// when collide with something play sound
void OnCollisionEnter2D()
{
Debug.Log("Sound was supposed to play on collision!");
AudioSource.PlayClipAtPoint(impact, transform.position);
}
}