gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:24:27 26 4
gpt4 key购买 nike

我在家里和大学里的机器安装了不同版本的 Unity。在我家较新,在大学较年长,我想知道这是否是导致我出现问题的原因。游戏运行良好,直到我尝试在家用计算机上进一步开发它。

得到两条错误信息:

“UnityEngine.Component”不包含“bounds”的定义,并且找不到类型为“UnityEngine.Component”的扩展方法“bounds”。您是否缺少程序集引用?

和:

“UnityEngine.Component”不包含“MovePosition”的定义,并且找不到“UnityEngine.Component”类型的扩展方法“MovePosition”。您是否缺少程序集引用?

这是我的代码:

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);
}
}

求助!非常感谢!

最佳答案

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

这些是错误:

rigidbody2D.MovePosition(targetPosition);

float SantaBagWidth = renderer.bounds.extents.x;

要修复它,请声明 rigidbody2DRigidbody2D 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);
}

关于c# - UnityEngine.Component 不包含定义...C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41123057/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com