【问题标题】:How to enter ip address into Unity?如何在 Unity 中输入 IP 地址?
【发布时间】:2020-05-19 15:00:26
【问题描述】:

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

【问题讨论】:

  • 这能回答你的问题吗? Replace host in Uri
  • 如何从我的 Registration.cs 中调用它,因为我尝试通过键入字符串 ipAddress = Homepage.findObjectofType 来使用统一代码,并且出现错误说我无法将其转换为字符串跨度>

标签: c# unity3d uitextfield ip user-input


【解决方案1】:

是的,有多种方法。其中之一可能正在使用FindObjectOfType 以获取对Homepage 组件的引用。然后您可以访问它的所有public 成员,例如在您的情况下是ipField,这是一个InputField,因此您可以简单地读出它的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 来检查输入的有效性。

【讨论】:

  • 非常感谢,花了我一段时间来理解和实施(有点初学者),但这为我解决了。我选择了你的第二个解决方案
  • @CodingNeeded 很高兴能提供帮助 :) 第二个实际上更好,因为 FindObjectOfType 非常昂贵,并且已经通过 Inspector 引用了一些东西可以防止这种开销;)
猜你喜欢
  • 1970-01-01
  • 2013-11-02
  • 2019-01-29
  • 2016-01-11
  • 2012-06-23
  • 1970-01-01
  • 1970-01-01
  • 2015-01-15
  • 1970-01-01
相关资源
最近更新 更多