【发布时间】:2017-04-09 05:11:04
【问题描述】:
您好,我想从 Unity 的另一个类中获取一个变量
public class CameraMove : MonoBehaviour {
public GameObject lookTarget;
public GameObject MainCamera;
public GameObject nextMovePoint;
private int currentPoint = 0;
[System.Serializable]
public class Paths
{
public float time;
public Transform[] movePoints;
}
public Paths[] Path;
void Update()
{
Paths paths = gameObject.GetComponent<Paths>();
Debug.Log (paths.movePoints [currentPoint]);
if (nextMovePoint.transform.position != paths.movePoints [currentPoint].position)
{
currentPoint += 1;
nextMovePoint.transform.position = paths.movePoints [currentPoint].position;
}
iTween.MoveTo(nextMovePoint,iTween.Hash("time",paths.time));
}
我想从类 Paths 中获取 movePoints,但 GetComponent 给我一个错误?我如何获得该变量?
还在为此苦苦挣扎,有人知道吗?
【问题讨论】:
-
附有
CameraMove的游戏对象是否也有Paths? GetComponent 从选定的游戏对象中获取组件(在本例中为脚本)。如果它来自另一个游戏对象,您需要先找到该游戏对象,然后从该对象执行 GetComponent 并查看变量。GameObject.Find("Object with paths").GetComponent<Paths>();。但是,您不应该在Update()方法中执行此操作,因为它会运行每一帧,而您只需要执行一次,对吗?在Start()方法中执行此操作,并将Paths变量保存为要使用的类变量。 -
路径未附加。我该怎么做?它不在检查器中,而是在附加到对象的另一个脚本中。
-
然后 GetComponent 在另一个脚本上,然后通过那里获取它,如果该脚本将它作为变量。
Paths paths = GetComponent<AnotherScript>().pathsVariable;如果AnotherScript在另一个游戏对象上,您必须先获取该游戏对象。 -
您不能从另一个脚本执行 'Paths paths ='。此外,我没有另一个脚本,我只想要 1 个脚本中名为“CameraMove”的类中名为“Paths”的类中的“movePoints”。
-
不要在你的问题中到处写 C#,你应该把 C# 放在标签部分,就像你对 unity3d 所做的那样。我意识到这个问题有所不同,所以我重新打开它并更改了标题以匹配您正在做的事情。你还在为此苦恼吗?