Hi, I’m new to Unity and scripting and this forum, so try not to bite my face off.
The thread title might be a bit misleading. I think I more or less know what = does, but I’ve ran across seemingly inconsistent behaviour, so even though I (think I) know how to fix my problem, I thought I should ask here to figure out what happened.
Background: I just started scripting, so the first thing I tried to do was make the camera revolve around a target (which will at some point be the player) by moving the mouse. I did that by making a new class that handles spherical coordinates around a custom axis. It can convert these to Vector3, or get a Vector3 and find the coordinates. It went well, until I tried to make the camera get closer to the player if there is a collider in the way and then when the collider’s gone, smoothly go back to its default position.
Problem: So I’ve made my class called SphericalCoords and to get that functionality I decided I needed three fields of its type (three SphericalCoords objects? Forgive the terminology if it’s wrong. Please correct me if it is) to have spherical coordinates for the max distance, min distance and position of the camera that is derived from the former.
So after having declared and set sphecoMax (for the max distance) I wrote:
SphericalCoords sphecoMin = sphecoMax; // this line is obviously not doing what I thought it would do sphecoMin.r = targetRayHit.point.magnitude;
Anyway the problem seems to be that the new variable doesn’t hold a copy of sphecoMax, it holds sphecoMax itself?
When I change sphecoMin.r, sphecoMax.r also changes…
I thought this wouldn’t happen because I’d seen and written similar code with Vector3 and it works but I checked it to make sure. And sure this code that is similar to the above works:
Vector3 testVector2 = testVector;
testVector2.y = 10;
y only changes in testVector2 and testVector remains unchanged…
So… I guess I have to make a method to duplicate a SphericalCoords object and do what I thought = would do.
But still, I want to clear this up so the question is: why does = work differently with Vector3? Can I make my class work like that? Did I miss something else?
Sorry for asking if this is already explained in tutorials. It feels pretty basic, but I haven’t ran across it yet, and thought it wouldn’t hurt to ask here.