2

I have a strange problem in unity3d. I want to use several audio sources for playing a sound with a overlapping effect. Because I can't explain the problem myself- I tried the same with only one AudioSource. So I have this script:

 public class audioOverlap:MonoBehaviour
 {
    private AudioSource sct;
    public AudioClip clp;
    void Start(){
       sct=new AudioSource(); 
       sct.clip=clp;//NullReferenceException!?
    } 
 }

Because of the NullReferenceException- I tried figuring out why.

    void Start(){
       sct=new AudioSource(); 
       if(sct==null){Debug.Log("AudioSourceBug");/*gets executed-wtf???*/}
       if(clp==null){Debug.Log("AudioClipBug");/*gets notexecuted-okay*/}
       sct.clip=clp;//NullReferenceException!?
    } 

I know what a NullReferenceException is-please don't mark it as duplicate when the linked question isn't a working solution:

I'm a beginner with Unity, but not with C#.

Community
  • 1
  • 1
leAthlon
  • 734
  • 1
  • 10
  • 22

2 Answers2

3

This is perfectly natural C#, but it won't fly:

sct=new AudioSource();

Unity has a component-driven, factory-based architecture. Instead of calling a component constructor, Unity wants you to call AddComponent to attach the component to a specific GameObject:

sct = gameObject.AddComponent<AudioSource>();

There are a few reasons for that. First off, Unity needs every Component to be owned by a GameObject. Second, many of Unity's built-in classes are actually shells representing resources that are created and managed by the engine's underlying native code layer.

rutter
  • 11,242
  • 1
  • 30
  • 46
  • I really wasn't far of going postal because I didn't understood this problem... They really should have made the class `sealed` (or is there a reason not to?). Thank you very much. – leAthlon Jun 08 '15 at 20:22
  • 2
    @leAthlon I've also wondered why they have public constructors if we're not supposed to use them. So far, I don't know, but I hope there's a reason. – rutter Jun 08 '15 at 21:23
0

have you tried adding the audioSource to another object (like a child object)? maybe the problem is having to audio sources on one object.

Babak Gohardani
  • 155
  • 1
  • 5
  • 17