c#:Unity:从不同的脚本引用Rigidbody2d时遇到麻烦
本文关键字:Rigidbody2d 引用 遇到 麻烦 脚本 Unity | 更新日期: 2023-09-27 18:17:42
我的场景有一个主角,一个气球和一根绳子。我有一个连接到气球的弹簧关节2d,我希望能够将连接的身体更改为玩家点击的对象。到目前为止,我有以下两个脚本,一个用于气球,另一个用于连接体:
气球:using UnityEngine;
using System.Collections;
public class BalloonTethering : MonoBehaviour {
public SpringJoint2D theSpringJoint;
public Rigidbody2D theTether;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
theSpringJoint.connectedBody = theTether;
}
}
连接身体:using UnityEngine;
using System.Collections;
public class TetherAny : MonoBehaviour {
public GameObject mainBalloon;
public Rigidbody2D iAmATether = new Rigidbody2D();
// Use this for initialization
void Start () {
mainBalloon.GetComponents<BalloonTethering>();
iAmATether = this.gameObject.GetComponents<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
}
void OnMouseDown(){
BalloonTethering.theTether = iAmATether;
}
}
我一直得到以下两个错误在TetherAny脚本:
(12,17):错误CS0029:不能隐式转换类型"UnityEngine"。Rigidbody2D[]'到'UnityEngine。Rigidbody2D '
(21,34):错误CS0120:需要对象引用来访问非静态成员'BalloonTethering.theTether'
如果有人能告诉我我错在哪里,我将非常感激:)
谢谢!
从第一个错误行我可以告诉GetComponents()将返回多个Rigidbody2D对象,而不仅仅是一个。
http://docs.unity3d.com/ScriptReference/Component.GetComponents.html http://msdn.microsoft.com/en-us/library/aa288453%28v=vs.71%29.aspx使用这两个链接来了解实际发生了什么。
关于第二个…你正在尝试访问一个类的成员,而你没有这个类的对象(这不是你访问其他对象成员的方式)
http://msdn.microsoft.com/en-us/library/x9afc042.aspx在我看来,你应该先学习如何编程的基础知识,老实说。
(12,17):错误CS0029:不能隐式转换类型"UnityEngine"。Rigidbody2D[]'到'UnityEngine。Rigidbody2D '
GetComponents返回刚体列表。不能将整个列表分配给一个对象。你需要使用GetComponent,而不是GetComponents。单数。错误中Rigidbody2D后的'[]'表示它是一个列表,而不是单个对象。
(21,34):错误CS0120:需要对象引用来访问非静态成员'BalloonTethering.theTether'
这是因为你从来没有告诉它你想要它引用什么。您需要在气球对象上使用GetComponent()。这里还有其他问题,我很惊讶你没有得到更多的错误。只要您试图访问这些变量中的任何一个,就会出现问题!我将修复第一个脚本,让您继续前进
using UnityEngine;
using System.Collections;
public class BalloonTethering : MonoBehaviour {
public SpringJoint2D theSpringJoint;
public Rigidbody2D theTether;
// Use this for initialization
void Start () {
theSpringJoint = this.gameObject.GetComponent<SpringJoint2D>();
}
// Update is called once per frame
void Update () {
}
}
如果你想让connectedBody