[英]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.