简体   繁体   中英

How do I change the y scale of my player in Unity?

When I try this code it gives me the following error: "Cannot modify Transform.localRotation because it's not a variable."

public Transform Player;
public float speed = 12f;
bool isGrounded;

if (Input.GetKey("left ctrl") && isGrounded)
{
     speed = 6f;

     Player.localScale.y = 0.5f;
}
else
{
     speed = 12f;
     Player.localScale.y = 1f;
}

The Transform.localScale is a Vector3 property as well as the Transform.localRotation a Quaternion property which are both struct and thereby value type properties.

You can't just change a field of them because it would only change a field in the struct value returned by the getter of the property but never call the setter of the property with the new value.

You rather have to reassign the entire value like eg

// Store in a temporary variable
var scale = Player.localScale;
// Now in a variable (or field) you CAN change the field values
scale.y = 0.5f;
// Assign back to the property
Player.localScale = scale;

See also Problem with struct and property in c#

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM