2017-10-06 124 views
1

我正在製作一個基本的籃球比賽,我有一個公共布爾值,稱爲dunkComplete,在球被扣球后被激活並被附加到球腳本上,我試圖在遊戲中引用該布爾值經理腳本,但由於某種原因,即使dunkComplete成爲真正的遊戲管理器副本不會,但請參閱遊戲管理器腳本。引用非靜態變量

using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 

public class game_manager : MonoBehaviour { 

    public GameObject Basket; 

    private float x_value; 
    private float y_value; 

    public GameObject ball; 
    private ball_script basketBallScript; 
    private bool dunkCompleteOperation; 

    // Use this for initialization 
    void Start() { 
     basketBallScript = ball.GetComponent<ball_script>(); 

     Vector2 randomVector = new Vector2(Random.Range(-9f, 9f), Random.Range(0f, 3f)); 

     Debug.Log(randomVector); 

     Instantiate(Basket, randomVector, transform.rotation); 

     Instantiate(ball, new Vector2(0, -3.5f), transform.rotation); 
    } 

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

     dunkCompleteOperation = basketBallScript.dunkComplete; 

     if (dunkCompleteOperation == true) 
     { 
      Vector2 randomVector = new Vector2(Random.Range(-9f, 9f), Random.Range(0f, 3f)); 

      Instantiate(Basket, randomVector, transform.rotation); 
     } 
    } 
} 

任何幫助將大大apreciated謝謝。

+0

你能分享你的ball_script嗎?另外,是否只有一個球,或者你在扣籃之後產卵了? – ZayedUpal

回答

0

您的basketBallScript不會引用您實例化的球對象的ball_script。您應該保留對您創建的GameObject的引用,然後分配basketBallScript。

試試這個:

public class game_manager : MonoBehaviour { 

    public GameObject Basket; 

    private float x_value; 
    private float y_value; 

    public GameObject ball; 
    private ball_script basketBallScript; 
    private bool dunkCompleteOperation; 

    // Use this for initialization 
    void Start() { 

     Vector2 randomVector = new Vector2(Random.Range(-9f, 9f), Random.Range(0f, 3f)); 

     Debug.Log(randomVector); 

     Instantiate(Basket, randomVector, transform.rotation); 
     // Get the ref. to ballObj, which is instantiated. Then assign the script. 
     GameObject ballObj = Instantiate(ball, new Vector2(0, -3.5f), 
     transform.rotation) as GameObject; 
     basketBallScript = ballObj.GetComponent<ball_script>(); 
    } 

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

     dunkCompleteOperation = basketBallScript.dunkComplete; 

     if (dunkCompleteOperation == true) 
     { 
      Vector2 randomVector = new Vector2(Random.Range(-9f, 9f), Random.Range(0f, 3f)); 

      Instantiate(Basket, randomVector, transform.rotation); 
     } 
    } 
} 

而且,只是爲了讓你的代碼更容易跟隨別人的未來,你可能要檢查出general naming conventions

相關問題