我家里和大学的计算机都安装了不同版本的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);
    }
}


请帮忙!非常感谢!

最佳答案

您不能再像过去那样直接访问附加到GameObject的组件。您现在必须使用GetComponent。您的代码对Unity 4及更低版本有效,但对5不有效。

这些是错误:

rigidbody2D.MovePosition(targetPosition);




float SantaBagWidth = renderer.bounds.extents.x;


要解决此问题,请用rigidbody2D声明Rigidbody2D rigidbody2D;

然后使用GetComponent通过GetComponent<Renderer>().bounds.extents.x;获取渲染器

整个代码:

public Camera cam;

private float maxWidth;

Rigidbody2D rigidbody2D;

// Use this for initialization
void Start()
{
    rigidbody2D = GetComponent<Rigidbody2D>();

    if (cam == null)
    {
        cam = Camera.main;
    }
    Vector3 upperCorner = new Vector3(Screen.width, Screen.height, 0.0f);
    Vector3 targetWidth = cam.ScreenToWorldPoint(upperCorner);
    float SantaBagWidth = GetComponent<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);
}

07-25 20:53