您的位置:首页 > 移动开发 > Unity3D

【Unity】动态生成物体,设置一个物体为另外一个物体的父类

2016-12-20 17:47 746 查看
如何设置一个物体为另外一个物体的子类

如何动态生成物体

可以参考:unity动态创建游戏物体并放置到一个父类游戏物体下 

Unity通过脚本实现给一个物体添加子物体

Unity实例化对象的公共方法

Unity中添加组件的几种方法

GameObject father = GameObject.Instantiate(oklable.gameObject.Vector3.zero,Quaternion.identity) as GameObject;

go.transform.parent = lableParent.transorm;//父类为

生成的主要代码如下:

GameObject go_specialfoot1 = GameObject.Instantiate (BombArry [0],targetPos+new Vector2(0,1), Quaternion.identity) as GameObject;

首先在代码开头声明

public GameObject[] BombArry;//一个公共物体组,把物体放入其中

第二个就是位置的坐标

第三个Quaternion.identity是旋转的角度

参考资料上有这些方法的来源

DBtest.CS文件内容如下

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DBtest : MonoBehaviour {

public GameObject prefab;
// Use this for initialization
void Start()
{
if (prefab)
{
//动态生成物体的一种方式
 GameObject player = (GameObject)GameObject.Instantiate(prefab, this.transform.position, Quaternion.identity);
//这个IF判断语句用于添加名字为LTLeg的组件,可以不用添加
if (!player.GetComponent<LTLeg>())
{
player.AddComponent<LTLeg>();
}
}

}
}

LTLeg.cs文件内容如下

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DragonBones;

public class LTLeg : MonoBehaviour {
// Use this for initialization
void Start () {
//遍历这个LTLeg.cs文件所挂的物体的子物体
 foreach (var spriterender in GetComponentsInChildren<Renderer>())
{
//如果这个物体的MeshRenderer组件(简称Renderer)名字为Body,则执行判断语句
 if (spriterender.name == "Body")
{

//动态生成物体的一种方式,具体内容参考参考资料
 GameObject left_hand = Resources.Load("123/Armature_Left_Hand") as GameObject;
GameObject prefab_left_Instance = Instantiate(left_hand);
//遍历找到的这个“身体”为动态加载的“左手”的父类
 prefab_left_Instance.transform.parent = spriterender.transform;
//调整这个“左手”的大小,强制类型转换
  prefab_left_Instance.transform.localScale = new Vector3((float)0.1, (float)0.1, 1);
//获得“左手”物体的“UnityArmatureComponent”的组件,播放DragonBones的animation动画名字为“handsup”
 prefab_left_Instance.GetComponent<UnityArmatureComponent>().animation.Play("handsup");

GameObject right_hand = Resources.Load("123/Armature_Right_Hand") as GameObject;
GameObject prefab_right_Instance = Instantiate(right_hand);
prefab_right_Instance.transform.parent = spriterender.transform;
prefab_right_Instance.transform.localScale = new Vector3((float)0.1, (float)0.1, 1);
prefab_right_Instance.GetComponent<UnityArmatureComponent>().animation.Play("handsup");

}
}
}
}




注意在DragonBones中骨架左手的根骨骼要对齐,红色圆圈内

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: