Stu*_*ent 0 c# unity-game-engine unityscript
我试图将一些UnityScript代码转换为D#,我收到以下错误:
表达式表示的方法基团,其中一个
variable,value或type预期对Getcomponent
void Update ()
{
float xVel = GetComponent().Rigidbody2D().velocity.x;
if( xVel < 18 && xVel > -18 && xVel !=0){
if(xVel > 0){
GetComponent.Rigidbody2D().velocity.x=20;
}else{
GetComponent.Rigidbody2D().velocity.x = -20;
}
}
}
Run Code Online (Sandbox Code Playgroud)
您的问题是:GetComponent().Rigidbody2D()因为这不是您使用GetComponent的方式,您看到的错误可能是因为GetComponent需要参数或指定的类型.JS和C#GetComponent的工作方式略有不同.你可能意味着:
void Update ()
{
float xVel = GetComponent<Rigidbody2D>().velocity.x;
if( xVel < 18 && xVel > -18 && xVel !=0){
if(xVel > 0){
GetComponent<Rigidbody2D>().velocity.x = 20;
}else{
GetComponent<Rigidbody2D>().velocity.x = -20;
}
}
}
Run Code Online (Sandbox Code Playgroud)
同样在C#中,我认为你不能直接修改速度,因为它周围有属性包装器.相反,您必须手动将速度更新为新的速度Vector2.如果您只想设置x值,请传入现有y值.
我会写这样的东西:
private Rigidbody2D _rigidBody;
void Start()
{
_rigidBody = GetComponent<Rigidbody2D>();
}
void Update ()
{
float xVel = _rigidBody.velocity.x;
if( xVel < 18 && xVel > -18 && xVel !=0){
if(xVel > 0){
_rigidBody.velocity = new Vector2(20, _rigidBody.velocity.y);
}else{
_rigidBody.velocity = new Vector2(-20, _rigidBody.velocity.y);
}
}
}
Run Code Online (Sandbox Code Playgroud)
虽然我也将这个魔法18改为变量,但我不能在这里猜测它代表什么!
| 归档时间: |
|
| 查看次数: |
95 次 |
| 最近记录: |