- Home /
Can I call sounds from other script?
I have too many class and script to add the same sounds ,so i wonder that can i create script that can be used in many class or script? and how?
I try this but it error something like Expression denotes a `type', where a `variable', `value' or `method group' was expected.
(plus, i am just a beginner who having a bad skill in programming and never write c# before. i sorry if i ask, do, or show something stupid)
using UnityEngine;
using System.Collections;
public class AudioTest : MonoBehaviour
{
public AudioClip soundClick;
void OnGUI(){
if (GUI.Button(new Rect(10, 10, 100, 50), "Test")){
Audio().playOnClick();
}
}
and in other script Audio
public void playOnClick(){
audio.clip = soundClick;
audio.Play();
}
if i put this playOnClick code to AudioTest it can play sound
maybe this "Audio().playOnClick();" is wrong, but i don't know how to fix it.
i try to fix it my self 3 day but it did't work. Please help me.
unityGE$$anonymous$$S.com for basic explanation of how to call other scripts, other components etc.
Answer by prototype7 · Nov 02, 2012 at 10:19 AM
You should GetComponent first
1) example AudioTest.cs attached to GameObject with named "object1"
2) example OtherScriptAudio.cs attached to GameObject named "object2"
AudioTest.cs
public class AudioTest : MonoBehaviour {
private GameObject getGO;
private OtherScriptAudio getComponentAudio;
// Use this for initialization
void Start () {
getGO = GameObject.Find("object2");
getComponentAudio = getGO.GetComponent<OtherScriptAudio>();
}
void OnGUI()
{
if (GUI.Button(new Rect(10, 10, 100, 50), "Test")){
getComponentAudio.playOnClick();
}
}
}
OtherScriptAudio.cs
public class OtherScriptAudio : MonoBehaviour {
public void playOnClick()
{
audio.clip = soundClick;
audio.Play();
}
}
This is it. Just one little detail, you do not need to keep the getGo variable. You might as well make it local to the start function or simply :
getComponentAudio = GameObject.Find("ObjectName").GetComponent<OtherScriptAudio>();
But yes that is the way.