Problem with crouch script.

Hello everyone.

I’m trying to make a crouch script for my game, but I ran into one error that I cannot seem to understand on how to fix… I’m using c# script.

The error says: Assets/scripts/Crouch.cs(31,35): error CS1612: Cannot modify a value type return value of `UnityEngine.Transform.position’. Consider storing the value in a temporary variable

Can someone give me some advice on what am I doing wrong here?

P.S. Sorry if my english is bad…

The Script:

using UnityEngine;
using System.Collections;

public class Crouch : MonoBehaviour 
	private CharacterController charController;
	private Transform theTransform;
	private float charHeight;

	private float h;
	private float lastHeight;

	void  Start ()
		theTransform = transform;
		charController = GetComponent<CharacterController>();
		charHeight = charController.height;

	void  Update ()
		h = charHeight;

		if (Input.GetButton("Crouch"))
			h = charHeight * 0.15f;

		lastHeight = charController.height;
		charController.height = Mathf.Lerp(charController.height, h, 5 * Time.deltaTime);
		theTransform.transform.position.y += (charController.height - lastHeight) / 2;

You can’t change individual values of position, like position.y or position.x, instead, you need to set position as a new Vector3, like this:

*Also, why you reference theTransform.transform instead of just theTransform?

float x, y, z;
theTransform.position = new Vector3(x,y,z);

or in this case:

Vector3 pos = theTransform.position; //Actual position of the Transform
theTransform.position = new Vector3(pos.x,pos.y+((charController.height - lastHeight)/2),pos.z);

Just a little observation: You might want to reference .localPosition instead of position. So test both to see wich one fits better for you :slight_smile:

Vector3 pos = theTransform.localPosition; //Actual position of the Transform
theTransform.localPosition = new Vector3(pos.x,pos.y+((charController.height - lastHeight)/2),pos.z);