- Home /
Help removing an AudioSource component from another script
I'm having trouble destroying an AudioSource component on my game object via script. The overall aim of my TestScript.cs script is that when the script is added to an object in the scene through the editor, it also adds an AudioSource component to it. Similarly, when the script is removed from an object, I want it to remove the AudioSource component. For this reason I have used the OnDestroy() hook and used DestroyImmediate(...) (for editor functionality). Unfortunately when I enter and leave play mode, I get the following error: Destroying object multiple times. Don't use DestroyImmediate on the same object in OnDisable or OnDestroy.
Here is the code I am reproducing the issue with:
[ExecuteInEditMode]
public class TestScript : MonoBehaviour
{
private SpriteRenderer spriteRenderer;
private AudioSource audioSource;
void OnEnable()
{
//spriteRenderer = gameObject.AddComponent<SpriteRenderer>();
audioSource = gameObject.AddComponent<AudioSource>();
}
void OnDestroy()
{
//DestroyImmediate(spriteRenderer);
DestroyImmediate(audioSource);
}
}
Note that I have tried the same with a SpriteRenderer component and am not encountering the same issues.
I am also aware that with this script, a new AudioSource component gets added every time OnEnable() gets called which can result in multiple AudioSource components. I'm not concerned about this as I am handling it correctly in my actual script. I have just reproduced the error in the fewest lines with the least noise.
Does anyone have any insight on why this may be happening and how I can fix it?
Your answer
Follow this Question
Related Questions
Weird audio problem 1 Answer
Zenject add component dynamically 2 Answers
Call compoent by name 2 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers