unity3d - C# Unity:无法将方法组“GetComponent”转换为非委托类型“Rigidbody2D”
问题描述
我是 C#/C++ 新手(对不起,如果代码中的错误很明显。)
我正在使用本教程(1:27:47 标记)并且遇到了错误。我试图通过在网上寻找其他有类似问题的人的解决方案来修复此代码。当我第一次得到这个代码时,错误是:
UnityEngine.Component' does not contain a definition for 'velocity' and no extension method 'velocity' of type 'UnityEngine.Component' could be found. Are you missing an assembly reference?'
在我应用了一些修复之后,这就是代码现在的样子:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
//This scrits makes the character move when the screen is pressed and
handles the jump
public class CharacterFinal : MonoBehaviour
{
public bool jump = false; // Condition for whether the player should jump.
public float jumpForce = 10.0f; // Amount of force added when the player jumps.
private bool grounded = false; // Whether or not the player is grounded.
public int movementSpeed = 10; // The vertical speed of the movement
private Animator anim; // The animator that controls the characters animations
//Declare rigid2D
Rigidbody2D rigid2D;
// Use this for initialization
void Awake()
{
anim = GetComponent<Animator>();
//Initialize rigid2D
rigid2D = GetComponent<Rigidbody2D>;
}
//This method is called when the character collides with a collider (could be a platform).
void OnCollisionEnter2D(Collision2D hit)
{
grounded = true;
print ("isground");
}
//The update method is called many times per seconds
void Update()
{
if(Input.GetButtonDown("Fire1"))
{
// If the jump button is pressed and the player is grounded and the character is running forward then the player should jump.
if(grounded == true)
{
jump = true;
grounded = false;
//We trigger the Jump animation state
anim.SetTrigger("Jump");
}
}
}
//Since we are using physics for movement, we use the FixedUpdate method
void FixedUpdate ()
{
//if died that
rigid2D.velocity = new Vector2(movementSpeed, rigid2D.velocity.y );
//else
//moving
// If jump is set to true we add a quick force impulse for the jump
if(jump == true)
{
// Add a vertical force to the player.
rigid2D.AddForce(new Vector2(0f, jumpForce),ForceMode2D.Impulse);
// We set the variable to false again to avoid adding force constantly
jump = false;
}
}
}
它给出的错误是这样的
Cannot convert method group 'GetComponent' to non-delegate type
UnityEngine.Rigidbody2D'.
错误在第 22 行
rigid2D = GetComponent<Rigidbody2D>;
解决方案
简单地改变
rigid2D = GetComponent<Rigidbody2D>;
至
rigid2D = GetComponent<Rigidbody2D>();
注意()
最后。该错误表示它无法转换“方法组” - 那是因为它是一种方法,但您没有正确调用它。
推荐阅读
- java - 如何使用 .json 文件刷新基本“数据库”
- angular - 带有 intl 的 angular/devextreme 中的自定义日期格式
- c# - .NET 何时尝试解析程序集引用?
- java - 创建一个简单的 Java 规则引擎
- javascript - 如何相对于映射的 div 放置组件?反应 Redux CSS
- ascii - \033[ 中的控制序列列表(用于 urxvt 键符)
- batch-file - 将错误级别与字符进行比较时批处理文件退出
- python - 如何将 5D 张量输入 LSTM?
- java - 如何使用 jsoup 获取 html 类型的 url
- scala.js - 在 Scala.js 外观中,为什么 @js.native 注释排除了 @JSExport 注释?