[英]How to add Class properties to List?
在MainClass中,我有:
public List<TransformData> matrices1 = new List<TransformData>();
public Vector3 scaleVector = 1f;
在TransformData類中,我有:
public class TransformData
{
public Vector3 position;
public Quaternion rotation;
public Vector3 scale;
}
回到MainClass,我想將TransformData中的信息添加到變量matrices1中。 您如何正確執行此操作? 我有-
matrices1.Add(TransformData.(TransformData.position, TransformData.rotation, scaleVector));
那給我錯誤。 我看到了其他有關此的StackOverflow問題,但我無法正確解決
先生,您在這里:
TransformData td = new TransformData();
matrices1.add(td);
如果您想在清除時添加參數,則向您的TransformData
類添加一個構造函數。
public class TransformData
{
public Vector3 position;
public Quaternion rotation;
public Vector3 scale;
public TransformData(){}
public TransformData(Vector3 pos, Quaternion rot, Vector3 sc)
{
position = pos;
rotation = rot;
scale = sc;
}
}
然后您就可以像您在代碼中所做的那樣進行操作。
matrices1.add(new Transformdata(somepos, somerotation, somevector));
您需要向保存數據的對象添加變量或引用:
TransformData myObj = new TransformData();
myObj.position = //populate it here
myObj.rotation = //populate it here
myObj.scale = //populate it here
然后將其添加到列表中:
matrices1.Add(myObj);
如果在其他地方已經創建了該對象,則只需添加保存它的變量。
您在Stack Overflow上看到的與所討論的行類似的內容可能是:
matrices1.Add(new TransformData(){
position = //something,
rotation = //something,
scale = //something
});
這將創建新對象並將其添加到列表中。
你應該給它一個構造函數
// In order to be able to actually save that list this class has to be
// Serializable!
// Another nice side effect is that from now you can also adjust the values
// from the Inspector of the MonoBehaviour using such an instance or list
[Serializable]
public class TransformData
{
public Vector3 position;
public Quaternion rotation;
public Vector3 scale;
// Serialization always needs a default constructor
// doesn't have to do anything but can
public TransformData()
{
// scale should be 1,1,1 by default
// The other two can keep their default values
scale = Vector3.one;
}
public TransformData(Vector3 pos, Quaternion rot, Vector3 scal)
{
position = pos;
rotation = rot;
scale = scal;
}
}
然后做例如
// this is a vector not a float!
public Vector3 scaleVector = Vector3.one;
private void Start()
{
// I guess you wanted to add the data for some transform component
matrices1.Add(new TransformData(transform.position, transform.rotation, Vector3.one));
}
請注意,不能在方法外部使用Add
。
如果您想直接添加一些元素來初始化列表,則可以像
public List<TransformData> matrices1 = new List<TransformData>()
{
new TransformData(somePosition, someRotation, scaleVector);
};
如果 somePosition
和someRotation
也是例如您從Inspector獲得的值。 您不能在方法外部使用transform.position
等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.