Search Unity

Resolved Start void on variable value changed.

Discussion in 'Scripting' started by Karma_XX, Mar 14, 2023.

  1. Karma_XX

    Karma_XX

    Joined:
    May 12, 2022
    Posts:
    10
    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.
    Screenshot (1569).png
    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.
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,925
    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:
    Code (CSharp):
    1. public class MainObject : Monobehaviour
    2. {
    3.     [SerializeField]
    4.     private string _name;
    5.    
    6.     public string Name
    7.     {
    8.         get => _name;
    9.         set
    10.         {
    11.             _name = value;
    12.             OnNameChanged?.Invoke(_name);
    13.         }
    14.     }
    15.    
    16.     public event Action<string> OnNameChanged;
    17. }
    18.  
    19. // usage
    20. mainObject.OnNameChanged += PrintNewName;
    21. mainObject.Name = "New Name";
    22.  
    23. private void PrintNewName(string name)
    24. {
    25.     Debug.Log("New name is: " + name);
    26. }
    Spend some time learning how to use delegates, as they are getting into strong intermediate territory.
     
    Karma_XX likes this.
  3. QuinnWinters

    QuinnWinters

    Joined:
    Dec 31, 2013
    Posts:
    494
    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.

    Code (CSharp):
    1. public OcTree ocTree;
    2. float ocTreeHeight;
    3.  
    4. void Start () {
    5.     ocTreeHeight = ocTree.height;
    6. }
    7.  
    8. void Update () {
    9.     if (ocTreeHeight != ocTree.height) {
    10.         ocTreeHeight = ocTree.height;
    11.         PrintHeight (ocTree.height);
    12.     }
    13. }
    14.  
    15. void PrintHeight (float height) {
    16.     print (height);
    17. }
     
    spiney199 and Karma_XX like this.
  4. Karma_XX

    Karma_XX

    Joined:
    May 12, 2022
    Posts:
    10
    Thank you both :D