我目前正在努力使一個類可以從其他腳本訪問。以下是我編碼的內容。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
[RequireComponent(typeof(BoxCollider2D))]
// Start is called before the first frame update
public class _move
{
private float _sizex;
private float _sizey;
public _move(float sizx, float sizy....etc)
{
_sizex = sizx;
_sizey = sizy;
}
public void regularmove(float sizex, float sizey...etc)
{
GameObject _player;
_player = GameObject.GetComponent<GameObject>();
BoxCollider2D bc2d;
bc2d = _player.GetComponent <BoxCollider2D>();
bc2d.offset = new Vector2(locationx 1, locationy);
}
}
但是,當我嘗試編譯它時,它給了我一個錯誤。
cannot access non-static method"GetComponent"
在這行代碼上
_player = GameObject.GetComponent<GameObject>();
我不知道為什么會發生這種情況,因為我沒有將類宣告為靜態的,并且不太了解 GetComponent 的屬性。有人可以告訴我發生了什么以及如何解決這個問題嗎?另外,當我改變
GameObject _player;
to
public GameObject player;
下面的腳本突然停止作業,給我這樣的錯誤
cannot resolve symbol _player
這里到底發生了什么?提前致謝!
uj5u.com熱心網友回復:
無論創建 _move 類實體的腳本(順便說一句,這不好命名,它應該是 Move)也應該將其 gameObject 傳遞給建構式。
// attributes here are not valid if your class is not a MonoBehaviour
public class Move
{
GameObject m_object;
public Move(GameObject obj, ...)
{
m_object = obj;
}
}
如果你的類是一個 MonoBehaviour 組件,那么它已經有一個 GameObject 成員,你可以使用屬性:
[RequireComponent(typeof(BoxCollider2D),typeof(Rigidbody2D))]
// Start is called before the first frame update
public class Move : MonoBehaviour
{
void Start()
{
Debug.Log(gameObject.name);
}
}
uj5u.com熱心網友回復:
問題是GetComponent()inGameObject未標記為,但static通過呼叫GameObject.GetComponent<GameObject>();您正試圖將其作為靜態方法訪問。
您需要先實體化 a GameObject,然后呼叫GetComponent(),即:
_player = new GameObject().GetComponent<GameObject>();
DateTime作為比較,您可以在兩種不同的環境中探索您對課程的選擇。
在static背景關系中,您可以呼叫諸如Today、UtcNow、之類的成員MinValue,它們不需要特定DateTime值即可計算其回傳值。
但是為了能夠呼叫 eg DayOfWeekor AddDays(),您需要一個已定義的DateTime實體來呼叫它們,因為它們需要一些背景關系來進行計算。
// Static examples
var today = DateTime.Today;
var utcNow = DateTime.UtcNow;
var minDate = DateTime.MinValue;
// Non-static examples
var dayOfWeek = today.DayOfWeek;
var tomorrow = today.AddDays(1);
var inlineDayOfWeek = new DateTime(2022, 3, 7).DayOfWeek;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/439968.html
