[英]How do I access an updated variable between two scripts in Unity with C#?
希望這不是太多細節,我不習慣問編程問題。
我正在嘗試使用Udemy上的Unity 3D課程進行3D視頻游戲開發,盡管使用的是C#而不是Javascript。 我剛剛完成了有關創建太空射擊游戲的教程。
其中,用戶按下按鈕時會創建一個盾牌。 防護罩具有“使用次數”變量,在本教程完成時實際上並未使用。 我正在嘗試添加它,並成功地實現了它,因此每次使用時,我們都會減少剩余的使用次數,並且一旦該次數<= 0,就不再能夠實例化防護。
此變量存儲在播放器中,如果我從播放器中打印出來,它將返回我期望的值。
但是,我使用了一個單獨的SceneManager.cs(在此教程中放置了生命,得分和計時器變量),在該處將數字打印到GUI中。 我的問題是,當我嘗試從場景管理器打印它時,我無法使我的use變量數量保持最新狀態……它注冊了初始值,但此后不更新。
這是播放器腳本
using UnityEngine;
using System.Collections;
public class player_script : MonoBehaviour {
// Inspector Variables
public int numberOfShields = 2; // The number of times the user can create a shield
public Transform shieldMesh; // path to the shield
public KeyCode shieldKeyInput; // the key to activate the shield
public static bool shieldOff = true; // initialize the shield to an "off" state
public int NumberOfShields
{
get{return numberOfShields;}
set{numberOfShields = value;}
}
// Update is called once per frame
void Update()
{
// create a shield when shieldKey has been pressed by player
if (Input.GetKeyDown (shieldKeyInput)) {
if(shieldOff && numberOfShields>0)
{
// creates an instance of the shield
Transform clone;
clone = Instantiate (shieldMesh, transform.position, transform.rotation) as Transform;
// transforms the instance of the shield
clone.transform.parent = gameObject.transform;
// set the shield to an on position
shieldOff = false;
// reduce the numberOfShields left
numberOfShields -=1;
}
}
print ("NumberOfShields = " + NumberOfShields);
}
public void turnShieldOff()
{
shieldOff = true;
}
}
當我運行“ print(” NumberOfShields =“ + NumberOfShields);” 我得到了我期望的價值。 (當星形與屏蔽碰撞時,它們會觸發turnShieldOff()。
但是,在我的場景管理器中...這是我正在運行的代碼:
using UnityEngine;
using System.Collections;
public class SceneManager_script : MonoBehaviour {
// Inspector Variables
public GameObject playerCharacter;
private player_script player_Script;
private int shields = 0;
// Use this for initialization
void Start ()
{
player_Script = playerCharacter.GetComponent<player_script>();
}
// Update is called once per frame
void Update ()
{
shields = player_Script.NumberOfShields;
print(shields);
}
// GUI
void OnGUI()
{
GUI.Label (new Rect (10, 40, 100, 20), "Shields: " + shields);
}
}
知道我做錯了什么會阻止我的player_script中的NumberOfShields更新時,我的SceneManager腳本中的盾牌無法更新嗎?
我認為您可能已將一個預制塊分配給playerCharacter GameObject變量,而不是游戲單元中的實際變量。 在這種情況下,它將始終打印預設的默認屏蔽值。 而不是通過檢查器分配該變量,而是嘗試在Start函數中找到玩家GameObject。 例如,您可以給您的玩家對象一個標簽,然后:
void Start() {
playerCharacter = GameObject.FindGameObjectWithTag("Player");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.