在 unity3d 中将此 class 中的值保存到另一个 class 的变量?

A variable to hold value in this class to from another class in unity3d?

大家好,我有一个段 class 保存这个值 nextSegment 代码如下。

public class Segment : MonoBehaviour {

    public SplineComputer spline;
    public Segment nextSegment;

    // Use this for initialization
    void Start () {

        spline = GetComponentInChildren<SplineComputer>();
        nextSegment = GetComponent<Segment>();

        if (nextSegment == null)
            Debug.Log("No segement");
        else
            Debug.Log("present "+ nextSegment);

        spline.space = SplineComputer.Space.Local;
        SplinePoint[] points = spline.GetPoints();

        if (points.Length == 0)
            return; 
    }

    // Update is called once per frame
    void Update () {

    }
}

在这个 class 中,我有一个名为 currentSegmant 的变量。写法如下

public class Player :MonoBehaviour {
void Start()
    {
        controller = GetComponent<CharacterController>();
        anim = GetComponent<Animator>();
        controller = GetComponent<CharacterController>();
        follower = GetComponent<SplineFollower>();

        currentSegment = Segment.nextSegment; //Error 

        Debug.Log(currentSegment);

        follower.onEndReached += Follower_onEndReached;

        currentDistanceOnPath = 50f;

    }

    private void Follower_onEndReached()
    {
        currentSegment = currentSegment.nextSegment;
        follower.computer = currentSegment.spline;

        Debug.Log(follower.computer);
    }
}

如上所示,我想在 Player class currentSegment 变量中保存 Segment class nextSegment 变量。我如何实现这一目标?我在上面实现的代码给出了一个错误,我将其显示为错误,已注释。

供参考错误是:非静态字段、方法或属性需要对象引用'Segment.nextsegment'.

此错误是因为您没有在播放器 class 中声明段 class 或段不是静态的 class。

有几种方法可以解决这个问题:

选项 1: 将以下行添加到您的播放器 class(在 currentSegment = Segment.nextSegment 之上;//错误行):

[SerializeField]
private Segment segment

添加这两行后更改此行:

currentSegment = Segment.nextSegment; //Error 

收件人:

currentSegment = segment.nextSegment;

最后将 GameObject(Segment 脚本附加到的位置)拖到检查器中的可序列化字段(当您选择了播放器脚本附加到的 GameObject 时)。

选项2: 您可以使段 class 静态。

更改此行:

public class Segment : MonoBehaviour {

收件人:

public static class Segment : MonoBehaviour{

然后添加以下行(在 class header 下方):

public Segment instace;

void Awake(){
instance = this;
}

现在更改:

currentSegment = Segment.nextSegment; //Error 

至:

currentSegment = Segment.instance.nextSegment;

我认为我给你的第一个选项是解决这个问题的最佳方案。

希望这个回答可以帮助您解决这个错误。

汤姆,