Home > Back-end >  Audio not playing when triggered from script in Unity
Audio not playing when triggered from script in Unity

Time:10-27

I made a script that is supposed to manage audio files, so multiple can play at once.

Here is the script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MultipleSoundManager : MonoBehaviour
{
    #region AudioSource Variables
    public AudioSource AS1;
    public AudioSource AS2;
    public AudioSource AS3;
    public AudioSource AS4;
    public AudioSource AS5;
    #endregion
    
    
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public void AudioSourceManager(AudioClip clippy)
    { 
        for (int i = 1; i > 1; i  )
        {
            AudioSource[] audioManagerArray = {AS1, AS2, AS3, AS4, AS5};

            audioManagerArray[i].clip = clippy;
            audioManagerArray[i].Play();
      
            if(i == 5)
            {
                i = 1;
            }

        }

    }
}

And the AudioSourceManager function is called from other scripts like so:

public MultipleSoundManager soundManagerScript;

soundManagerScript.AudioSourceManager(AKMShot);

When this function is called, nothing happens whatsoever. I am a bit of a noob to Unity, and I really don't know what the issue is.

CodePudding user response:

I think your problem is

for (int i = 1; i > 1; i  )

How many times do you think this cycle will run?

CodePudding user response:

If you provide more information, it will help a lot. Here is some suggestion: 1.Try to find out if the [AKMShot] is null, may be is this cause the problume. 2.Try to find out if the [AS1/2/3/4/5] is null, may be is this cause the problume. 2.you can use "foreach" to replace the "for" in your [AudioSourceManager], try to google "C# foreach" and learn, but it cant solve this question, it just can make your code look pretty. 3.The "start" and update part is useless. You can just delete them.(also just to make your code pretty)

CodePudding user response:

The code will never run into the for-loop:

for (int i = 1; i > 1; i  )
{
      //...
}
  • Related