Why does this script require me to assign this variable twice to work?
Hello! So I am a beginner to Unity and programming, and have decided to start simple with Pong, using a tutorial. But while I was trying to make it so the paddles did not leave the screen/set the boundaries for the screen, I noticed something in my script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Playercontrol : MonoBehaviour
{
public KeyCode moveUp = KeyCode.W;
public KeyCode movedown = KeyCode.S;
public float speed = 10.0f;
public float boundY = 1f;
private Rigidbody2D rb2d;
// Use this for initialization
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
{
var vel = rb2d.velocity;
if (Input.GetKey(moveUp))
{
vel.y = speed;
}
else if (Input.GetKey(movedown))
{
vel.y = -speed;
}
else if (!Input.anyKey)
{
vel.y = 0;
}
rb2d.velocity = vel;
var pos = transform.position;
if (pos.y > boundY)
{
pos.y = boundY;
}
else if (pos.y < -boundY)
{
pos.y = -boundY;
}
transform.position = pos;
}
}
}
This code works perfectly, no issues. The paddles cannot leave past the boundaries I have set for them within the script. But I do have a question. Why is it when I remove transform.position = pos;
From the code, it no longer works? I don't understand why I have to reassign the variable after the function- but without it, the script will not preform correctly. The paddles are able to go past the boundaries I set. I can't get my head around why. Any help would be greatly appreciated!
Answer by Hellium · Mar 02, 2018 at 11:22 PM
Because the Vector3
type is a value type.
In many programming languages, variables have what is called a "data type". The two primary data types are value types (int, float, bool, char, struct, ...) and reference type (instance of classes). While value types contains the value itself, references contains a memory address pointing to a portion of memory allocated to contain a set of values (similar to C/C++).
For example, Vector3 is a value type (a struct containing the coordinates and some functions) while components attached to your GameObject (including your custom scripts inheriting from MonoBehaviour) are reference type.
Thus, calling var pos = transform.position;
makes a copy of the position of the transform into the pos
variable.
When you apply changes to pos
, they are not applied to the transform.position
. So you have to reassign the pos
to transfor.position
Your answer
