- Home /
calling a function when any variable in an array changes
I am trying to call a function whenever any element of an array gets modified. Here is my approach
public class drawpoints : MonoBehaviour {
public Vector2[] values;
private Vector2[] mvalues;
public delegate void onvalueschangedelegate(Vector2[] newvalues);
public event onvalueschangedelegate onvalueschange;
void Start () {
values = GetComponentInParent<hero>().values; // the reference to the array
onvalueschange += valueschange; //the array will be modified by other gameobject which
//has the refercnce to this array
}
public Vector2 values
{
get { return mvalues; }
set{
if (values == mvalues)
return;
values = mvalues;
if (onvalueschange != null)
onvalueschange (values);
}
}
void valueschange(Vector2 newvalues) //the function I want to call
{
Debug.Log ("values has changed");
}
}
This method seems to work fine for float and int datatypes, but not for an array.
Yes, I may check for the change in the values of every variables in the array for every frame in the Update function, or even call the function on the gameobject that changes the value of the array. But these methods does not seem to work in the context of my project. Can somebody please suggest me a good method for calling a function when any element of an array changes? Thanks in advance.
Answer by hexagonius · Oct 30, 2018 at 07:43 AM
either override the indexer itself:
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/indexers/using-indexers
or instead of a setter property, create a method with index and value as parameter that youwhere you can do the check