Changing a property's value doesn't change the var reference value?

Hi gurus!

So, I’m still pretty new to Unity and C# and I’m cloning these rooms in my game, the idea is that they’ll have unique identifiers and other values. Then I can save them to my “database”.

Now the thing is, I thought that by changing a property value in C#, the references to that property would change too, right? Because they’re just reference types, they should be pointing at the property value is that correct?

The code below works but I thought debug logging slotID again after changing the property would print 42 but it doesn’t, it keeps the original value. I’m sure it’s something basic that I am missing.

        var slotID = clone.GetComponent<RoomManager>().roomObjectId;
        Debug.Log("Room ID is: " + slotID);
        // YASS!!!

        clone.GetComponent<RoomManager>().roomObjectId = 42;
        var newSlotID = clone.GetComponent<RoomManager>().roomObjectId;
        Debug.Log("Room ID is: " + slotID);
        Debug.Log("Room ID is: " + newSlotID);

TLDR; Basically changing a property’s value doesn’t seem to reflect in the original reference to that property… Is it something to do with var?

Now the thing is, I thought that by changing a property value in C#, the references to that property would change too, right? Because they’re just reference types, they should be pointing at the property value is that correct?

That’s where you are wrong. roomObjectId is most likely an integer, which is a value type. Changing it won’t change the original value contained in the RoomManager instance. And changing the value contained in the RoomManager instance won’t change the value of the integer variable.

var slotID = clone.GetComponent<RoomManager>().roomObjectId;

The previous line creates a new integer and store the value of roomObjectId into it.

Supposing roomObjectId would have been an object (instance of a class), the same would have applied because when calling var slotID = clone.GetComponent<RoomManager>().roomObjectId;, you would have created a reference to the roomObjectId instance (we could see it as a memory address). No, let’s suppose you are calling clone.GetComponent<RoomManager>().roomObjectId = newRoomObjectID, you would have changed the memory address contained in the RoomManager instance, leaving slotID as is.