Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Playing Sounds from a different Game Object

Discussion in 'Scripting' started by Mails_PR, Jan 5, 2019.

  1. Mails_PR

    Mails_PR

    Joined:
    Jul 30, 2018
    Posts:
    9
    I am currently trying to access and play a sound from one game object by using a script attached to a different game object. In my attempts I have been trying to read up stuff here: https://answers.unity.com/questions/1119537/help-how-do-i-referenceaccess-another-script-in-un.html and wrote the following script:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class GameController : MonoBehaviour {  
    6.     public GameObject DisplayText;
    7.  
    8.     void Start ()
    9.         {
    10.           DisplayText.GetComponent<PlaySound>().PlayVictorySound;
    11.         }
    12.     public void StageClear ()
    13.     {
    14.         gameOverText.text = "Congratulations, you won!";
    15.         gameOver = false;
    16.         DisplayText.PlaySound.PlayVictorySound();
    17.     }
    18. }
    19.  
    I have also added the actual Display Text game object to the field crated by the first script. The other script attached to the DisplayText came object reads as follows:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlaySound : MonoBehaviour {
    6.  
    7.     private AudioSource audioSource;
    8.  
    9.     void Start () {
    10.         audioSource = GetComponent<AudioSource>();  
    11.     }
    12.  
    13.     public void PlayVictorySound ()
    14.     {
    15.         audioSource.Play();
    16.     }
    17. }
    18.  
    According to Unity, I am probably missing an assembly reference. What should I correct in the code?
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    Code (csharp):
    1. DisplayText.GetComponent<PlaySound>().PlayVictorySound;
    should be
    Code (csharp):
    1. DisplayText.GetComponent<PlaySound>();
    in Start(). You should have received the exact line number of the error, so make sure you practice your debugging abilities. You're going to need them a lot as a game developer.
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,514
    Amen! Some days I write nothing but bugs in fact.

    Then I spend the next week debugging! Yaaay!
     
    GroZZleR likes this.