如何从另一个脚本C#获取变量

时间:2018-03-07 04:24:46

标签: c# string scripting

我完全陷入困境,我觉得这也是一个简单的问题。基本上,我在一个名为pubKey的脚本中有两个字符串privKeyWalletGen.cs,我想在Loader.cs中显示它们。在我寻找答案的过程中,我所能找到的就是如何在Unity中完成它,因为我使用Unity,所以它并没有完全帮助。

以下是WalletGen.cs

的代码
namespace scriptcoin
{
    public class WalletGen
    {
        static void WalletHash()
        {
            Random rnd = new Random();
            int seed = rnd.Next();

            byte[] data = BitConverter.GetBytes(seed);
            byte[] pubData;
            byte[] privData;

            SHA384 pubHash = new SHA384Managed();
            pubData = pubHash.ComputeHash(data);
            pubData = pubHash.ComputeHash(pubData);
            seed = rnd.Next();
            SHA256 privHash = new SHA256Managed();
            privData = privHash.ComputeHash(data);

            string pubKey = Convert.ToBase64String(pubData);
            string privKey = Convert.ToBase64String(privData);
        }
    }
}

我在Loader.cs中确实没有任何特定代码,因为我无法弄明白。

2 个答案:

答案 0 :(得分:0)

由于您的代码代表您无法访问pubKey或privKey,因为它们仅存在于方法WalletHash的范围内。

要公开它们,您可以从WalletHash返回它们,例如

    public static Tuple<string, string> WalletHash()
    {
        Random rnd = new Random();
        int seed = rnd.Next();

        byte[] data = BitConverter.GetBytes(seed);
        byte[] pubData;
        byte[] privData;

        SHA384 pubHash = new SHA384Managed();
        pubData = pubHash.ComputeHash(data);
        pubData = pubHash.ComputeHash(pubData);
        seed = rnd.Next();
        SHA256 privHash = new SHA256Managed();
        privData = privHash.ComputeHash(data);

        string pubKey = Convert.ToBase64String(pubData);
        string privKey = Convert.ToBase64String(privData);
        return new Tuple<string, string>(pubKey, privKey);
    }

然后在Loader中,您可以从WalletHash获取值(假设您当前正在从Loader调用WalletHash

Tuple<string, string> keys = WalletGen.WalletHash();
string pubKey = keys.Item1;
string privKey = keys.Item2;

答案 1 :(得分:-1)

将代码更改为lil bit请尝试。

namespace scriptcoin
{
    public class WalletGen
    {
        static string privKey=string.Empty,pubKey=string.Empty;
        static void WalletHash()
        {
            Random rnd = new Random();
            int seed = rnd.Next();

            byte[] data = BitConverter.GetBytes(seed);
            byte[] pubData;
            byte[] privData;

            SHA384 pubHash = new SHA384Managed();
            pubData = pubHash.ComputeHash(data);
            pubData = pubHash.ComputeHash(pubData);
            seed = rnd.Next();
            SHA256 privHash = new SHA256Managed();
            privData = privHash.ComputeHash(data);

            pubKey = Convert.ToBase64String(pubData);
            privKey = Convert.ToBase64String(privData);
        }
    }
}