如何在Unity中输入IP地址?

问题描述 投票:1回答:1

我有3个单独的代码,当我在外面进行测试时,需要我手动更改IP地址。因此,我试图统一输入一个输入字段,以便可以输入一次,并且所有代码都将使用它,但是我不知道该怎么做。

enter image description here这只是我在Homepage.cs页面中放置的一个简单输入字段,用于输入IP地址

using UnityEngine;
using UnityEngine.UI;

public class HomePage : MonoBehaviour
{
public Text playerDisplay;
public InputField ipField;
public Button submitButton;

private void Start()
{
    if (DBManager.LoggedIn)
    {
        playerDisplay.text = "Player: " + DBManager.username;
    }

}

public void QuitGame()
{
    Debug.Log("Quit!");
    Application.Quit();
}
}

这是我的主页代码,我只将InputField'ipField'放了进去。从这里输入我想将其传输到

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class Registration : MonoBehaviour
{
public InputField nameField;
public InputField passwordField;
public Text error1 = null;
public Text error2 = null;

public Button submitButton;

readonly string postUrl = "http://localhost/sqlconnect/register.php";

我的Registration.cs页面。这只是代码的一部分,我只放了相关部分。我要替换的是Homepage.cs页中从只读字符串到输入字段的“ localhost”。有解决方案吗?

c# unity3d uitextfield ip user-input
1个回答
0
投票

是的,有多种方法。其中之一可能是

ipAddress = FindObjectOfType<Homepage>().ipField.text;

如果仍然只有一个Homepage实例。


[如果可能,您应该像Registration中直接引用它

public class Registration : MonoBehaviour
{
    // Reference this via the Unity Inspector by drag&drop the according GameObject here
    [SerializeField] private Homepage homepage;

    private void Awake()
    {
        // You could still have a fallback here
        if(! homepage) homepage = FindObjectOfType<Homepage>();
    }

    ...
}

然后再简单地使用

ipAddress = homepage.ipField.text;

您也可以只提供public所需的东西,就可以遵循并遵守封装原则:

public class Homepage : MonoBehaviour
{
    // This still allows to reference the object in the Inspector 
    // but prevents direct access from other scripts
    [SerializeField] private InputField ipField;

    // This is a public ReadOnly property for reading the IP from other scripts
    public string IP => ipField.text;

    ...
}

然后回到您只需使用的Registartion

ipAdress = homepage.IP;
© www.soinside.com 2019 - 2024. All rights reserved.