2017-10-06 123 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

相关问题