Kas*_*ska 3 c# unity-game-engine
我家和大学的机器安装了不同版本的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);
}
}
Run Code Online (Sandbox Code Playgroud)
请帮忙!非常感谢!
您不能再像过去那样直接访问附加到GameObject的组件.你现在必须使用GetComponent.您的代码对Unity 4及更低版本有效,但对5不有效.
这些是错误:
rigidbody2D.MovePosition(targetPosition);
Run Code Online (Sandbox Code Playgroud)
和
float SantaBagWidth = renderer.bounds.extents.x;
Run Code Online (Sandbox Code Playgroud)
为了解决这个问题,声明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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2770 次 |
| 最近记录: |