Unity中替换模型的方法

制作项目时,经常会遇到替换人物模型的情况。为了方便,会采用显示和隐藏的方法。

但是当模型处于隐藏状态时,是无法找到的。

如果在Unity界面直接拖拽,虽然简单,但是当模型有改动需要再次替换的时候,又要重新拖拽一次,这会产生不小的工作量。

所以怎样通过代码找到模型就变成了解决问题的关键。

本文采用的方式是将模型统一放到空物体下,通过遍历的方式查找,再按需显示与隐藏。

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

public class Show : MonoBehaviour
{
    public Transform models;
   //summary 
   //模型替换
    public void showmodels(string name)
    {
        for (int i = 0; i < models.childCount; i++)
        {
            string modelname = GameObject.Find("Models").transform.GetChild(i).name;
            if (name == modelname)
            {
                models.GetChild(i).gameObject.SetActive(true);
                print(1);
            }
            else
            {
                models.GetChild(i).gameObject.SetActive(false);
            }
        }
    }
    // Start is called before the first frame update
    void Start()
    {
        models = GameObject.Find("Models").transform;
    }

若需显示多组模型,判断结束后按需显示。

 public void showmodels(string name)
    {
        for (int i = 0; i < models.childCount; i++)
        {
            string modelname = GameObject.Find("Models").transform.GetChild(i).name;
            if (name == modelname)
            {
                models.GetChild(i).gameObject.SetActive(true);
                print(1);
            }
            else
            {
                models.GetChild(i).gameObject.SetActive(false);
            }
        }
        models.Find("Cube").gameObject.SetActive(true);
    }

 


版权声明:本文为m0_54876601原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。