d

Vector3 instantiation

Dennis Brown
posted to: Basic Raycasting

Quick question for you:

At 3:15 you instantiated a new Vector3 class when using the coords, but when using the forward method you do not create a new class. Does this method instantiate a new Vector3 class through the method itself, so instantiating a new class is redundant?

  • Jonathan Gonzalez(jgonzalez) replied

    Vector3 is a struct, so every time we want to change the value of a Vector3 we need to create a new Vector3. It's not being instantiated, but rather being used as a direction for the raycast. 

    The first "transform.position" is a Vector3, which is used as the origin point of where the ray starts. The second parameter after that is the direction. Vector3.forward just means we want to use the Z axis for the direction. We're not changing the value of that Vector3 but just determining that we want to use the Z axis from that Vector3. 



  • d
    Dennis Brown replied

    Ahhhh! Great to know those are structs, and makes a lot more sense.

    So if I'm understanding you correctly, the first use was the initializing of a new Vector3 struct with the positioning (hence the new), and when using the forward we were still referencing that same struct, and the reason there was no need to create a new struct? 

  • Jonathan Gonzalez(jgonzalez) replied

    Yes that's correct. When we use Vector.forward (or any of the other shorthand ways) you're not assigning a new value, you're basically saying you want to move in a specific direction. Vector3.forward would be like saying I want to move along the Z axis. 

  • demonslayer112 replied

    I was gonna ask a question about something similar to this but this i saw this and it particaly answered my question. But now im currious about structs. Is there a unity or c# place on the site about them?