1

我正在尝试使用 unity5 在线学习太空射击教程,但我遇到了刚体问题。

我意识到刚体已被替换为 Component.GetComponent() 但我想创建一个变量而不是全部输入。

我使用 Component.GetComponent() 收到大量错误,但不明白出了什么问题。

这是我的代码片段,我试图用夹子限制运动:

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

    public float speed;
    public float xMin, zMin, xMax, zMax;

    void FixedUpdate(){
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
        Component.GetComponent<Rigidbody>().velocity = movement*speed;

        Component.GetComponent<Rigidbody>().position = new Vector3
        (
            Mathf.Clamp(Component.GetComponent<Rigidbody>().position.x, xMin, xMax),
            0.0f,
            Mathf.Clamp(Component.GetComponent<Rigidbody>().position.z, zMin, zMax)
        );
    }
}

这是它给我的大量错误:

Finished updating scripts / assemblies

Some scripts have compilation errors which may prevent obsolete API usages to get updated. Obsolete API updating will continue automatically after these errors get fixed.

Assets/Scripts/PlayerController.cs(14,27): error CS0120: An object reference is required to access non-static member `UnityEngine.Component.GetComponent(System.Type)'

Assets/Scripts/PlayerController.cs(14,47): error CS0120: An object reference is required to access non-static member `UnityEngine.Component.GetComponent(System.Type)'

Assets/Scripts/PlayerController.cs(18,31): error CS1502: The best overloaded method match for `UnityEngine.Mathf.Clamp(float, float, float)' has some invalid arguments

Assets/Scripts/PlayerController.cs(18,31): error CS1503: Argument `#1' cannot convert `object' expression to type `float'

Assets/Scripts/PlayerController.cs(20,47): error CS0120: An object reference is required to access non-static member `UnityEngine.Component.GetComponent(System.Type)'

Assets/Scripts/PlayerController.cs(20,31): error CS1502: The best overloaded method match for `UnityEngine.Mathf.Clamp(float, float, float)' has some invalid arguments

Assets/Scripts/PlayerController.cs(20,31): error CS1503: Argument `#1' cannot convert `object' expression to type `float'

Assets/Scripts/PlayerController.cs(21,18): error CS1502: The best overloaded method match for `UnityEngine.Vector3.Vector3(float, float, float)' has some invalid arguments

Assets/Scripts/PlayerController.cs(21,18): error CS1503: Argument `#1' cannot convert `object' expression to type `float'

Assets/Scripts/PlayerController.cs(16,27): error CS0120: An object reference is required to access non-static member `UnityEngine.Component.GetComponent(System.Type)'

我觉得我错过了一些重要而明显的东西,因为这不是很多代码来保证这么多错误。

4

1 回答 1

1

在使用非静态类函数之前,您应该首先创建一个对象的实例。

在您的情况下,它很可能是附加了 RigidBody 组件的 gameObject。这是代码示例:

gameObject.GetComponent<RigidBody>().velocity = movement * speed;

分别重做代码中的其他字符串。

于 2015-07-11T07:10:18.683 回答