如何在Unity中输入IP地址?

How to enter ip address into Unity?

我有 3 个单独的代码,要求我在室外测试时手动更改 ip 地址。因此我试图统一输入一个输入字段,这样我就可以输入一次,我的所有代码都会使用它,但我不知道该怎么做。

这只是我在 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 页面。这只是一部分代码,我只放了相关的部分。我想要替换的是 'localhost' 从只读字符串到我的 Homepage.cs 页面的输入字段。有解决办法吗?

是的,有多种方法。其中之一可能正在使用 FindObjectOfType in order to get a reference to the Homepage component. Then you can access all its public members like in your case the ipField which is an InputField so you can simply read out its InputField.text

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

万一Homepage只有一个实例呢。


如果可能,您应该使用 public[SerializeField] private 字段直接在 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;

请注意,如果相应对象处于非活动状态或组件已禁用,FindObjectOfType 将失败!


您也可以通过使用 read-only property

仅提供 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;

最后,对于 IP/URL 字段,您可以使用 Regex 检查输入的有效性。