我对如何获取transform
对象的Enum
组件感到困惑。<{1}}组件是角色的骨骼。
使用GetBoneTransform
方法可以在Mecanim中轻松完成,所以当我不使用Mecanim
骨架时,我正在尝试编写一个函数来执行此操作。
以下是我的课程:
using UnityEngine;
using System.Collections;
public class GetTransform : MonoBehaviour
{
public enum BradBodyBones
{
JtPelvis = 0,
JtSkullA = 1,
JtSkullB = 2
}
void Start()
{
GetEnumTransform(JtPelvis); // This is the error line.
}
Transform GetEnumTransform(BradBodyBones boneName)
{
Transform tmpTransf;
GameObject enumObject = GameObject.Find(boneName.ToString());
tmpTransf = enumObject.transform;
return tmpTransf;
}
}
我知道这是错误的,因为JtPelvis
中的Start()
突出显示为红色,所以有人可以帮助我了解我该如何做到这一点吗?
换句话说,我如何实现类似于GetBoneTransform
枚举HumanBodyBones
的函数,当我在Start()
中使用它时,它给了我transform
的{{1}}?
基本上,我JtPelvis
的{{1}}应该返回该骨骼的GetEnumTransform(JtPelvis);
组件......
答案 0 :(得分:1)
你想要的是dictionary。使用枚举也更安全,因为您不会受到小错字的影响。然后,您必须进行适当的转换。例如,您的代码可能如下所示:
public class GetTransform : MonoBehaviour
{
public Transform headBone;
public Transform pelvisBone;
private Dictionary<myBonesBody,Transform> mEnumToBone;
void Start() {
mEnumToBone=new Dictionary<myBonesBody,Transform>();
mEnumToBone.Add(myBodyBone.skull,headBone); //Continue as such.
mEnumToBone[myBodyBone.skull]; //This is how you retrieve the value from the dictionary
}
public Transform GetTransform(myBonesBody part) {
return mEnumToBone[part];
}
}
答案 1 :(得分:1)
如果您的枚举列表在应用程序生命周期中无法更改,则最好使用枚举。我使用enum,例如,奇数/偶数,骰子数(1到6),周(周日到周六)等等。
在您的情况下,我正在改变架构。 类似的东西:
public class GetTransform : MonoBehaviour
{
Transform GetEnumTransform(BodyBones bodyBone)
{
return bodyBone.GetBodyBoneTransform();
}
}
class BodyBones
{
protected Transform _transform;
public BodyBones(Transform transform)
{
_transform = transform;
}
public Transform GetBodyBoneTransform()
{
return _transform;
}
}
class JtPelvis : BodyBones
{
public JtPelvis (Transform transform): base(transform)
}
class JtSkull : BodyBones
{
public JtSkull (Transform transform): base(transform)
}
答案 2 :(得分:0)
using UnityEngine;
using System.Collections;
public class GetTransform : MonoBehaviour
{
public enum BradBodyBones
{
JtPelvis = 0,
JtSkullA = 1,
JtSkullB = 2
// more here later ...
}
void Start()
{
// Debug.Log(BradBodyBones.JtSkullA); // JtSkullA which is a string!
// Debug.Log((int)(BradBodyBones.JtSkullA)); // 1 which is an integer!
// GameObject Pelvis = GameObject.Find("JtPelvis");
// Debug.Log(Pelvis.transform.position.x);
Debug.Log(GetEnumTransform(BradBodyBones.JtPelvis).position.x);
Debug.Log(GetEnumTransform(BradBodyBones.JtPelvis).position.y);
Debug.Log(GetEnumTransform(BradBodyBones.JtPelvis).position.z);
}
Transform GetEnumTransform(BradBodyBones boneName)
{
Transform tmpTransf;
GameObject enumObject = GameObject.Find(boneName.ToString()); // GameObject.Find(boneName.ToString()).GetComponentInChildren<BradBodyBones>();
tmpTransf = enumObject.transform;
return tmpTransf;
}
}
非常感谢ehh + Caramiriel + PearsonArtPhoto帮助我解决这个问题。