0

In my project I have a very simple assignment.

Vector3 v1 = new Vector3(0,0,0);
Vector3 v2 = v1;
v2.x = 10;
Debug.Log(v1);

The above code prints "0,0,0". If this was Java it would print "10,0,0" because v2 would reference v1. How do I get this in C#?

I want v1 and v2 to point to the same object. This is also part of a unity project but I don't think that's relevant here?

1

2 Answers 2

2

In Unity3d, Vector3 is not a reference type (class). It's a value type (struct). Which means it behaves in this sense more like a primitive would in Java.

When you assign, you're copying, not referencing the same object.

What you can do is call a method using the ref keyword, and allow that to modify an existing Vector3:

private static void Vector3Test()
{
    Vector3 v1 = new Vector3(0, 0, 0);

    ChangeVector(ref v1);

    Debug.Log(v1);
}

private static void ChangeVector(ref Vector3 vector)
{
    vector.x = 10;
}

This will output "10,0,0" as expected.

Sign up to request clarification or add additional context in comments.

Comments

1

This is because Vector3 is Structure type not Class type. It's a value type, not a reference type, like Class. So when you assign it, it will copy a new value, but their address in memory is not same.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.