dictionary of functions?
In c# this works:
Dictionary<int, System.Action> functions = new Dictionary<int, System.Action>();
I'm using System.Action because my functions return nothing and take no parameters
void Function1()
{
Debug.Log("This is Function1.");
}
//add a function to the dictionary with key 1
functions.Add(1, Function1);
//call it
functions[1]();
// console output:
//"This is Function1."
However, in a unity c# script I'm getting an invalidkey error. What am I doing wrong?
EDIT: I figured out what was wrong with my code. I'm using a getter and setter, and in the set block I wasn't setting the variable to the keyword "value"
private int _funcNum
public int functionNumber
{
get
{
return _funcNum;
}
set
{
_funcNum = functionNumber; //This should be: _funcNum = value;
DoFunction(_funcNum);
}
}
there's not enough info here to help you - try showing the code of adding the key too...
If all else fails, you can always store the function name as a string and use Invoke to call it.
Answer by gjf · Nov 09, 2015 at 09:29 PM
really not sure why it's not working for you - i tried the following and got the expected results (including the error for the entry which didn't exist)
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ActionTest : MonoBehaviour
{
Dictionary<int, System.Action> functions = new Dictionary<int, System.Action>();
void Start()
{
functions.Add(64, Function0);
functions.Add(57, Function1);
functions[57]();
functions[64]();
functions[3]();
}
private void Function0()
{
Debug.Log("Function 0");
}
private void Function1()
{
Debug.Log("Function 1");
}
}
in future, please also include the complete error message.
Thank you gjf, you getting yours to work helped me figure out it had to be in my get/set function because I didn't include that before.
I'll remember to post the error next time as well.