【问题标题】:Acces a variable from a C# script from another C#? [duplicate]从另一个 C# 访问 C# 脚本中的变量? [复制]
【发布时间】:2017-01-19 03:16:30
【问题描述】:

这就是我在脚本 A 中的内容

using UnityEngine;
using System.Collections;

public class gameController : MonoBehaviour 
{
    public int Score;
    ...

我想从另一个脚本访问“分数”变量,但我不知道该怎么做?有什么帮助吗?

【问题讨论】:

    标签: c# unity3d int unityscript var


    【解决方案1】:

    有很多方法可以访问其他脚本的属性/方法。您可以使用 1) 单例模式、2) 类对象引用、3) 属性等等。

    以下是上述三种方式的基本思路

    1) 单例模式

    定义类的单例实例如下: 公共静态游戏控制器实例;

    并使用此实例获取分数,如下所述: gameController.Instance.Score

    2) 类对象引用

    获取类的对象,如下所示: public gameController gameControllerObjectRef;

    并使用该对象来访问分数,如下所述: gameControllerObjectRef.Score;

    3) 属性

    属性与第二种方式相同,只是提供了更好的类方法/成员的访问控制 有关属性的更多信息,请参阅此链接:https://unity3d.com/learn/tutorials/topics/scripting/properties

    希望这会对你有所帮助...

    最好, 哈迪克。

    【讨论】:

      【解决方案2】:

      您可以执行以下操作:

      public int temp =  GameObject.Find("<name of the gaeme object to which your script is attached>").GetComponent<gameController>().Score
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多