- Home /
Modifying CharacterController center (C#)
I'm getting this error when attempting to change the center of the character controller:
controller.center.y = controller.height/2;
Cannot modify a value type return value of 'UnityEngine.CharacterController.center'
I've had these problems with trying to edit the rotation and position of objects but I figured out a way around those. This here, though, I am clueless.
How should I do this? Thanks in advance!
Answer by Avaista · Jul 14, 2012 at 11:41 PM
Center itself is a property. It can be retrieved and set, but not modified. Most of the time this doesnt matter, as you get a reference type. But with structs like Vector3, its another story
So this is valid
Vector3 tempCenter = controller.center;
tempCenter.y = controller.height/2;
controller.center = tempCenter;
as is this
controller.center = new Vector3(controller.center.x,controller.height/2,controller.center.z);
but you cannot modify a value of a property that is value type (struct)
You can modify a variable on a reference type return(a class)
public class Bacon:Yummy
{
public int healthRestore;
}
public class MyClass
{
private Bacon myBacon;
public Bacon propertyExample
{
get{ return myBacon;}
set{myBacon = value;}
}
}
MyClass example = new MyClass();
int hp = example.propertyExample.healthRestore;
Is valid ONLY because Bacon is a class, and therefore a reference type. When you access the property, you are NOT modifying the returned value, since the reference to bacon remains unchanged.
I do not know if I explained that well, let me know if you would like clarification and where.
No that makes sense. I was just wondering though, how does UnityScript bypass it?
I don't use UnityScript, so I cannot say for sure. Could you send me a link to an example where, and I will try to answer to the best of my ability. Remember that it is completely fine to access the value of a variable in a value type property... Example
Debug.Log(transform.position.y);
...because this does not modify the value.
GET//O$$anonymous$$AY
return transform.position;
SET//O$$anonymous$$AY
transform.position = Vector3.zero;
$$anonymous$$ODIFY//NOT SO $$anonymous$$UCH
transform.position.x += 9001;
GET FIELD//Okay, the property value has not been changed
float height = transform.position.y;
Your answer
![](https://koobas.hobune.stream/wayback/20220613074206im_/https://answers.unity.com/themes/thub/images/avi.jpg)