簡體   English   中英

Unity3d AddComponent采用變量

[英]Unity3d AddComponent taking variable

詳細信息:在Unity3d上的C#中搜索統一文檔但該示例不適合我的情況,對於我訪問過的其他網站也是如此。 (我沒有按照我的意願列出它們。)

我想要做的是傳遞一個帶有構造函數的類變量作為組件:

CustomComponentClass ccc = new CustomComponentClass(2343, "blop");
gameObject.AddComponent(ccc);

我想知道我正在嘗試什么工作,或者如果我錯過了什么......

問題:

gameObject.AddComponent(ccc); -> cannot convert ccc to string.

gameObject.AddComponent<ccc>(); -> Are you missing a using directive or an assembly reference? (i'm not, i'm using a variable and all is in the same namespace)

gameObject.AddComponent<CustomComponentClass>(ccc); -> UnityEngine.GameObject.AddComponent(string) cannot be used with the type arguments

gameObject.AddComponent<CustomComponentClass>(2343, "blop"); -> No overload for method AddComponent takes 2 arguments

無論我嘗試什么都行不通。 C#不是真的像javascript,如果我是對的,我們以前能夠在js中的addcomponent中傳遞變量。

上下文:我必須在構造函數中完全傳遞它。 我有2個私有的字段,出於安全原因,我無法將其歸為靜態,常量或公共字段。

選項:如果答案對我來說太復雜,我可能會進行獲取/設置並檢查字段是否為空。

您絕對不需要將其傳遞給構造函數。

而是正常創建組件(不帶參數),將組件添加到游戲對象,然后在提供必要參數的組件上調用setup方法,並運行構造函數中當前具有的任何代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM