简体   繁体   English

如何在 Unity 中更改播放器的 y 比例?

[英]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."当我尝试此代码时,它给了我以下错误:“无法修改 Transform.localRotation,因为它不是变量。”

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. Transform.localScaleVector3 属性Transform.localRotationQuaternion 属性,它们都是struct值类型属性。

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.你不能只改变它们的一个字段,因为它只会改变属性的 getter 返回的struct中的一个字段,但永远不会用新值调用属性的 setter。

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#另请参阅c# 中的结构和属性问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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