My game has lots of triggers which will do something different when the player touches them. Right now each trigger object has its own script which will call a function in another script.
But this seems inefficient to me. I wondered if there was a solution where I could add the same script component to all these triggers, and choose a function to call in another script through the inspector. Like you can when choosing an onclick event for a button (you can select a script and a function).
I think this would be efficient, but I’m not sure how to reference another script and function through the inspector. Anyone else think this is a good idea? Anyone do it already? How would it be done?
Not really sure if this is what you’re after, but something like this?->
Some class :
using UnityEngine;
/**this script/class just sits in the standard assets folder somewhere and doesn't
attach to any objects in the scene**/
[System.Serializable]
public class SomeClass
{
//an enum for each method/function you make
public enum MethodSelect
{
DoThis, DoThat, DoSomethingElse
}
//set in inspector which method to use
public MethodSelect method ;
//main method that is called from wherever...
public void DoStuff()
{
//switch to a different case for each method you make
switch(method)
{
case MethodSelect.DoThis :
DoThis() ;
break ;
case MethodSelect.DoThat :
DoThat() ;
break ;
case MethodSelect.DoSomethingElse :
DoSomethingElse() ;
break ;
}
}
//the methods for each of your enum values-->
void DoThis()
{
Debug.Log("Did This") ;
}
void DoThat()
{
Debug.Log("Did That") ;
}
void DoSomethingElse()
{
Debug.Log("Did Something Else") ;
}
}
Some other class with a SomeClass variable :
using UnityEngine;
using System.Collections;
/**the script to attach to game objects in the scene**/
public class UseSomeClass : MonoBehaviour
{
//set [method] of this in the inspector
public SomeClass someClass ;
void OnTriggerEnter()
{
//call the main method DoStuff() on someClass
someClass.DoStuff() ;
}
}