繁体   English   中英

一个变量来保存这个类中的值到unity3d中另一个类中的值?

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

大家好,我有一个Segment类,其中保存有一个称为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 () {

    }
}

在此类中,我有一个名为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类currentSegment变量中保留Segment类的nextSegment变量。 我该如何实现? 我上面实现的代码给出了一个错误,已显示为错误,已注释。

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

该错误是因为您没有在播放器类中声明Segment类,或者Segment不是静态类。

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

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

[SerializeField]
private Segment segment

当您添加这2行时,请更改此行:

currentSegment = Segment.nextSegment; //Error 

至:

currentSegment = segment.nextSegment;

最后,将GameObject(Segment脚本所在的位置)拖动到检查器中的可序列化字段(当您选择了Player脚本所在的GameObject时)。

选项2:您可以将Segment类设为静态。

更改此行:

public class Segment : MonoBehaviour {

至:

public static class Segment : MonoBehaviour{

而不是在类标题下添加以下行:

public Segment instace;

void Awake(){
instance = this;
}

现在更改:

currentSegment = Segment.nextSegment; //Error 

至:

currentSegment = Segment.instance.nextSegment;

我认为,我给您的第一个选择是解决此问题的最佳解决方案。

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

汤姆,

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM