在 Unity3d 中将一个脚本的值传递给另一个脚本

Pass Value to One Script to Another in Unity3d

目前,我正在尝试将一个脚本的值添加/减去另一个脚本。我想要脚本一为脚本二添加 +125 健康但不知道如何。此场景中不涉及任何游戏对象。

脚本一是

using UnityEngine;
using System.Collections;

public class AddHealth : MonoBehaviour {

    int health = 10;

    public void ChokeAdd()

    {
        AddHealthNow();
    }

    public void AddHealthNow()
    {
        health += 125;
        Debug.Log("Added +125 Health");
    }
}

脚本二是

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

namespace CompleteProject
{
    public class DataManager : MonoBehaviour

    {
        public static int depth;        
        public Text BOPPressureText;
        int health = 20;

        void Awake ()

        {
            depth = 0 ;
        }

        void Update ()
        {
            BOPPressureText.text = depth + 7 * (health) + " psi ";
        }
    }
}

如果您尝试为第二个脚本添加生命值,请将您的 health 字段声明为 public。这样您就可以在您的第一个脚本中访问它的值。

public int health;

但我不会那样做。通过 属性 公开此字段,例如:

public int Health 
{
 get 
   {
    return this.health;
   }
 set 
   {
    this.health = value;
   }
}

默认情况下,健康将被声明为

private int health;

其他脚本无法访问私有字段。 您还需要参考您的第二个脚本。您可以通过以下方式访问:

public DataManager data;

您必须在 Unity 编辑器中将第二个对象分配到该字段中。然后 这样,您可以通过在第一个脚本中调用 data.health += 125 来访问字段 health

Unity中具体的我不清楚,不过我想你也可以通过以下方式调用你的脚本:

DataManager data = GetComponent<DataManager>();
data.health += 125;

获取其他脚本的其他方法是像在第一个脚本中那样调用它:

var secondScript = GameObject.FindObjectOfType(typeof(DataManager)) as DataManager;
secondScript.health += 125;