我有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页面。这只是代码的一部分,我只放了相关部分。我要替换的是从Homestring.cs页面的只读字符串到输入字段的“ localhost”。有针对这个的解决方法吗?
是的,有多种方法。其中之一可能是FindObjectOfType
为了获取对该Homepage
组件的引用而使用的。然后,您可以访问其所有public
成员,就像您的情况一样,ipField
这是一个,InputField
因此您可以简单地读出其成员InputField.text
ipAddress = FindObjectOfType<Homepage>().ipField.text;
万一只有一个实例Homepage
。
如果可能的话,您应该Registration
使用public
或[SerializeField] private
字段直接引用它,例如
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
如果相应对象处于非活动状态或禁用了compomemt ,则失败!
您还可以通过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来检查输入的有效性。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句