Pass a value between script or else by reference?

Hello guys. I’m making a sort of editor for my game and i need to change multiple values from a script inside a component. Each value will get modified by pressing something like “increase+/decrease-” buttons and with this said, it means that every pair button will have a different script each

Explained simply:

The script with the values: let’s suppose i have a MonoBehaviour script on a component like this:

public class A : MonoBehaviour
{
    public int a = 0;
    public int b = 0;
}

Where a and b are some of the many values that i have to change costantly

and on the pair of buttons I have a script that inherits from another script like:

public class C : MonoBehaviour
{
    int reference;

    void Start()
    {
        
        SetValue();
    }

    public virtual void SetValue()
    {
        //Note: this is a way to get it. I don't really need GetComponent itself
        //the basic thing, however, would be that with a script i get a reference
        //on a value, then with another script inherited from this i override this
        //method and set another reference to another value like 'b'
        reference = GameObject.Find("a").GetComponent<A>().a;
    }

    public void ChangeValue()
    {
        //see below
    }
}

Now let’s suppose from script C on ChangeValue() i want to run a command like:

++reference; //or --reference

and when I do so, I will modify the value ‘a’ on the script A and not the variable ‘reference’ on C.

How could I do so without pointers?

NOTE: I can’t, for my case, save the script instead and use A.a, of course, and any other kind of stuff like that (otherwise I would have to change on every script the code on ChangeValue() and it would be boring over than pointless and too long since there are maaaany values).
I can only get the “reference” on the Start() method for my kind of need. Otherwise i wouldn’t ask for how to do it.

Many thanks in advance and regards :smiley:

I think the ref keyword is what you’re looking for. This will only work for function calls.

You’re script C might have a function that looks like this:

void setValue(ref int someValue) {
     value = 123;
}

To call this function, use
setValue(ref A.a);

Though if you could do this, you could just set A.a directly.


If you have to make the fields references (i.e. the above won’t work), the easiest way would be using a wrapper class:

class PassingMyIntByReferenceUsingAWrapper {
    public int a;
}

Here is a generic version of the above:

class PassingMyTypeByReferenceUsingAWrapper<T> {
    public T value;
}