- Home /
Question by
Proxtx · Apr 14, 2020 at 02:46 PM ·
c#eventeventsystemargumentexception
passing function to class
public class option
{
public UnityEvent onclick = new UnityEvent();
public string name;
}
With this code I'm able to pass a funtion to the class but only functions from the same class:
public class objScript : MonoBehaviour
{
public List<option> defaultOptions = new List<option>();
void yey()
{
Debug.Log("YAY");
}
void Start()
{
opti = new option();
opti.name = "Delete";
opti.onclick.AddListener(yey);
defaultOptions.Add(opti);
}}
This won't work:
public class objScript : MonoBehaviour
{
public List<option> defaultOptions = new List<option>();
void Start()
{
options opt = GetComponent<options>();
option opti;
opti = new option();
opti.name = "Delete";
opti.onclick.AddListener(opt.delete); //options.delete is defined
defaultOptions.Add(opti);
}}
ERORR: ArgumentException: Value does not fall within the expected range.
Comment
Answer by Jasr_88 · Apr 14, 2020 at 05:47 PM
To access a method from another class you need to specify that the method is for Public Access
public class Option
{
public UnityEvent onclick = new UnityEvent();
public string name;
public void Delete(){
// Some sentences to delete....
}
}
Now this code will work
public class ObjScript : MonoBehaviour
{
public List<Option> defaultOptions = new List<Option>();
void Start()
{
options opt = GetComponent<Options>();
option opti;
opti = new Option();
opti.name = "Delete";
opti.onclick.AddListener(opt.Delete); //options.delete is defined an NOW have public access
defaultOptions.Add(opti);
}
}
For more information about access modifiers you might what to read the official documentation https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers