Audio doesn't want to play
I have been having so much trouble with this. After 5 hours of trying all kinds of things this idiotic thing still doesn't want to work. Then suddenly it worked and now it doesn't again -__-
This script is attached to the AudioSource. The times it get's through is 3.
this is the error I'm getting:
NullReferenceException: Object reference not set to an instance of an object
SoundManager.PlaySound (Int32 i, Int32 x) (at Assets/Scripts/PlayerScripts/SoundManager.cs:29)
UIController.NButton () (at Assets/Scripts/PlayerScripts/UIController.cs:82)
UIController.Start () (at Assets/Scripts/PlayerScripts/UIController.cs:35)
And this is the script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SoundManager : MonoBehaviour
{
public AudioSource audioSource;
public AudioClip AlarmClock;
public static SoundManager instance = null;
int times;
void Awake()
{
if (instance == null)
instance = this;
else if (instance != this)
Destroy(gameObject);
DontDestroyOnLoad(gameObject);
}
public void PlaySound(int i, int x)
{
switch (i)
{
case 1:
// SFX Alarm clock
audioSource.clip = AlarmClock;
times = x; // Is 3
while (times >= 0)
{
if (!audioSource.isPlaying)
{
audioSource.Play();
times--;
}
}
break;
}
}
}
I hope someone can help me to find the mistake. But at this point I am starting to think it's a bug :/
Even when adding the audio file directly to the clip area, it just doesn't want to play :/
When I use the function in the script itself, then everything is fine, but the moment that I have to call it from another script, it stop's working
Answer by vinilly · Apr 25, 2018 at 04:31 PM
I think you can have a work around. I am not sure if alarm clock is the scenes music?
or a sound SFX from a clock. But I would just instantiate a prefab that auto destroys itself after a few with a clip
Example:
public AudioClip clip;
// Use this for initialization
void Start ()
{
AudioSource.PlayClipAtPoint(clip, transform.position);
Destroy(this.gameObject, 2.0f);
}
This would come instantiated as a GameObject from prefab with a music clip. Can be called from any script.
Your answer
![](https://koobas.hobune.stream/wayback/20220612161506im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Help with Fixed Joint , where the joint has a weird behavior. 0 Answers
Rigidbody / Animator Moving Y Position - bug? 1 Answer
Particle System not showing anything in its Component separated editor? 0 Answers
AvatarBuilder.BuildHumanAvatar set NaN positions with some avatars 1 Answer
3D Jumping Collision Bug 1 Answer