Hello,
I would like to be able to start a void everytime the value of a variable under a certain script changes, and if possible, even send which variable changed to the void.
Like in this photo. When the height changes, a script should detect this change and start a void by sending which variable value changed.
Thank you.
First thing to note that ‘void’ is the return type of a method/function that returns nothing. Call them methods in the context of C#.
What you’re asking for is called a ‘callback’, which is best accomplished in C# with something called a delegate.
Though it’s easiest to use the pre-supplied delegates such as System.Action
.
Basic example:
public class MainObject : Monobehaviour
{
[SerializeField]
private string _name;
public string Name
{
get => _name;
set
{
_name = value;
OnNameChanged?.Invoke(_name);
}
}
public event Action<string> OnNameChanged;
}
// usage
mainObject.OnNameChanged += PrintNewName;
mainObject.Name = "New Name";
private void PrintNewName(string name)
{
Debug.Log("New name is: " + name);
}
Spend some time learning how to use delegates, as they are getting into strong intermediate territory.
1 Like
Though spiney’s suggestion is the better route, another option is the following. As the saying goes, there are many ways to skin a cat.
public OcTree ocTree;
float ocTreeHeight;
void Start () {
ocTreeHeight = ocTree.height;
}
void Update () {
if (ocTreeHeight != ocTree.height) {
ocTreeHeight = ocTree.height;
PrintHeight (ocTree.height);
}
}
void PrintHeight (float height) {
print (height);
}
2 Likes