How can I set a var to a function in another script ?
The function is called “function SwingSound()” and is in a script called MouseSoundController on a object called Camera.
The below works fine.
#var mouseSound = GameObject; // Set link to the Mouse Sound Controller, I've put it on the camera
mouseSound.GetComponent.< MouseSoundController >().SwingSound();
I’ve tried the below with no luck, I get the message (Cannot convert ‘void’ to ‘UnityEngine.GameObject’.)
#var mouseSound = GameObject; // Set link to the Mouse Sound Controller, I've put it on the camera
private var myVar : GameObject;
myVar = mouseSound.GetComponent.< MouseSoundController >().SwingSound();
I really don’t know what you are trying to do here. But if you want to call a function in another script, you could do like this:
MouseSoundController.js:
// this returns the AudiSource from the gameObject this script is attached
function SwingSound () : AudioSource {
return audio;
}
OtherScript.js
var mouseSound : GameObject; // The object that has the MouseSoundController attached
private var myAudio : AudioSource;
function Start() {
myAudio = mouseSound.GetComponent("MouseSoundController").SwingSound();
myAudio.Play();
}
EDIT: The solution of the problem:
If the function SwingSound in MouseSoundController is a void and don’t return a value, and it don’t take any parameters, then use this:
var mouseSound : GameObject;
function Start () {
var myVar: System.Action;
var swooshSoundEvent = new AnimationEvent();
myVar = mouseSound.GetComponent(MouseSoundController).SwingSound;
swooshSoundEvent.functionName = myVar.Method.Name;
Debug.Log(swooshSoundEvent.functionName);
}
and: this is an example if the function SwingSound in MouseSoundController takes a parameter int, and return a value of float:
var mouseSound : GameObject;
function Start () {
var myVar: System.Func.<int,float>; // where int is the type of variable put into the function, and float is the variable the function returns.
var swooshSoundEvent = new AnimationEvent();
myVar = mouseSound.GetComponent(MouseSoundController).SwingSound;
swooshSoundEvent.functionName = myVar.Method.Name;
Debug.Log(swooshSoundEvent.functionName);
}
The last script is the case where SwingSound looks similar to this:
function SwingSound (t:int) : float{
return 1.0223;
}
You can declare myVar: Function, like this (other script):
var myVar: Function; // myVar is a function reference
function Start(){
// get the function reference (no parenthesis!)
myVar = mouseSound.GetComponent(MouseSoundController).SwingSound;
}
// and use it like this:
myVar();
You can even pass parameters and receive the function result, if you want.
NOTE: This version of GetComponent is better than the generic and string ones.