对于一个学校项目,我建立了一个API在团结。在这样做时,发生了以下警告:
--您正在尝试使用'new‘关键字创建一个MonoBehaviour。这是不允许的。MonoBehaviours只能使用AddComponent()添加。或者,您的脚本可以从ScriptableObject继承,也可以在所有UnityEngine.MonoBehaviour:.ctor()中没有基类。
我没有GameObject。它是一个应该为纯接口服务的脚本。下面是我的密码。有人能帮我吗?
public class ApiPost : MonoBehaviour
{
public static bool PostDataSchachtGui(string url,string SchachtNrGui)
{
bool isfinish = false;
var instance = new ApiPost();
instance.StartCoroutine(Post(url, SchachtNrGui));
IEnumerator Post(string uri, string schacht_nr)
{
WWWForm form = new WWWForm();
form.AddField("SchachtNr1", schacht_nr);
UnityWebRequest www = UnityWebRequest.Post(uri, form);
www.chunkedTransfer = false;
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
isfinish = false;
}
else
{
isfinish = true;
}
}
return isfinish;
}
}{
// Start is called before the first frame update
public void abfragen(string button)
{
if (button == "start")
{
StartBtn.postdata();
}
else
{
}
}
}public static void postdata()
{
//Suche Inputfeld
GameObject Schacht_field = GameObject.Find("Schacht_field");
input Schacht = Schacht_field.GetComponent<input>();
SchachtNrGui = Schacht.inputtext;
//Setze Globale Daten
StaticData.SchachtNrDataShow = SchachtNrGui;
//Poste Daten
var check = ApiPost.PostDataSchachtGui("http://localhost/prototype1/setumgevar.php", SchachtNrGui);
if (check == true)
{
//ApiGet.GetAllData("http://localhost/prototype1/getdata.php");
}
}发布于 2020-05-12 15:11:23
您的问题在于读取var instance = new ApiPost();的行。
类ApiPost继承自Monobehaviour,与错误状态一样,不允许使用new关键字创建MonoBehaviour,但可以通过AddComponent()方法添加MonoBehaviours。
你有两个主要的行动路线
Monobehaviour中删除继承。使用public class ApiPost.public class ApiPost : MonoBehaviour,以不同的方式创建ApiPost实例。您可以将它附加到的对象( Instantiate )、对象( GetComponent )、对象(GetComponent)或不同的方法(GetComponent)。例如,您可以通过将ApiPost附加到ApiGameObject,然后调用:var实例= ApiGameObject.GetComponent();
希望这能有所帮助!
发布于 2020-05-12 15:04:07
你能更具体地回答这个问题吗?这里是什么?
如果您谈论的是ApiPost,那么是的,您不能像这样实例化一个MonoBehaviour。您必须将该脚本附加到GameObject,然后在脚本中引用该GameObject。然后使用这个游戏对象,使用GetComponent()访问脚本。
所以就像这样:
//write this in your class
public GameObject myGameObject;
//write this in your function:
var instance = myGameObject.GetComponent<ApiPost>();https://stackoverflow.com/questions/61754806
复制相似问题