[英]UNity3D, return value from one class/method to another class/method in 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.