UnityEngine.Component不包含定义... C#

时间:2016-12-13 14:02:34

标签: c# unity3d

我家和大学的机器安装了不同版本的Unity。在我家更新,在大学时更老,我想知道这是不是导致我的问题。游戏工作正常,直到我试图在家用电脑上进一步开发它。

收到两条错误消息:

'UnityEngine.Component' does not contain a definition for 'bounds' and no extension method 'bounds' of type 'UnityEngine.Component' could be found. Are you missing an assembly reference?

'UnityEngine.Component' does not contain a definition for 'MovePosition' and no extension method 'MovePosition' of type 'UnityEngine.Component' could be found. Are you missing an assembly reference?

这是我的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SantaBagController : MonoBehaviour {

    public Camera cam;

    private float maxWidth;

    // Use this for initialization
    void Start () {
        if (cam == null) {
            cam = Camera.main;
        }
        Vector3 upperCorner = new Vector3 (Screen.width, Screen.height, 0.0f);
        Vector3 targetWidth = cam.ScreenToWorldPoint (upperCorner);
        float SantaBagWidth = renderer.bounds.extents.x;
        maxWidth = targetWidth.x - SantaBagWidth;
    }


    // Update is called once per frame
    void FixedUpdate () {
            Vector3 rawPosition = cam.ScreenToWorldPoint (Input.mousePosition);
            Vector3 targetPosition = new Vector3 (rawPosition.x, 0.0f, 0.0f);
            float targetWidth = Mathf.Clamp (targetPosition.x, -maxWidth, maxWidth);
            targetPosition = new Vector3 (targetWidth, targetPosition.y, targetPosition.z);
            rigidbody2D.MovePosition (targetPosition);      
    }
}

请帮忙!非常感谢!

2 个答案:

答案 0 :(得分:5)

您无法再像过去那样直接访问附加到GameObject的组件。您必须现在使用class。您的代码对Unity 4及以下版本有效,但不适用于5。

这些是错误:

GetComponent

rigidbody2D.MovePosition(targetPosition);

要解决此问题,请使用float SantaBagWidth = renderer.bounds.extents.x; 声明rigidbody2D

然后使用GetComponent获取带有Rigidbody2D rigidbody2D;

的渲染器

整个代码:

GetComponent<Renderer>().bounds.extents.x;

答案 1 :(得分:1)

使用“MonoBehaviour属性”(例如转换,渲染器,...等折旧。

相反,请使用显式函数GetComponent

    Renderer r = GetComponent<Renderer>();
    if( r != null )
    {
          float santaBagWidth = r.bounds.extents.x;
          maxWidth = targetWidth.x - santaBagWidth ;
    }

对你刚性的人也有同样的建议。将其缓存在Awake功能中并在Fixed Update

中使用它
private Rigidbody2D r2D ;

void Awake()
{
    r2D = GetComponent<Rigidbody2D>() ;
    if( r2D == null )
         r2D = gameObject.AddComponent<Rigidbody2D>();
}

void FixedUpdate () {
   Vector3 rawPosition = cam.ScreenToWorldPoint (Input.mousePosition);
   Vector3 targetPosition = new Vector3 (rawPosition.x, 0.0f, 0.0f);
   float targetWidth = Mathf.Clamp (targetPosition.x, -maxWidth, maxWidth);
   targetPosition = new Vector3 (targetWidth, targetPosition.y, targetPosition.z);
    r2D.MovePosition (targetPosition);      
}