【问题标题】:Pass Value to One Script to Another in Unity3d在 Unity3d 中将值传递给一个脚本到另一个脚本
【发布时间】:2016-04-13 12:59:09
【问题描述】:

目前,我正在尝试将一个脚本中的值添加/减去另一个脚本。我希望脚本一为脚本二添加 +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 ";
        }
    }
}

【问题讨论】:

  • "此场景中不涉及游戏对象。"当您在 Unity 中工作时,这是一个相当大的要求,而且非常重要。在不将它们与游戏对象关联的情况下,您是如何制作这些组件的?

标签: c# unity3d send


【解决方案1】:

如果您尝试为第二个脚本添加运行状况,请将您的 health 字段声明为公开。这样您就可以在您的第一个脚本中访问它的值。

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;

【讨论】:

  • 我在添加 DataManager 数据时遇到一些错误 = GetComponent();在第二个脚本上。
  • 你有没有引用你的第一个脚本,它是否在同一个命名空间中,如果不考虑将它添加到你的 usings 中。
  • 不,它没有任何参考。
  • 我目前收到此错误“找不到类型或命名空间名称‘DataManager’。您是否缺少 using 指令或程序集引用?”
  • 如果您使用的是 Visual Studio,请尝试右键单击并“解决”。否则,在第一个脚本中添加对第二个脚本的引用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-07
  • 1970-01-01
  • 1970-01-01
  • 2013-05-07
  • 2011-02-08
  • 1970-01-01
相关资源
最近更新 更多