简体   繁体   English

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

[英]Pass Value to One Script to Another in Unity3d

Currently, I'm trying to add / subtract value from one script to another. 目前,我正在尝试从一个脚本向另一个脚本添加/减去值。 I wanted script one to add +125 health to script two but don't know how. 我希望脚本一为脚本二增加+125生命值,但不知道如何。 There is no gameobject involved in this scenarios. 在这种情况下不涉及任何游戏对象。

Script one is 脚本一是

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

Script two is 脚本二是

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

If you're trying to add health to your second script, declare your health field as public. 如果您要向第二个脚本中添加运行状况,请将您的health字段声明为public。 So that you can access its value in your first script. 这样您就可以在第一个脚本中访问其值。

public int health;

But I wouldn't do stuff like that. 但是我不会那样做。 Expose this field by a property like: 通过以下属性公开此字段:

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

by default the health will be declared as 默认情况下,运行状况将声明为

private int health;

Other scripts can't access private fields. 其他脚本无法访问私有字段。 Also you need a reference to your second script. 您还需要引用第二个脚本。 You can access this via: 您可以通过以下方式访问它:

public DataManager data;

You've to assign your second object into this field in your Unity Editor. 您必须在Unity编辑器的此字段中分配第二个对象。 Then This way, you can access the field health by calling data.health += 125 in your first script. 然后,通过这种方式,您可以通过在第一个脚本中调用data.health += 125来访问字段health

I don't know the specific thing in Unity, but I think you can also call your script by: 我不知道Unity中的具体内容,但我认为您也可以通过以下方式调用脚本:

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

Other method to get your other script is call it like that in your first script: 获取其他脚本的另一种方法是像在第一个脚本中那样调用它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM