如何使用 C# 在 Unity 中访问两个脚本之间的更新变量

本文关键字:脚本 两个 之间 变量 更新 何使用 Unity 访问 | 更新日期: 2023-09-27 18:32:40

希望这不是太多的细节,我不习惯问编程问题。

我正在尝试在Udemy上进行Unity 3D视频游戏开发课程,尽管使用C#而不是Javascript。我刚刚完成了涉及创建太空射击游戏的教程。

在其中,用户在按下按钮时会创建一个盾牌。shield 有一个"使用次数"变量,在教程结束时实际上并没有被使用。我正在尝试添加它,并已成功实现它,以便每次使用时,我们都会减少剩余的使用次数,并且一旦该数字为 <=0,我们就无法再实例化盾牌。

此变量存储在播放器上,如果我从播放器打印它,它将返回我期望的值。

但是,我使用的是单独的场景管理器.cs(这是教程放置生命、分数和计时器变量的地方(,我将数字打印到 GUI 中。 我的问题是,当我尝试从场景管理器打印它时,我无法让我的使用次数变量保持最新状态......它注册初始值,但之后不会更新。

这是播放器脚本

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;
    }
}

当我运行"打印("盾牌数量 = " + 盾牌数量(;"我得到了我期望的价值。(星体在与盾牌碰撞时触发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);
}
}

知道我做错了什么,阻止我的场景管理器脚本中的盾

如何使用 C# 在 Unity 中访问两个脚本之间的更新变量

牌在我的player_script更新时更新盾牌数量?

我想您可能已经将预制件分配给 playerCharacter GameObject 变量而不是实际的游戏单元。在这种情况下,它将始终打印预制件的默认屏蔽值。不要通过检查器分配该变量,而是尝试在开始函数中查找玩家游戏对象。例如,您可以为播放器对象指定一个标签,然后:

void Start() {
    playerCharacter = GameObject.FindGameObjectWithTag("Player");
}