Search Unity

Resources.Load Path

Discussion in 'Scripting' started by arahmitz, Jun 25, 2019.

  1. arahmitz

    arahmitz

    Joined:
    Jun 25, 2019
    Posts:
    25
    Hey guys!
    I've been struggling with the Resources.Load method. Why? I wanted to pass a different sound depending on my GameObjects name load a different sound file.


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class LoadAudioClip : MonoBehaviour{
    7.    
    8.     AudioSource audioSource;
    9.  
    10.     void Start(){
    11.  
    12.         audioSource = GetComponent<AudioSource>();
    13.         audioSource.clip = Resources.Load<AudioClip>("Sounds/ObjectOne");
    14.     }
    15.  
    16. }
    17.  
    For now it just gets the file "ObjectOne" for every object. But lets say I have 3 GO:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class LoadAudioClip : MonoBehaviour{
    7.  
    8.     private GameObject ObjectOne;
    9.     private GameObject ObjectTwo;
    10.     private GameObject ObjectThree;
    11.  
    12.     string nameOne, nameTwo, nameThree;
    13.    
    14.     AudioSource audioSource;
    15.  
    16.     void Start(){
    17.         nameOne = ObjectOne.name;
    18.         nameTwo = ObjectTwo.name;
    19.         nameThree = ObjectThree.name;
    20.         audioSource = GetComponent<AudioSource>();
    21.         audioSource.clip = Resources.Load<AudioClip>("Sounds/[stringname]");
    22.     }
    23.  
    24. }
    25.  
    How could I pass the string into Resources.Load path?
     
  2. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,748
    $"Sounds/{gameObject.name}"
     
  3. arahmitz

    arahmitz

    Joined:
    Jun 25, 2019
    Posts:
    25
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class LoadAudioClip : MonoBehaviour{
    7.  
    8.     string pathName;
    9.     AudioSource audioSource;
    10.  
    11.     void Start(){
    12.         pathName = gameObject.name;
    13.         audioSource = GetComponent<AudioSource>();
    14.         audioSource.clip = Resources.Load<AudioClip>("Sounds/Heart Sounds/${pathName}");
    15.     }
    16.  
    17. }
    18.  

    As I tried this way - it doesnt add the MP3 file into the Object's AudioSource with the same name.


    EDIT:
    Ofc I can't read, I put the $ in the wrong place, it should go like
    Code (CSharp):
    1. audioSource.clip = Resources.Load<AudioClip>($"Sounds/Heart Sounds/{pathName}");

    It works now, ty.
     
    Last edited: Jun 25, 2019