- Home /
Unity error, can't modify transform.position value
So I have a door in my scene and I want a script (attached to the door) that adds an empty gameobject (hinge) to the scene, sets the position of the hinge to be in the left-down corner of the the door, and make the hinge a parent to the door so I can later on transform that empty gameobject with eulerangles, and the door will move with it.
I have this script:
using UnityEngine;
using System.Collections;
public class DoorScript : MonoBehaviour {
GameObject hinge;
public Transform door;
// Use this for initialization
void Start () {
hinge = new GameObject();
hinge.name = "hinge";
float PosDoorX = door.transform.position.x;
float PosDoorY = door.transform.position.y;
float PosDoorZ = door.transform.position.z;
float ScaleDoorX = door.transform.localScale.x;
float ScaleDoorY = door.transform.localScale.y;
hinge.transform.position.x = PosDoorX + ScaleDoorX / 2;
hinge.transform.position.y = PosDoorY - ScaleDoorY / 2;
hinge.transform.position.z = PosDoorZ;
door.transform.parent = hinge.transform;
}
// Update is called once per frame
void Update () {
}
}
It returns this error: 'Assets/Scripts/DoorScript.cs(21,33): error CS1612: Cannot modify a value type return value of `UnityEngine.Transform.position'. Consider storing the value in a temporary variable '
I know it means that I cant do math with the transform values, but how can I fix this?
tyvm!
Alexander
I basically want the game object to be in the left down corner of EVERY door, whatever the size or scale is. so I can just add the script to every door, and when I press play, there is an empty gameobject in the left corner of EVERY door.
Answer by Landern · Dec 26, 2014 at 07:00 PM
in C# you can't modify a struct directly, in unity/javascript it "appears" you can but during the script building process it does the same as i'm displaying below:
using UnityEngine;
using System.Collections;
public class DoorScript : MonoBehaviour {
GameObject hinge;
public Transform door;
// Use this for initialization
void Start () {
hinge = new GameObject();
hinge.name = "hinge";
float PosDoorX = door.transform.position.x;
float PosDoorY = door.transform.position.y;
float PosDoorZ = door.transform.position.z;
float ScaleDoorX = door.transform.localScale.x;
float ScaleDoorY = door.transform.localScale.y;
Vector3 posCopy = hinge.transform.position; // make a copy of the Vector3
posCopy.x = PosDoorX + ScaleDoorX / 2;
posCopy.y = PosDoorY - ScaleDoorY / 2;
posCopy.z = PosDoorZ;
hinge.transform.position = posCopy; // Reassign the Vector3 copy back to position
door.transform.parent = hinge.transform;
}
// Update is called once per frame
void Update () {
}
}