- Home /
Sound effect make 2D game lagged
Hi everyone, I'm making 2D game using Unity 4.3. I developed the collecting coins function. The game works fine until I applied sound effect to game. The game lagged each time player collected a coin (with sound). Then, I remove sound, and the game run smoothly.
I have research around but I can't figure out the reason for this issue. My question is How to make my game run smoothly when I applied sound effect to collecting coins function.
Following is more information about my game:
Target build test: iPad2
Sound file format: mp3 (14K)
Snippet of code when player get a coin:
public class CollisionPlayer : MonoBehaviour {
void OnCollisionEnter2D(Collision2D collision)
{
//when player get coin 1$
if (collision.collider.tag == Constants.STATIC_COIN_TAG) {
GameManger.playerBudget ++;
GameManger.updatePlayerBudget();
ParticleSystem cloneObj = (ParticleSystem)Instantiate(bonusEffect,transform.position,transform.rotation);
ParticleSystem cloneObj1 = (ParticleSystem)Instantiate(staticCoinEffect,collision.collider.transform.position,collision.collider.transform.rotation);
**SoundEffectsHelper.Instance.PlayCollectCoinSound();**
Destroy (collision.gameObject);
Destroy (cloneObj.gameObject, 0.5f);
Destroy (cloneObj1.gameObject, 0.5f);
}
}
} }
SoundEffectsHelper class:
public class SoundEffectsHelper : MonoBehaviour {
// Singleton
public static SoundEffectsHelper Instance;
public AudioClip getBonusSound;
public AudioClip jumpSound;
public AudioClip hitSound;
public AudioClip screamingSound;
public AudioClip congratulationSound;
public AudioClip collectCoinSound;
public AudioClip specialJumpSound;
public AudioClip rocketSound;
public AudioClip explosionSound;
public AudioClip gunshotSound;
private float volume = 1f;
void Awake()
{
// Register the singleton
if (Instance == null)
{
Instance = this;
}
}
public void PlayCollectCoinSound(){
volume = 1f;
MakeSound(collectCoinSound);
}
private void MakeSound(AudioClip originalClip)
{
// As it is not 3D audio clip, position doesn't matter.
AudioSource.PlayClipAtPoint(originalClip, transform.position, volume);
}
}
Hello
$$anonymous$$h...I never got lag playing clips like this . you have no errors?
anyway can you try this ins$$anonymous$$d:
AudioSource.PlayClipAtPoint(originalClip,Vector3.zero,volume);
line 39
Answer by timvanderweijde · Jul 02, 2014 at 01:52 PM
I don't know your complete code/objects in your game, but I see you are using a singleton pattern for the SoundEffectHelper.
This can create problems in a multithreaded environment if you don't do some locking.
Try this (not compiled/tested code)
var obj = new object();
if (Instance == null)
{
lock (obj)
{
if (Instance == null)
{
Instance = this;
}
}
}
This is called Double Checked Locking;