- Home /
Object Boundaries C# help please
So, I'm sorry I'm not great with C# I'm just learning. I'm trying to make the mouse follow an object (which works), but I want some boundaries (so the object can't move off screen). I thought my code would work, but I'm getting error CS1612: Cannot modify a value type return value of `UnityEngine.Transform.position'. Consider storing the value in a temporary variable. I don't quite know why its not working, but I'll attach it and hope that somebody knows what to do.
//the broken code
using UnityEngine;
using System.Collections;
public class MouseMove2D : MonoBehaviour {
private Vector3 mousePosition;
public float moveSpeed = 1f;
private float maxWidth = 16.6f;
private float minWidth = -16.6f;
private float maxHeight = 12.2f;
private float minHeight = -12.2f;
void Update (){
mousePosition = Input.mousePosition;
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
transform.position = Vector3.Lerp( new Vector3 (transform.position.x , transform.position.y, +1), mousePosition, moveSpeed);
if (transform.position.x > maxWidth)
transform.position.x = maxWidth;
if (transform.position.x < minWidth)
transform.position.x = minWidth;
if (transform.position.x > maxHeight)
transform.position.x = maxHeight;
if (transform.position.x < minHeight)
transform.position.x = minHeight;
}
}
Answer by Tarlius · Jun 10, 2014 at 08:15 AM
The clue is in the error. "Cannot modify a value type return value of `UnityEngine.Transform.position'. Consider storing the value in a temporary variable"
transform.position returns you a Vector3 which is a value type (in this case a struct). When you access a value type, a copy of it is made, so the version you get back is not the original, and any chances to it will not affect the original. This means that if you set the x on it, you set the x on the version of it that was returned to you, NOT the version in the transform. Ie:
transform.position.x = 0;
// is the same as:
Vector3 pos = transform.position;
pos.x = 0;
What you need to do is take transform.position, store it locally, edit the value, then set it again. For example:
Vector3 pos = transform.position; // Returns you a *copy of* a the Vector3 position
// Some logic to change pos
pos.x = 0;
transform.position = pos; // Update the original with the updated value.
Its a bit of a gotcha in c#. If you want to know more, look up the difference between value types (int, float, struct; get copied) and reference types (classes; get a reference to the original).
Your answer
Follow this Question
Related Questions
Two methods are called on repet in my code and I don't know why 1 Answer
Camera Movement Bounds? 1 Answer
Help clamping player movement boundaries 1 Answer
Camera Boundry when changing orthographic size 0 Answers
How can I keep randomly moving enemies within a certain area (top-down 2D RPG)? 3 Answers