我正在用 Unity 制作一個游戲,我正在開發一個庫存系統,我想要做的是創建一個名為 Item 的類,它具有創建專案所需的所有必要資訊和功能,然后它還有一個物件用它來創建每個專案,這是迄今為止的簡單類
public class Item
{
public Item(string name, GameObject obj)
{
//name to display in inventory
String ItemName = name;
//object to be shown in inventory slot
GameObject ShownObj = obj;
}
}
但是當我嘗試使用該物件來創建一個新專案時,我通過了一個統一游戲物件,它給了我一個錯誤,說你不能使用帶有非靜態類的欄位初始值設定項,我該如何解決這個問題或得到周圍? 這是我嘗試使用該課程的方式:
Public gameobject item;
public Item testItem = new Item("test item", item);
uj5u.com熱心網友回復:
Item當你傳入一個像你的游戲物件這樣的非靜態變數時,你不能在函式之外呼叫建構式!
您試圖在編譯時之前宣告和初始化 Item 變數(因為它在函式之外),這對于非靜態內容是不可能的,因為它們可以更改。
但是你可以初始化它,Start其中呼叫一次。剛剛宣布將基準作為公共變數和初始化它Start。
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ItemTest : MonoBehaviour
{
// public Item item = new Item("test item", obj); // won't work!
public GameObject obj;
public Item item;
// Start is called before the first frame update
void Start()
{
item = new Item("test item", obj);
}
// Update is called once per frame
void Update()
{
}
}
public class Item
{
String ItemName;
//object to be shown in inventory slot
GameObject ShownObj;
public Item(string name, GameObject obj)
{
//name to display in inventory
ItemName = name;
//object to be shown in inventory slot
ShownObj = obj;
}
}
注意:如果您的Item建構式只有一個 String 作為建構式引數,它會作業得很好,因為該字串是在編譯時完全定義的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/315783.html
上一篇:ReactNative渲染物件鍵
