private void Start()
 {
     playerT = transform;
     skinnedMeshRenderers = new List <SkinnedMeshRenderer>();
     playerRenderers      = new List <MeshRenderer>();
     playerRenderers.AddRange(playerObject?.GetComponentsInChildren <MeshRenderer>());
     skinnedMeshRenderers.AddRange(playerObject?.GetComponentsInChildren <SkinnedMeshRenderer>());
 }
Esempio n. 2
0
    public CarryItem TakeItem()
    {
        var item = ItemSlot?.GetComponentsInChildren <CarryItem>().FirstOrDefault();

        item.transform.SetParent(null);
        return(item);
    }
Esempio n. 3
0
 protected virtual void Awake()
 {
     Loading.LoadingSpinner = this;
     _container             = transform.GetChild(0)?.gameObject;
     _spinner = _container?.GetComponentsInChildren <Image>(true).First(i => i.gameObject != _container.gameObject);
     _text    = GetComponentInChildren <Text>(true);
 }
Esempio n. 4
0
    private void Awake()
    {
        saveSlotDisplayers = saveSlotContainer?.GetComponentsInChildren <UISaveSlotDisplayer>();

        buttonTabRight?.onClick.AddListener(OnSwitchTabRight);
        buttonTabLeft?.onClick.AddListener(OnSwitchTabLeft);
    }
Esempio n. 5
0
    void Update()
    {
        //a new hand object was added!
        if (interactionManager.transform.childCount != lastChildCount)
        {
            handColliders.Clear();
            GameObject leftHandObject     = GameObject.Find(interactionManager.name + "/Left Interaction Hand Contact Bones");
            GameObject rightHandObject    = GameObject.Find(interactionManager.name + "/Right Interaction Hand Contact Bones");
            Collider[] leftHandColliders  = leftHandObject?.GetComponentsInChildren <Collider>() ?? null;
            Collider[] rightHandColliders = rightHandObject?.GetComponentsInChildren <Collider>() ?? null;
            switch (hand)
            {
            case Hand.Both:
                if (leftHandColliders != null)
                {
                    handColliders.AddRange(leftHandColliders);
                }
                if (rightHandColliders != null)
                {
                    handColliders.AddRange(rightHandColliders);
                }
                break;

            case Hand.Left:
                if (leftHandColliders != null)
                {
                    handColliders.AddRange(leftHandColliders);
                }
                break;

            case Hand.Right:
                if (rightHandColliders != null)
                {
                    handColliders.AddRange(rightHandColliders);
                }
                break;
            }
            lastChildCount = interactionManager.transform.childCount;
        }

        if (handColliders.Count > 0)
        {
            Bounds bounds = new Bounds();                                   // Creates a new bounds at (0,0,0) with a size of (0,0,0)

            bounds.center = handColliders[0].gameObject.transform.position; // Center the bounds to the first point so we can start encapsulating
            foreach (var col in handColliders)
            {
                bounds.Encapsulate(col.bounds);
            }
            BoxCollider thisCollider = gameObject.GetComponent <BoxCollider>();
            thisCollider.size   = bounds.size;
            thisCollider.center = bounds.center;
        }
    }
Esempio n. 6
0
        /// <summary>
        /// Creates an <see cref="InstanceTrailData"/> object
        /// with the correct trail transforms
        /// </summary>
        /// <param name="saberObject">The saber gameobject that the <see cref="CustomTrail"/> component is on</param>
        /// <param name="trailModel">The <see cref="TrailModel"/> to use</param>
        public void InitializeTrailData(GameObject saberObject, TrailModel trailModel)
        {
            if (trailModel is null)
            {
                return;
            }

            var trails = saberObject?.GetComponentsInChildren <CustomTrail>();

            if (trails is null || trails.Length < 1)
            {
                return;
            }

            var saberTrail = trails[0];

            if (trails.Length > 1)
            {
                SecondaryTrails = new List <CustomTrail>();
                for (int i = 1; i < trails.Length; i++)
                {
                    SecondaryTrails.Add(trails[i]);
                }
            }

            // if trail comes from the preset save system
            // the model comes without the material assigned
            // so we assign
            if (trailModel.Material is null)
            {
                trailModel.Material = new MaterialDescriptor(saberTrail.TrailMaterial);

                // set texture wrap mode
                if (trailModel.Material.Material.TryGetMainTexture(out var tex))
                {
                    trailModel.OriginalTextureWrapMode = tex.wrapMode;
                }
            }

            Transform pointStart = saberTrail.PointStart;
            Transform pointEnd   = saberTrail.PointEnd;

            // Correction for sabers that have the transforms set up the other way around
            bool isTrailReversed = pointStart.localPosition.z > pointEnd.localPosition.z;

            if (isTrailReversed)
            {
                pointStart = saberTrail.PointEnd;
                pointEnd   = saberTrail.PointStart;
            }

            InstanceTrailData = new InstanceTrailData(trailModel, pointStart, pointEnd, isTrailReversed);
        }
Esempio n. 7
0
        /// <summary>
        /// Instantiate prefab at position, set parent, parent lossyScale
        /// </summary>
        /// <param name="prefab"></param>
        /// <param name="parent"></param>
        /// <param name="position"></param>
        /// <param name="destroyTime"></param>
        internal static GameObject InstantiatePrefab(GameObject prefab, Transform parent, Vector3 position, int sortingLayer, int sortingOrder)
        {
            GameObject g = InstantiatePrefab(prefab, parent, position, 0);

            SpriteRenderer[] sRs = g?.GetComponentsInChildren <SpriteRenderer>();
            if (sRs != null)
            {
                foreach (var sR in sRs)
                {
                    sR.sortingLayerID = sortingLayer;
                    sR.sortingOrder   = sortingOrder;
                }
            }
            return(g);
        }
Esempio n. 8
0
    private void OnEnable()
    {
        var rends = MeshObject?.GetComponentsInChildren <MeshRenderer>() ?? new MeshRenderer[0];

        foreach (var rend in rends)
        {
            foreach (var mat in rend.materials)
            {
                if (mat.shader.name == "Stencil/Read")
                {
                    mat.SetInt("_StencilRef", 3);
                }
            }
        }
    }
Esempio n. 9
0
    public GroundPlatform(string data, GameObject[] prefabs, LandPlatformGenerator lpg)
    {
        resetPointer();

        List <Tile> tileList = new List <Tile>();

        ushort tileCount = getNext(data);

        for (ushort i = 0; i < tileCount; i++)
        {
            ushort x        = getNext(data);
            ushort y        = getNext(data);
            ushort type     = getNext(data);
            byte   rotation = (byte)getNext(data);
            ushort dirCount = getNext(data);

            var dirs = new Dictionary <Vector2Int, byte>();

            for (int j = 0; j < dirCount; j++)
            {
                dirs.Add(new Vector2Int(getNext(data), getNext(data)), (byte)getNext(data));
            }

            Vector2Int pos = new Vector2Int(x, y);

            GameObject tileObj = null;
            if (prefabs != null)
            {
                tileObj = UnityEngine.Object.Instantiate(prefabs[type], LandPlatformGenerator.TileToWorldPos(pos), Quaternion.identity);
                tileObj.GetComponent <SpriteRenderer>().color = lpg.color;
                tileObj.transform.localEulerAngles            = new Vector3(0, 0, 90 * rotation);
                tileObj.transform.SetParent(lpg.transform);
            }


            tileList.Add(
                new Tile()
            {
                pos        = pos,
                type       = (byte)type,
                rotation   = (byte)rotation,
                directions = dirs,
                colliders  = tileObj?.GetComponentsInChildren <Collider2D>()
            });
        }
        tiles = tileList;
    }
Esempio n. 10
0
        private IEnumerator OpenColladaRoutine()
        {
            yield return(FileExplorer.Instance.OpenFile("ќткрыть файл", filters: "dae"));

            if (FileExplorer.Instance.LastResult == null)
            {
                yield break;
            }

            _model?.GetComponentsInChildren <MeshFilter>().ToList().ForEach(filter => Destroy(filter.sharedMesh));
            Destroy(_model);

            Resources.UnloadUnusedAssets();

            (_model, _wires) = Parser.Load(FileExplorer.Instance.LastResult);

            _calculateButton.interactable = true;
        }
 private void Heal(object[] param)
 {
     if (param == null)
     {
         return;
     }
     entityStat.Heal((float)param[0]);
     if (param.Length > 1)
     {
         ActionEventHandler.Invoke(SkillCastEvent.UIChangeEvent, param, null);
         // Play effect here
         if (!healParticleEffect)
         {
             healParticleEffect = Instantiate(listSkills[(int)param[2]].parcicleSkillEffect, transform.position + Vector3.up * -0.59f + Vector3.right * 0.14f, Quaternion.identity);
             healParticleEffect.transform.SetParent(this.transform);
             healParticleSystem = healParticleEffect?.GetComponentsInChildren <ParticleSystem>();
         }
         foreach (var item in healParticleSystem)
         {
             item.Play();
         }
     }
 }
Esempio n. 12
0
        /// <summary>
        /// Find all mesh filters within a GameObject
        /// </summary>
        /// <param name="gameObject">GameObject</param>
        /// <param name="includeInactive">Include inactive filter</param>
        public static IEnumerable <MeshFilter> GetGameObjectMeshFilter(GameObject gameObject, bool includeInactive = false)
        {
            IEnumerable <MeshFilter> filters = gameObject?.GetComponentsInChildren <MeshFilter>(includeInactive);

            return(filters ?? Enumerable.Empty <MeshFilter>());
        }
            // Runtime Constructor, uses CelestialBody
            public ScaledVersionLoader(CelestialBody body)
            {
                // Get the scaled version object
                scaledVersion = body.scaledBody;
                owner = body;

                // Figure out what kind of body we are
                if (scaledVersion.GetComponentsInChildren<SunShaderController>(true).Length > 0)
                    type = BodyType.Star;
                else if (owner.atmosphere)
                    type = BodyType.Atmospheric;
                else
                    type = BodyType.Vacuum;
            }
Esempio n. 14
0
 public static ParticleSystem[] GetParticles(GameObject go)
 {
     return(go?.GetComponentsInChildren <ParticleSystem>(true));
 }
Esempio n. 15
0
    void CombineMeshesMultiDraw(GameObject[] meshes)
    {
        GameObject skeleton = gameObject;
        //Vector3 position = skeleton.transform.position;

        //________________________________________
        // Instantiate Meshes and Collect Pieces
        //________________________________________
        List <CombineInstance> combineInstances = new List <CombineInstance> ();
        List <Material>        materials        = new List <Material> ();
        List <Transform>       bones            = new List <Transform> ();

        Transform[] transforms = skeleton.GetComponentsInChildren <Transform> ();

        //bool should_unload_unused_items = false;
        int to_combine_len = _toCombine.Length;

        for (int i = 0; i < to_combine_len; ++i)
        {
            SkinnedMeshRenderer[] smrs = _toCombine[i].CombinedMesh.GetComponents <SkinnedMeshRenderer> ();

            if (smrs == null)
            {
                continue;
            }

            SkinnedMeshRenderer smr = smrs [0];

            if (smr == null)
            {
                continue;
            }

            materials.Add(smr.materials [0]);

            // Add mesh if needed
            if (smr.sharedMesh != null)
            {
                for (int sub = 0; sub < smr.sharedMesh.subMeshCount; sub++)
                {
                    CombineInstance ci = new CombineInstance();
                    ci.mesh         = smr.sharedMesh;
                    ci.subMeshIndex = sub;
                    combineInstances.Add(ci);
                }

                foreach (Transform bone in smr.bones)
                {
                    foreach (Transform transform in transforms)
                    {
                        if (transform.name != bone.name)
                        {
                            continue;
                        }
                        bones.Add(transform);
                        break;
                    }
                }
            }

            GameObject.Destroy(_toCombine[i].CombinedMesh);
        }

        // Combine all meshes into one
        SkinnedMeshRenderer combined_mesh = skeleton.AddComponent <SkinnedMeshRenderer> ();

        SetRequiredCustomizationMeshProperties(combined_mesh);
        combined_mesh.sharedMesh = new Mesh();
        combined_mesh.sharedMesh.CombineMeshes(combineInstances.ToArray(), false, false);
        combined_mesh.bones     = bones.ToArray();
        combined_mesh.rootBone  = gameObject.transform;
        combined_mesh.materials = materials.ToArray();


        //bomber.m_customizations.m_combined_mesh = combined_mesh;

        /*if (combined_mesh.materials.Length > 2) {
         *  bomber.m_customizations.m_body_material = combined_mesh.materials [0];
         *  SetDefaultMaterialLightingCubeMap (bomber.m_customizations.m_body_material);
         *
         *  bomber.m_customizations.m_face_material = combined_mesh.materials [1];
         *  SetDefaultMaterialLightingCubeMap (bomber.m_customizations.m_face_material);
         *
         *  bomber.m_customizations.m_hair_material = combined_mesh.materials [2];
         *  SetDefaultMaterialLightingCubeMap (bomber.m_customizations.m_hair_material);
         * }  else if (combined_mesh.materials.Length > 1) {
         *  bomber.m_customizations.m_body_material = combined_mesh.materials [0];
         *  SetDefaultMaterialLightingCubeMap (bomber.m_customizations.m_body_material);
         *
         *  bomber.m_customizations.m_face_material = combined_mesh.materials [1];
         *  SetDefaultMaterialLightingCubeMap (bomber.m_customizations.m_face_material);
         *
         *  bomber.m_customizations.m_hair_material = combined_mesh.materials [1];
         *  SetDefaultMaterialLightingCubeMap (bomber.m_customizations.m_hair_material);
         * }  else if (combined_mesh.materials.Length > 0) {
         *  bomber.m_customizations.m_body_material = combined_mesh.materials [0];
         *  SetDefaultMaterialLightingCubeMap (bomber.m_customizations.m_body_material);
         *
         *  bomber.m_customizations.m_face_material = combined_mesh.materials [0];
         *  SetDefaultMaterialLightingCubeMap (bomber.m_customizations.m_face_material);
         *
         *  bomber.m_customizations.m_hair_material = combined_mesh.materials [0];
         *  SetDefaultMaterialLightingCubeMap (bomber.m_customizations.m_hair_material);
         * }
         * bomber.m_customizations.m_combined_material = bomber.m_customizations.m_body_material;*/


        // If necessary remove unused items from memory
        //if(should_unload_unused_items)
        //{
        //	RequestUnloadUnusedItem();
        //}
    }
Esempio n. 16
0
 private HowToMsg _HowToImage;     // 操作方法画像
 /*---------------------------------------------------------------------*/
 void Awake()
 {
     // 親オブジェクトからアイテムを取得する。
     _InfoItems = _Info.GetComponentsInChildren <InfoText> ();
     _MsgItems  = _Message.GetComponentsInChildren <MsgItem> ();
 }
        private void GeneratePie(bool update)
        {
            if (mFixPositionPie == null)
                update = false;
            if (update == false)
                ClearChart();
            else
                EnsureTextController();
            if (((IInternalPieData)Data).InternalDataSource == null)
                return;

            double[,] data = ((IInternalPieData)Data).InternalDataSource.getRawData();
            int rowCount = data.GetLength(0);
            int columnCount = data.GetLength(1);

            if (rowCount != 1) // row count for pie must be 1
                return;

            double total = 0.0;

            for (int i = 0; i < columnCount; ++i)
            {
                double val = Math.Max(data[0, i], 0);
                total += val;
            }

            float start = startAngle;
            if (clockWise)
                start -= angleSpan;
            float totalGaps = columnCount * spacingAngle;
            float spanWithoutGaps = angleSpan - totalGaps;

            if (spanWithoutGaps < 0f)
                spanWithoutGaps = 0f;

            if (mFixPositionPie == null)
            {
                mFixPositionPie = new GameObject("FixPositionPie", typeof(ChartItem));
                ChartCommon.HideObject(mFixPositionPie, hideHierarchy);
                mFixPositionPie.transform.SetParent(transform, false);
                if (IsCanvas)
                {
                    var rectTrans = mFixPositionPie.AddComponent<RectTransform>();
                    rectTrans.anchorMax = new Vector2(0.5f, 0.5f);
                    rectTrans.anchorMin = new Vector2(0.5f, 0.5f);
                    rectTrans.pivot = new Vector2(0.5f, 0.5f);
                    rectTrans.anchoredPosition = new Vector2(0.5f, 0.5f);
                }
            }
            
            for (int i = 0; i < columnCount; ++i)
            {
                object userData = ((IInternalPieData)Data).InternalDataSource.Columns[i].UserData;
                float radiusScale = 1f;
                float depthScale = 1f;
                float depthOffset = 0f;
                if (userData != null && userData is PieData.CategoryData)
                {
                    radiusScale = ((PieData.CategoryData)userData).RadiusScale;
                    depthScale = ((PieData.CategoryData)userData).DepthScale;
                    depthOffset = ((PieData.CategoryData)userData).DepthOffset;
                }
                if (radiusScale <= 0.001f)
                    radiusScale = 1f;
                if (depthScale <= 0.001f)
                    depthScale = 1f;
                                string name = ((IInternalPieData)Data).InternalDataSource.Columns[i].Name;
                double amount = Math.Max(data[0, i], 0);
                if (amount == 0f)
                    continue;
                float weight = (float)(amount / total);
                float currentSpan = spanWithoutGaps * weight;
                GameObject pieObject = null;
                IPieGenerator generator = null;
                PieObject dataObject;
                CanvasLines.LineSegement line;
                float modifiedRadius = Mathf.Max(radius * radiusScale, torusRadius);
              //  float modifiedDepth = d
                float lineAngle = start + currentSpan * 0.5f;
                if (mPies.TryGetValue(name, out dataObject))
                {
                    dataObject.StartAngle = start;
                    dataObject.AngleSpan = currentSpan;
                    generator = dataObject.Generator;
                    if (dataObject.ItemLabel)
                    {
                        Vector3 labelPos = AlignTextPosition(mItemLabels, dataObject, out line, modifiedRadius);
                        dataObject.ItemLabel.transform.localPosition = labelPos;
                        string toSet = ChartAdancedSettings.Instance.FormatFractionDigits(mItemLabels.FractionDigits, amount, CustomNumberFormat);
                        toSet = mItemLabels.TextFormat.Format(toSet, name, "");
                        ChartCommon.UpdateTextParams(dataObject.ItemLabel.UIText, toSet);
                        if (dataObject.ItemLine != null)
                        {
                            var lst = new List<CanvasLines.LineSegement>();
                            lst.Add(line);
                            dataObject.ItemLine.SetLines(lst);
                        }
                    }
                    if (dataObject.CategoryLabel != null)
                    {
                        Vector3 labelPos = AlignTextPosition(mCategoryLabels, dataObject, out line, modifiedRadius);
                        dataObject.CategoryLabel.transform.localPosition = labelPos;
                        if (dataObject.CategoryLine != null)
                        {
                            var lst = new List<CanvasLines.LineSegement>();
                            lst.Add(line);
                            dataObject.CategoryLine.SetLines(lst);
                        }
                    }
                    Vector2 add = ChartCommon.FromPolar(start + currentSpan * 0.5f, Extrusion);
                    dataObject.TopObject.transform.localPosition = new Vector3(add.x, add.y, 0f);
                }
                else
                {
                    GameObject topObject = new GameObject();
                    if (IsCanvas)
                        topObject.AddComponent<RectTransform>();
                    ChartCommon.HideObject(topObject, hideHierarchy);
                    topObject.AddComponent<ChartItem>();
                    topObject.transform.SetParent(mFixPositionPie.transform);
                    topObject.transform.localPosition = new Vector3();
                    topObject.transform.localRotation = Quaternion.identity;
                    topObject.transform.localScale = new Vector3(1f, 1f, 1f);

                    generator = PreparePieObject(out pieObject);

                    ChartCommon.EnsureComponent<ChartItem>(pieObject);
                    ChartMaterialController control = ChartCommon.EnsureComponent<ChartMaterialController>(pieObject);
                    control.Materials = Data.GetMaterial(name);
                    control.Refresh();
                    dataObject = new PieObject();
                    dataObject.StartAngle = start;
                    dataObject.AngleSpan = currentSpan;
                    dataObject.TopObject = topObject;
                    dataObject.Generator = generator;
                    dataObject.category = name;
                    var pieInfo = pieObject.AddComponent<PieInfo>();
                    pieInfo.pieObject = dataObject;
                    pieObject.transform.SetParent(topObject.transform);
                    Vector2 add = ChartCommon.FromPolar(start + currentSpan * 0.5f, Extrusion);
                    pieObject.transform.localPosition = new Vector3(0f, 0f, 0f);
                    pieObject.transform.localScale = new Vector3(1f, 1f, 1f);
                    pieObject.transform.localRotation = Quaternion.identity;
                    mPies.Add(name,dataObject);

                    topObject.transform.localPosition = new Vector3(add.x, add.y, 0f);
                    CharItemEffectController effect = ChartCommon.EnsureComponent<CharItemEffectController>(pieObject);
                    effect.WorkOnParent = true;
                    effect.InitialScale = false;

                    ChartItemEvents[] events = pieObject.GetComponentsInChildren<ChartItemEvents>();

                    for (int j = 0; j < events.Length; ++j)
                    {
                        if (events[j] == null)
                            continue;
                        InternalItemEvents comp = (InternalItemEvents)events[j];
                        comp.Parent = this;
                        comp.UserData = dataObject;
                    }

                    if (mItemLabels != null)
                    {
                        Vector3 labelPos = AlignTextPosition(mItemLabels, dataObject, out line, modifiedRadius);
                        if (line != null && IsUnderCanvas)
                            dataObject.ItemLine = AddLineRenderer(topObject, line);
                        string toSet = ChartAdancedSettings.Instance.FormatFractionDigits(mItemLabels.FractionDigits, amount, CustomNumberFormat);
                        toSet = mItemLabels.TextFormat.Format(toSet, name, "");
                        BillboardText billboard = ChartCommon.CreateBillboardText(null,mItemLabels.TextPrefab, topObject.transform, toSet, labelPos.x, labelPos.y, labelPos.z,lineAngle, topObject.transform, hideHierarchy, mItemLabels.FontSize, mItemLabels.FontSharpness);
                        dataObject.ItemLabel = billboard;
                        TextController.AddText(billboard);
                    }

                    if (mCategoryLabels != null)
                    {
                        Vector3 labelPos = AlignTextPosition(mCategoryLabels, dataObject, out line, modifiedRadius);
                        if (line != null && IsUnderCanvas)
                            dataObject.CategoryLine = AddLineRenderer(topObject, line);
                        string toSet = name;
                        toSet = mCategoryLabels.TextFormat.Format(toSet, "", "");
                        BillboardText billboard = ChartCommon.CreateBillboardText(null,mCategoryLabels.TextPrefab, topObject.transform, toSet, labelPos.x, labelPos.y, labelPos.z, lineAngle, topObject.transform, hideHierarchy, mCategoryLabels.FontSize, mCategoryLabels.FontSharpness);
                        dataObject.CategoryLabel = billboard;
                        TextController.AddText(billboard);
                    }

                }
                float maxDepth = Mathf.Max(OuterDepthLink, InnerDepthLink);
                float depthSize = maxDepth * depthScale;
                if (pieObject != null)
                {
                    float depthStart = (maxDepth - depthSize) * 0.5f;
                    pieObject.transform.localPosition = new Vector3(0f, 0f, depthStart - depthSize * depthOffset);
                }
                dataObject.Value =(float) data[0, i];
                generator.Generate(Mathf.Deg2Rad * start, Mathf.Deg2Rad * currentSpan, modifiedRadius, torusRadius, meshSegements, OuterDepthLink * depthScale,InnerDepthLink * depthScale);
                start += spacingAngle + currentSpan;
            }

        }
        /// <summary>
        /// Collect the bounds of the indicated types (MeshRenderer and/or Collider) on the object and all of its children, and returns bounds that are a sum of all of those.
        /// </summary>
        /// <param name="go">GameObject to start search from.</param>
        /// <param name="factorIn">The types of bounds to factor in.</param>
        /// <param name="includeChildren">Whether to search all children for bounds.</param>
        /// <returns></returns>
        public static Bounds CollectMyBounds(GameObject go, BoundsType factorIn, out int numOfBoundsFound, bool includeChildren = true, bool includeInactive = false)
        {
            // if we are ignoring inactive, an inactive parent is already a null. Quit here.
            if (!go.activeInHierarchy && !!includeInactive)
            {
                numOfBoundsFound = 0;
                return(new Bounds());
            }

            bool bothtype = factorIn == BoundsType.Both;
            bool rendtype = bothtype || factorIn == BoundsType.MeshRenderer;
            bool colltype = bothtype || factorIn == BoundsType.Collider;

            // Clear the reusables so they have counts of zero
            meshFilters.Clear();
            meshRenderers.Clear();
            colliders.Clear();
            spriteRenderers.Clear();
            validColliders.Clear();
#if !DISABLE_PHYSICS_2D
            validColliders2D.Clear();
#endif
            int myBoundsCount = 0;

            // Find all of the MeshRenderers and Colliders (as specified)
            if (rendtype)
            {
                if (go.activeInHierarchy)
                {
                    if (includeChildren)
                    {
                        go.GetComponentsInChildren(includeInactive, meshFilters);
                        go.GetComponentsInChildren(includeInactive, spriteRenderers);
                    }
                    else
                    {
                        go.GetComponents(meshFilters);
                        go.GetComponents(spriteRenderers);
                    }
                }
            }

            if (colltype)
            {
                if (go.activeInHierarchy)
                {
                    if (includeChildren)
                    {
                        go.GetComponentsInChildren(includeInactive, colliders);
#if !DISABLE_PHYSICS_2D
                        go.GetComponentsInChildren(includeInactive, colliders2D);
#endif
                    }
                    else
                    {
                        go.GetComponents(colliders);
#if !DISABLE_PHYSICS_2D
                        go.GetComponents(colliders2D);
#endif
                    }
                }
            }

            // Add any MeshRenderer attached to the found MeshFilters to their own list.
            // We want the MeshRenderer for its bounds, but only if there is a MeshFilter, otherwise there is a risk of a 0,0,0
            for (int i = 0; i < meshFilters.Count; i++)
            {
                MeshRenderer mr = meshFilters[i].GetComponent <MeshRenderer>();

                if (mr && (mr.enabled || includeInactive))
                {
                    meshRenderers.Add(mr);
                }
            }

            // Collect only the valid colliders (ignore inactive if not includeInactive)
            for (int i = 0; i < colliders.Count; i++)
            {
                if (colliders[i].enabled || includeInactive)
                {
                    if (colliders[i])
                    {
                        validColliders.Add(colliders[i]);
                    }
                }
            }

#if !DISABLE_PHYSICS_2D
            // Collect only the valid colliders (ignore inactive if not includeInactive)
            for (int i = 0; i < colliders2D.Count; i++)
            {
                if (colliders2D[i] && colliders2D[i].enabled || includeInactive)
                {
                    // 2d colliders arrive as null but present in scene changes, test for null
                    if (colliders2D[i])
                    {
                        validColliders2D.Add(colliders2D[i]);
                    }
                }
            }
#endif
            // Make sure we found some bounds objects, or we need to quit.
            numOfBoundsFound =
                meshRenderers.Count +
                spriteRenderers.Count +
                validColliders.Count
#if !DISABLE_PHYSICS_2D
                + validColliders2D.Count
#endif
            ;
            // No values means no bounds will be found, and this will break things if we try to use it.
            if (numOfBoundsFound == 0)
            {
                return(new Bounds());
            }

            // Get a starting bounds. We need this because the default of centered 0,0,0 will break things if the map is
            // offset and doesn't encapsulte the world origin.
            Bounds compositeBounds;

            if (meshRenderers.Count > 0)
            {
                compositeBounds = meshRenderers[0].bounds;
            }

            else if (validColliders.Count > 0)
            {
                compositeBounds = validColliders[0].bounds;
            }

#if !DISABLE_PHYSICS_2D
            else if (validColliders2D.Count > 0 && validColliders2D[0])
            {
                compositeBounds = validColliders2D[0].bounds;
            }
#endif
            else if (spriteRenderers.Count > 0)
            {
                compositeBounds = spriteRenderers[0].bounds;
            }
            /// nothing found, return an empty bounds
            else
            {
                return(new Bounds());
            }

            for (int i = 0; i < spriteRenderers.Count; i++)
            {
                myBoundsCount++;
                compositeBounds.Encapsulate(spriteRenderers[i].bounds);
            }

            // Encapsulate all outer found bounds into that. We will be adding the root to itself, but no biggy, this only runs once.
            for (int i = 0; i < meshRenderers.Count; i++)
            {
                myBoundsCount++;
                compositeBounds.Encapsulate(meshRenderers[i].bounds);
            }

            for (int i = 0; i < validColliders.Count; i++)
            {
                myBoundsCount++;
                compositeBounds.Encapsulate(validColliders[i].bounds);
            }
#if !DISABLE_PHYSICS_2D
            for (int i = 0; i < validColliders2D.Count; i++)
            {
                myBoundsCount++;
                if (validColliders2D[i])
                {
                    compositeBounds.Encapsulate(validColliders2D[i].bounds);
                }
            }
#endif
            return(compositeBounds);
        }
Esempio n. 19
0
            void Start()
            {
                if (Nyan.forever)
                {
                    TimingManager.LateUpdateAdd(TimingManager.TimingStage.BetterLateThanNever, UpdateBox);

                    GameObject cube = GalaxyCubeControl.Instance?.gameObject?.GetComponentsInChildren <Renderer>()?.FirstOrDefault(r => r.name == "XP")?.gameObject?.transform?.parent?.gameObject;

                    nyanMenu = nyanMenu ?? Instantiate(cube);

                    if (nyanMenu == null)
                    {
                        return;
                    }

                    nyanMenu.transform.SetParent(cube.transform.parent);
                    nyanMenu.transform.position   = cube.transform.position;
                    nyanMenu.transform.localScale = cube.transform.localScale * 0.9f;

                    frames = Nyan.nyanSkyBox;
                    none.SetPixel(1, 1, new Color(0, 0, 0, 0));
                    none.Apply();

                    // Set Textures
                    Renderer[] renderers = nyanMenu?.GetComponentsInChildren <Renderer>();

                    for (int i = 0; i < renderers?.Length; i++)
                    {
                        string   name     = renderers[i]?.name;
                        Material material = renderers[i]?.material;
                        if (material == null)
                        {
                            continue;
                        }

                        material.shader = Shader.Find("Unlit/Transparent");

                        if (name == "XP")
                        {
                            XP = material;
                        }
                        else if (name == "XN")
                        {
                            material.SetTexture(none);
                        }
                        else if (name == "YP")
                        {
                            material.SetTexture(none);
                        }
                        else if (name == "YN")
                        {
                            material.SetTexture(none);
                        }
                        else if (name == "ZN")
                        {
                            material.SetTexture(none);
                        }
                        else if (name == "ZP")
                        {
                            material.SetTexture(none);
                        }
                    }
                }
            }
Esempio n. 20
0
		public static void CreateFileForResult (List<Core_Voxel.Result> resultList, Shader[] shaders, string[] shaderKeywords, Vector2[] shaderRemaps, float scale, Vector3 pivot, ReplacementMode replacementMode) {

			var diffuseShader = shaders[0];

			for (int index = 0; index < resultList.Count; index++) {

				var result = resultList[index];
				bool lod = result.VoxelModels.Length > 1;
				bool isRig = !lod && result.IsRigged;
				int realLodNum = result.IsRigged ? 1 : result.VoxelModels.Length;

				var root = new GameObject(result.FileName).transform;
				var meshs = new List<Mesh>();
				var materialsMap = new Dictionary<Texture2D, Material[]>();
				Transform[] lodRoots = new Transform[realLodNum];
				for (int lodIndex = 0; lodIndex < realLodNum; lodIndex++) {

					var voxelModel = result.VoxelModels[lodIndex];
					var model = CreateModelFrom(voxelModel.RootNode, voxelModel.Materials, root, pivot, ref meshs, ref materialsMap, isRig, result.WithAvatar, shaders, shaderKeywords, shaderRemaps, scale);
					model.name = string.Format("Root{0}", lod ? "_lod " + lodIndex.ToString() : "");
					lodRoots[lodIndex] = model;

					// Rig			 
					if (isRig) {

						Vector3 halfModelSize = voxelModel.ModelSize[0] * 0.5f;
						halfModelSize.x = Mathf.Floor(halfModelSize.x);
						halfModelSize.y = Mathf.Floor(halfModelSize.y);
						halfModelSize.z = Mathf.Floor(halfModelSize.z);

						var skinMR = model.GetComponent<SkinnedMeshRenderer>();
						if (skinMR) {
							Vector3 rootBoneOffset = halfModelSize * scale;
							var boneTFList = new List<Transform>();
							if (voxelModel.RootBones != null) {
								for (int i = 0; i < voxelModel.RootBones.Length; i++) {
									var boneTF = CreateBoneTransform(voxelModel.RootBones[i], model, scale, ref boneTFList);
									if (boneTF) {
										boneTF.localPosition -= rootBoneOffset;
									}
								}
							}

							skinMR.bones = boneTFList.ToArray();
							skinMR.rootBone = model;

							// Bind Poses
							var poses = new Matrix4x4[boneTFList.Count];
							for (int i = 0; i < boneTFList.Count; i++) {
								poses[i] = boneTFList[i].worldToLocalMatrix * model.localToWorldMatrix;
							}
							skinMR.sharedMesh.bindposes = poses;

						}

						// Foot Fix
						model.localPosition = (halfModelSize - voxelModel.FootPoints[lodIndex]) * scale;

					}

				}



				// Lod
				if (lod) {
					LODGroup group = root.gameObject.AddComponent<LODGroup>();
					LOD[] lods = new LOD[realLodNum];
					for (int i = 0; i < realLodNum; i++) {
						lods[i] = new LOD(
							i == realLodNum - 1 ? 0.001f : GetLodRant(result.VoxelModels[i].MaxModelBounds, i),
							lodRoots[i].GetComponentsInChildren<MeshRenderer>(true)
						);
					}
					group.SetLODs(lods);
					group.RecalculateBounds();
				} else if (!isRig && root.childCount > 0) {
					var newRoot = root.GetChild(0);
					newRoot.name = root.name;
					root = newRoot;
				}



				// File
				string path = Util.CombinePaths(
					result.ExportRoot,
					result.ExportSubRoot,
					result.FileName + result.Extension
				);
				path = Util.FixPath(path);
				string parentPath = Util.GetParentPath(path);
				Util.CreateFolder(parentPath);
				List<Object> oldSubObjs = new List<Object>();

				if (result.Extension == ".prefab") {

					Object prefab;

					if (Util.FileExists(path)) {

						// Get Prefab
						prefab = AssetDatabase.LoadAssetAtPath<Object>(path);
						if (prefab as GameObject) {
							var group = (prefab as GameObject).GetComponent<LODGroup>();
							if (group) {
								Object.DestroyImmediate(group, true);
							}
						}

						// Old Sub Objs
						oldSubObjs.AddRange(AssetDatabase.LoadAllAssetRepresentationsAtPath(path));

						if (replacementMode == ReplacementMode.DeleteOldObjects) {
							foreach (Object o in oldSubObjs) {
								Object.DestroyImmediate(o, true);
							}
							oldSubObjs.Clear();
						}

					} else {
#if UNITY_4 || UNITY_5 || UNITY_2017 || UNITY_2018_1 || UNITY_2018_2
						prefab = PrefabUtility.CreateEmptyPrefab(path);
#else   // 2018.3+
						var tempObject = new GameObject();
						prefab = PrefabUtility.SaveAsPrefabAsset(tempObject, path);
						Object.DestroyImmediate(tempObject, false);
#endif
					}

					if (prefab) {

						// Get Old Sub Objects
						var oldSubMeshs = new List<Mesh>();
						var oldSubMaterials = new List<Material>();
						var oldSubTextures = new List<Texture2D>();
						var new2old = new Dictionary<Object, Object>();

						for (int i = 0; i < oldSubObjs.Count; i++) {
							var obj = oldSubObjs[i];
							if (obj is Mesh) {
								oldSubMeshs.Add(obj as Mesh);
							} else if (obj is Material) {
								oldSubMaterials.Add(obj as Material);
							} else if (obj is Texture2D) {
								oldSubTextures.Add(obj as Texture2D);
							}
						}


						if (replacementMode == ReplacementMode.ReplaceByName) {
							// Replace by Name
							// Delete Non-Replaced Old Sub / Create New2Old Map
							for (int i = 0; i < oldSubObjs.Count; i++) {

								var oldObj = oldSubObjs[i];
								bool deleteFlag = true;
								string name = oldObj.name;

								if (oldObj is Mesh) {
									// Mesh
									for (int j = 0; j < meshs.Count; j++) {
										if (new2old.ContainsKey(meshs[j])) { continue; }
										if (name == meshs[j].name) {
											new2old.Add(meshs[j], oldObj);
											deleteFlag = false;
											break;
										}
									}
								} else if (oldObj is Material) {
									// Material
									foreach (var textureMat in materialsMap) {
										var mats = textureMat.Value;
										for (int j = 0; j < mats.Length; j++) {
											if (new2old.ContainsKey(mats[j])) { continue; }
											if (mats[j].name == name) {
												new2old.Add(mats[j], oldObj);
												deleteFlag = false;
												break;
											}
										}
									}
								} else if (oldObj is Texture2D) {
									// Texture
									foreach (var textureMat in materialsMap) {
										if (new2old.ContainsKey(textureMat.Key)) { continue; }
										if (name == textureMat.Key.name) {
											new2old.Add(textureMat.Key, oldObj);
											deleteFlag = false;
											break;
										}
									}
								}

								if (deleteFlag) {
									Object.DestroyImmediate(oldObj, true);
									oldSubObjs.RemoveAt(i);
									i--;
								}
							}

							// Create Meshs
							for (int i = 0; i < meshs.Count; i++) {
								var mesh = meshs[i];
								if (new2old.ContainsKey(mesh)) {
									Util.OverrideMesh(new2old[mesh] as Mesh, mesh);
								} else {
									AssetDatabase.AddObjectToAsset(meshs[i], path);
								}
							}

							// Create Textures
							foreach (var textureMat in materialsMap) {
								if (new2old.ContainsKey(textureMat.Key)) {
									Util.OverrideTexture(new2old[textureMat.Key] as Texture2D, textureMat.Key);
								} else {
									AssetDatabase.AddObjectToAsset(textureMat.Key, path);
								}
							}

							// Create Materials
							foreach (var textureMat in materialsMap) {
								var mats = textureMat.Value;
								for (int i = 0; i < mats.Length; i++) {
									var mat = mats[i];
									if (new2old.ContainsKey(mat)) {
										Util.OverrideMaterial(new2old[mat] as Material, mat);
									} else {
										AssetDatabase.AddObjectToAsset(mat, path);
									}
								}
							}

						} else {

							// Just Create New
							// Create Meshs
							for (int i = 0; i < meshs.Count; i++) {
								AssetDatabase.AddObjectToAsset(meshs[i], path);
							}

							// Create Textures
							foreach (var textureMat in materialsMap) {
								AssetDatabase.AddObjectToAsset(textureMat.Key, path);
							}

							// Create Materials
							foreach (var textureMat in materialsMap) {
								var mats = textureMat.Value;
								for (int i = 0; i < mats.Length; i++) {
									AssetDatabase.AddObjectToAsset(mats[i], path);
								}
							}

						}

						// Create Avatar
						if (isRig && result.WithAvatar) {
							var avatar = GetVoxelAvatarInRoot(root);
							if (avatar) {
								avatar.name = result.FileName;
								AssetDatabase.AddObjectToAsset(avatar, path);

								// Animator
								var ani = root.GetComponent<Animator>();
								if (!ani) {
									ani = root.gameObject.AddComponent<Animator>();
								}
								ani.avatar = avatar;

							} else {
								Debug.LogWarning("[Voxel to Unity] Failed to get avatar from the prefab. Use \"+ Human Bones\" button in rig editor to create bones and don\'t change their names and layout.");
							}
						}

						// Replace to Old Instance
						var mrs = root.GetComponentsInChildren<MeshRenderer>(true);
						var srs = root.GetComponentsInChildren<SkinnedMeshRenderer>(true);
						var mfs = root.GetComponentsInChildren<MeshFilter>(true);
						for (int i = 0; i < mrs.Length; i++) {
							var mr = mrs[i];
							if (mr.sharedMaterial && new2old.ContainsKey(mr.sharedMaterial)) {
								var mat = new2old[mr.sharedMaterial] as Material;
								mr.sharedMaterial = mat;
								if (mat.mainTexture && new2old.ContainsKey(mat.mainTexture)) {
									var texture = new2old[mat.mainTexture] as Texture2D;
									mat.mainTexture = texture;
								}
							}
						}
						for (int i = 0; i < mfs.Length; i++) {
							var mf = mfs[i];
							if (mf.sharedMesh && new2old.ContainsKey(mf.sharedMesh)) {
								mf.sharedMesh = new2old[mf.sharedMesh] as Mesh;
							}
						}
						for (int i = 0; i < srs.Length; i++) {
							var sr = srs[i];
							if (sr.sharedMesh && new2old.ContainsKey(sr.sharedMesh)) {
								sr.sharedMesh = new2old[sr.sharedMesh] as Mesh;
							}
							if (sr.sharedMaterial && new2old.ContainsKey(sr.sharedMaterial)) {
								var mat = new2old[sr.sharedMaterial] as Material;
								sr.sharedMaterial = mat;
								if (mat.mainTexture && new2old.ContainsKey(mat.mainTexture)) {
									var texture = new2old[mat.mainTexture] as Texture2D;
									mat.mainTexture = texture;
								}
							}
						}


						// Prefab
#if UNITY_4 || UNITY_5 || UNITY_2017 || UNITY_2018_1 || UNITY_2018_2
						PrefabUtility.ReplacePrefab(root.gameObject, prefab, ReplacePrefabOptions.ReplaceNameBased);
#else  // 2018.3+
						prefab = PrefabUtility.SaveAsPrefabAsset(root.gameObject, path);
#endif

					}

				} else { // Obj

					string objFolderPath = Util.CombinePaths(parentPath, result.FileName);
					string textureFolderPath = Util.CombinePaths(objFolderPath, "Textures");
					Util.CreateFolder(objFolderPath);

					VoxelPostprocessor.TheShader = diffuseShader;

					// Assets
					var model = result.VoxelModels[0];
					for (int modelIndex = 0; modelIndex < model.Meshs.Length; modelIndex++) {

						string modelIndexedName = GetIndexedName(result.FileName, modelIndex, model.Meshs.Length);
						string modelPathRoot = Util.CombinePaths(objFolderPath, modelIndexedName);

						// Texture
						string texturePath = Util.CombinePaths(textureFolderPath, modelIndexedName + ".png");
						texturePath = Util.FixPath(texturePath);
						var texture = model.Textures[modelIndex];
						Util.ByteToFile(texture.EncodeToPNG(), texturePath);
						VoxelPostprocessor.AddTexture(texturePath);

						// Meshs
						var uMesh = model.Meshs[modelIndex];
						for (int i = 0; i < uMesh.Count; i++) {
							uMesh[i].name = GetIndexedName("Mesh", i, uMesh.Count);
							string obj = Util.GetObj(uMesh[i]);
							string objPath = GetIndexedName(modelPathRoot, i, uMesh.Count) + ".obj";

							bool hasObjBefore = Util.FileExists(objPath);

							Util.Write(obj, objPath);
							VoxelPostprocessor.AddObj(objPath, texturePath);

							if (hasObjBefore) {
								AssetDatabase.ImportAsset(Util.FixedRelativePath(objPath), ImportAssetOptions.ForceUpdate);
							}

						}

					}

				}


				// Delete Objects
				if (root.parent) {
					Object.DestroyImmediate(root.parent.gameObject, false);
				} else {
					Object.DestroyImmediate(root.gameObject, false);
				}

			}
			AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
			AssetDatabase.SaveAssets();
			Resources.UnloadUnusedAssets();

			EditorApplication.delayCall += VoxelPostprocessor.ClearAsset;

		}
        public void ConfigureColliders(GameObject meshGameObject, bool hasCollision, bool filterByColliderName = false, IDCLEntity entity = null, int colliderLayer = -1)
        {
            if (meshGameObject == null)
            {
                return;
            }

            if (entity != null)
            {
                entity.meshesInfo.colliders.Clear();
            }

            if (colliderLayer == -1)
            {
                colliderLayer = DCL.Configuration.PhysicsLayers.defaultLayer;
            }

            Collider collider;
            int      onClickLayer = PhysicsLayers.onPointerEventLayer; // meshes can have a child collider for the OnClick that should be ignored

            MeshFilter[] meshFilters = meshGameObject.GetComponentsInChildren <MeshFilter>(true);

            for (int i = 0; i < meshFilters.Length; i++)
            {
                if (meshFilters[i].gameObject.layer == onClickLayer)
                {
                    continue;
                }

                if (filterByColliderName)
                {
                    if (!meshFilters[i].transform.parent.name.ToLower().Contains("_collider"))
                    {
                        continue;
                    }

                    // we remove the Renderer of the '_collider' object, as its true renderer is in another castle
                    Object.Destroy(meshFilters[i].GetComponent <Renderer>());
                }

                collider = meshFilters[i].GetComponent <Collider>();

                //HACK(Pravus): Hack to bring back compatibility with old builder scenes that have withCollision = false in the JS code.
                //              Remove when we fix this changing the property name or something similar.
                bool shouldCreateCollider = hasCollision || filterByColliderName;

                if (shouldCreateCollider)
                {
                    if (collider == null)
                    {
                        collider = meshFilters[i].gameObject.AddComponent <MeshCollider>();
                    }

                    if (collider is MeshCollider)
                    {
                        ((MeshCollider)collider).sharedMesh = meshFilters[i].sharedMesh;
                    }

                    if (entity != null)
                    {
                        AddOrUpdateEntityCollider(entity, collider);
                    }
                }

                if (collider != null)
                {
                    collider.gameObject.layer = colliderLayer;
                    collider.enabled          = shouldCreateCollider;

                    if (entity != null)
                    {
                        entity.meshesInfo.colliders.Add(collider);
                    }
                }
            }
        }
Esempio n. 22
0
    private void Refresh(int toRefreshIndex = -1, string equipmentDataId = null)
    {
        //Step -1
        int[] refreshIndices = new int[_toCombine.Length];
        for (int i = 0; i < refreshIndices.Length; i++)
        {
            refreshIndices [i] = toRefreshIndex == -1 || i == toRefreshIndex ? 1 : 0;
        }

        for (int ii = 0; ii < _toCombine.Length; ++ii)
        {
            if (_toCombine[ii].GameObject != null)
            {
                CombinedMeshExtender cme = _toCombine[ii].GameObject.GetComponent <CombinedMeshExtender>();
                if (cme != null)
                {
                    for (int jj = 0; jj < cme.rowEntries.Length; ++jj)
                    {
                        int rowIndex = System.Array.FindIndex(_toCombine, arg => arg.Name == cme.rowEntries[jj].combineRowName);
                        _toCombine[rowIndex].GameObject = cme.rowEntries[jj].mesh;
                        refreshIndices [rowIndex]       = 1;
                    }
                }
            }
        }
        //Step 0
        //Remove any preview nodes
        if (_toDelete != null)
        {
            Transform deleteTransform = gameObject.transform.Find(_toDelete);
            deleteTransform.gameObject.SetActive(false);
        }

        //Step 1
        // Remove old mesh components
        GameObject          skeleton = gameObject;
        SkinnedMeshRenderer old_smr  = skeleton.GetComponent("SkinnedMeshRenderer") as SkinnedMeshRenderer;

        if (old_smr != null)
        {
            DestroyImmediate(old_smr);
        }

        //Step 2
        //first we need to try and download each of the Assetbundles for this dude

        //Step 3
        //Grab each piece and reskin it to our skeleton
        //Vector3 position = skeleton.transform.position;

        //List<CombineInstance> combineInstances = new List<CombineInstance> ();
        //List<Material> materials = new List<Material> ();
        List <Transform> bones = new List <Transform> ();

        Transform[] transforms = skeleton.GetComponentsInChildren <Transform> ();

        //bool should_unload_unused_items = false;
        for (int i = 0; i < _toCombine.Length; ++i)
        {
            bones = new List <Transform> ();

            if (refreshIndices[i] == 0)
            {
                continue;
            }
            if (_toCombine[i].GameObject == null)
            {
                continue;
            }
            if (_toCombine[i].CombinedMesh != null)
            {
                Destroy(_toCombine[i].CombinedMesh);
            }

            GameObject customization_object = (GameObject)GameObject.Instantiate(_toCombine[i].GameObject);
            customization_object.transform.parent = gameObject.transform;
            customization_object.SetActive(true);

            if (customization_object == null)
            {
                EB.Debug.LogWarning("CombineMesh: customization_object is null. type = {0}", _toCombine[i].Name);
                continue;
            }

            SkinnedMeshRenderer[] smrs = customization_object.GetComponentsInChildren <SkinnedMeshRenderer> ();

            if (smrs == null || smrs.Length == 0)
            {
                continue;
            }


            for (int j = 0; j < smrs.Length; j++)
            {
                if (_toCombine[i].OverrideMaterial.Length > 0)
                {
                    if (smrs[j].materials.Length == _toCombine[i].OverrideMaterial.Length)
                    {
                        smrs[j].materials = _toCombine[i].OverrideMaterial;
                    }
                    else
                    {
                        smrs[j].material = _toCombine[i].OverrideMaterial[0];
                    }
                }

                smrs[j].receiveShadows = false;
            }

            //set customizatioin color;
            ColorCustomization customization = customization_object.GetComponent <ColorCustomization>();


            if (customization != null)
            {
                //now we use this component to check whether current gameobject is hero instance, not a good way.
                if (GetComponent <HeroEquipmentDataLookup>() != null)
                {
                    customization.m_UseHeroColorPreset = true;
                    int skinColorIndex = 0;
                    DataLookupsCache.Instance.SearchIntByID("heroStats.skinColorIndex", out skinColorIndex);
                    customization.m_SkinColorIndex = skinColorIndex - 1;

                    int hairColorIndex = 0;
                    DataLookupsCache.Instance.SearchIntByID("heroStats.hairColorIndex", out hairColorIndex);
                    customization.m_HairColorIndex = hairColorIndex - 1;

                    int eyeColorIndex = 0;
                    DataLookupsCache.Instance.SearchIntByID("heroStats.eyesColorIndex", out eyeColorIndex);
                    customization.m_EyeColorIndex = eyeColorIndex - 1;

                    if (!string.IsNullOrEmpty(equipmentDataId))
                    {
                        int colorIndex = 0;
                        DataLookupsCache.Instance.SearchIntByID(string.Format("{0}.equipmentColorIndex", equipmentDataId), out colorIndex);
                        customization.m_EquipmentColorIndex = colorIndex - 1;
                    }
                }
                customization.ApplyColor();
            }

            SkinnedMeshRenderer smr  = smrs [0];
            Transform           root = null;

            //reskin this thing to the new skeleton
            foreach (Transform bone in smr.bones)
            {
                foreach (Transform transform in transforms)
                {
                    if (transform.name == smr.rootBone.name)
                    {
                        root = transform;
                    }

                    if (transform.name != bone.name)
                    {
                        continue;
                    }
                    bones.Add(transform);
                    break;
                }
            }
            smr.bones                  = bones.ToArray();
            smr.rootBone               = root;
            smr.transform.parent       = gameObject.transform;
            _toCombine[i].CombinedMesh = smr.gameObject;
            GameObject.Destroy(customization_object);
        }

        //Step 4
        //Combine meshes using the same material/shader combo into one
        if (_CombineTo1Draw)
        {
            CombineMeshes1Draw(meshes);
        }
        else
        {
            //CombineMeshesMultiDraw(meshes);
        }
        gameObject.SendMessage("ForceUpdateColorScale", SendMessageOptions.DontRequireReceiver);

        /*
         * //Raise character mesh update event.
         * if(_meshUpdateEvent == null)
         * {
         *  _meshUpdateEvent = new CharacterMeshUpdateEvent(gameObject);
         * }
         * EventManager.instance.Raise(_meshUpdateEvent);
         */
    }
Esempio n. 23
0
    /*void SetBomberCustomizations_1DrawCall (Bomber bomber, int avatar_id,
     *                                          uint body_id, List<DataObjects.InventoryItemColor> body_color_map,
     *                                          uint face_id, List<DataObjects.InventoryItemColor> face_color_map,
     *                                          uint hair_id, List<DataObjects.InventoryItemColor> hair_color_map)*/
    void CombineMeshes1Draw(GameObject[] meshes)
    {
        UnityEngine.Profiling.Profiler.BeginSample("SetBomberCustomizations_1DrawCall");

        //int customization_material_renderer_id = avatar_id;

        //if (bomber.m_customizations == null) {
        //	bomber.m_customizations = new CustomizationManager ();
        //}

        //GameObject bomber_skeleton = bomber.m_body;
        GameObject bomber_skeleton = gameObject;
        //CustomizationLoader loader = GetCustomizationLoader (bomber.m_gender);
        //Vector3 position = bomber_skeleton.transform.position;

        // Remove old mesh components
        SkinnedMeshRenderer old_smr = bomber_skeleton.GetComponent("SkinnedMeshRenderer") as SkinnedMeshRenderer;

        if (old_smr != null)
        {
            DestroyImmediate(old_smr);
        }

        //  Put Customization IDs into an array for easy iteration
        //uint[] customization_ids = new uint[3];
        //customization_ids [CustomizationLoader.CUSTOMIZATION_TYPE_BODY] = body_id;
        //customization_ids [CustomizationLoader.CUSTOMIZATION_TYPE_FACE] = face_id;
        //customization_ids [CustomizationLoader.CUSTOMIZATION_TYPE_HAIR] = hair_id;

        // Test whether you need a face or not
        //bool needs_face = (!BomberFactory.ShouldHairRemoveFace (hair_id) && !bomber.m_is_zombie) || bomber.m_is_king;
        //bool needs_face = true;

        //________________________________________
        // Instantiate Meshes and Collect Pieces
        //________________________________________
        //List<Material> materials = new List<Material>();
        Transform[] skeleton_bones = bomber_skeleton.GetComponentsInChildren <Transform> ();

        // Lists for all components of combined mesh
        UnityEngine.Profiling.Profiler.BeginSample("SetBomberCustomizations_1DrawCall - List Alocation");
        //List<Vector3> combined_verts = new List<Vector3> ();
        //List<Vector3> combined_normals = new List<Vector3> ();
        //List<Vector2> combined_uvs = new List<Vector2> ();
        //List<int> combined_tris = new List<int> ();
        //List<Transform> combined_bones = new List<Transform> ();
        //List<BoneWeight> combined_bone_weights = new List<BoneWeight> ();
        //List<Matrix4x4> combined_bind_poses = new List<Matrix4x4> ();
        UnityEngine.Profiling.Profiler.EndSample();

        // Load and stash the 3 customization pieces so we can know sizes of everything
        int combined_vert_count        = 0;
        int combined_normal_count      = 0;
        int combined_uv_count          = 0;
        int combined_tri_count         = 0;
        int combined_bone_count        = 0;
        int combined_bone_weight_count = 0;
        int combined_bind_pose_count   = 0;

        GameObject[] customization_objects      = new GameObject[meshes.Length];
        bool         should_unload_unused_items = false;

        for (int i = 0; i < meshes.Length; ++i)
        {
            UnityEngine.Profiling.Profiler.BeginSample("SetBomberCustomizations_1DrawCall - Load and Count");

            // Instantiate
            //uint customization_id = customization_ids [i];
            bool customization_was_removed_from_cache = false;
            customization_objects [i]   = meshes[i];
            should_unload_unused_items |= customization_was_removed_from_cache; // should free memory if customization was removed
            if (customization_objects [i] == null)
            {
                //Debug.LogWarning ("BomberFactory::SetBomberCustomizations: customization_object is null. type = " + i.ToString () + ", customization_id = " + customization_id.ToString ());
                continue;
            }

            // check if it should be added
            //if (i == CustomizationLoader.CUSTOMIZATION_TYPE_FACE && needs_face == false) {
            //	continue;
            //}

            // Get skinned mesh renderer
            SkinnedMeshRenderer[] smrs = customization_objects [i].GetComponentsInChildren <SkinnedMeshRenderer> ();
            if (smrs == null || smrs [0] == null || smrs [0].sharedMesh == null)
            {
                //GameObject.Destroy (customization_objects [i]);
                customization_objects [i] = null;
                continue;
            }
            SkinnedMeshRenderer smr = smrs [0];
            Mesh shared_mesh        = smr.sharedMesh;

            // Count the mesh properties
            combined_vert_count        += shared_mesh.vertices.Length;
            combined_normal_count      += shared_mesh.normals.Length;
            combined_uv_count          += shared_mesh.uv.Length;
            combined_tri_count         += shared_mesh.triangles.Length;
            combined_bone_weight_count += shared_mesh.boneWeights.Length;
            combined_bind_pose_count   += shared_mesh.bindposes.Length;

            //combined_bone_count += smr.bones.Length;
            Transform[] shared_mesh_bones     = smr.bones;
            int         bones_length          = shared_mesh_bones.Length;
            int         skeleton_bones_length = skeleton_bones.Length;
            for (int j = 0; j < bones_length; ++j)
            {
                Transform bone = shared_mesh_bones [j];
                for (int k = 0; k < skeleton_bones_length; ++k)
                {
                    Transform skeleton_bone = skeleton_bones [k];
                    if (skeleton_bone.name != bone.name)
                    {
                        continue;
                    }
                    combined_bone_count++;
                    break;
                }
            }


            UnityEngine.Profiling.Profiler.EndSample();
        }

        // Store materials for all customizations
        Material[] customization_materials = new Material[meshes.Length];

        // Adjust parameters as we loop through meshes
        //const float total_texture_size = 768.0f;
        //const float body_texture_size = 512.0f;
        //const float face_texture_size = 256.0f;
        //const float hair_texture_size = 256.0f;
        //Vector2[] uv_offsets = {
        //	new Vector2 (0, 0),
        //	new Vector2 (body_texture_size / total_texture_size, 0),
        //	new Vector2 (0, body_texture_size / total_texture_size)
        //} ;
        //float[] uv_scales = {
        //	body_texture_size / total_texture_size,
        //	face_texture_size / total_texture_size,
        //	hair_texture_size / total_texture_size
        //} ;

        // Build combined mesh
        UnityEngine.Profiling.Profiler.BeginSample("SetBomberCustomizations_1DrawCall - PreAlloc");
        Vector3[]    combined_verts        = new Vector3[combined_vert_count];
        Vector3[]    combined_normals      = new Vector3[combined_normal_count];
        Vector2[]    combined_uvs          = new Vector2[combined_uv_count];
        int[]        combined_tris         = new int[combined_tri_count];
        Transform[]  combined_bones        = new Transform[combined_bone_count];
        BoneWeight[] combined_bone_weights = new BoneWeight[combined_bone_weight_count];
        Matrix4x4[]  combined_bind_poses   = new Matrix4x4[combined_bind_pose_count];
        int          normal_id_offset      = 0;
        int          vert_id_offset        = 0;
        int          uv_id_offset          = 0;
        int          tri_id_offset         = 0;
        int          bone_id_offset        = 0;
        int          bone_weight_id_offset = 0;
        int          bind_pose_id_offset   = 0;

        UnityEngine.Profiling.Profiler.EndSample();
        for (int i = 0; i < customization_objects.Length; ++i)
        {
            //uint customization_id = customization_ids[i];

            if (customization_objects [i] == null)
            {
                continue;
            }

            SkinnedMeshRenderer[] smrs = customization_objects[i].GetComponentsInChildren <SkinnedMeshRenderer> ();
            SkinnedMeshRenderer   smr  = smrs [0];
            Mesh shared_mesh           = smr.sharedMesh;

            UnityEngine.Profiling.Profiler.BeginSample("SetBomberCustomizations_1DrawCall - Set Material");
            // Add the material to array to be put in avatar customization structure
            customization_materials[i] = smr.sharedMaterials[0];
            //mmcmanus
            //customization_materials [i] = BomberCustomizationMaterialRenderManager.m_Instance.m_Renderers[customization_material_renderer_id].m_RenderPlanes [i].sharedMaterial;
            // Send the material to the combined material renderer
            Material shared_mesh_material = smr.sharedMaterial;
            customization_materials [i].SetTexture("_MainTex", shared_mesh_material.GetTexture("_MainTex"));
            customization_materials [i].SetTexture("_TintTex", shared_mesh_material.GetTexture("_TintTex"));
            customization_materials [i].SetColor("_Tint1", shared_mesh_material.GetColor("_Tint1"));
            customization_materials [i].SetColor("_Tint2", shared_mesh_material.GetColor("_Tint2"));
            customization_materials [i].SetColor("_Tint3", shared_mesh_material.GetColor("_Tint3"));
            customization_materials [i].SetColor("_Tint4", shared_mesh_material.GetColor("_Tint4"));
            UnityEngine.Profiling.Profiler.EndSample();

            // Store some data in custmization
            UnityEngine.Profiling.Profiler.BeginSample("SetBomberCustomizations_1DrawCall - Loop End");

            /*switch (i) {
             * case CustomizationLoader.CUSTOMIZATION_TYPE_BODY:
             * {
             *  if (bomber.m_customizations.m_body_customization == null) {
             *      bomber.m_customizations.m_body_customization = new CustomizationBodyData ();
             *  }
             *  CustomizationBody body_source = customization_objects [i].GetComponent<CustomizationBody> ();
             *  if (body_source != null) {
             *      bomber.m_customizations.m_body_customization.Copy (body_source);
             *      bomber.m_customizations.m_body_id = customization_id;
             *  }
             *  break;
             * }
             * case CustomizationLoader.CUSTOMIZATION_TYPE_FACE:
             * {
             *  if (bomber.m_customizations.m_face_customization == null) {
             *      bomber.m_customizations.m_face_customization = new CustomizationFaceData ();
             *  }
             *  CustomizationFace face_source = customization_objects [i].GetComponent<CustomizationFace> ();
             *  if (face_source != null) {
             *      bomber.m_customizations.m_face_customization.Copy (face_source);
             *      bomber.m_customizations.m_face_id = customization_id;
             *  }
             *  break;
             * }
             * case CustomizationLoader.CUSTOMIZATION_TYPE_HAIR:
             * {
             *  if (bomber.m_customizations.m_hair_customization == null) {
             *      bomber.m_customizations.m_hair_customization = new CustomizationHairData ();
             *  }
             *  CustomizationHair hair_source = customization_objects [i].GetComponent<CustomizationHair> ();
             *  if (hair_source != null) {
             *      bomber.m_customizations.m_hair_customization.Copy (hair_source);
             *      bomber.m_customizations.m_hair_id = customization_id;
             *  }
             *  break;
             * }
             * } */

            // check if it should be added
            // Note: This check must be done after the customization_materials and bomber.m_customizations are set up
            //       so that the ApplyColors call below has the information it needs to color the materials
            //if (i == CustomizationLoader.CUSTOMIZATION_TYPE_FACE && needs_face == false) {
            //	GameObject.Destroy (customization_objects [i]);
            //	customization_objects [i] = null;
            //	continue;
            //}

            // Collect Verts
            UnityEngine.Profiling.Profiler.BeginSample("SetBomberCustomizations_1DrawCall - PreVerts");
            Vector3[] shared_mesh_verts = shared_mesh.vertices;
            int       vert_length       = shared_mesh_verts.Length;
            UnityEngine.Profiling.Profiler.EndSample();
            UnityEngine.Profiling.Profiler.BeginSample("SetBomberCustomizations_1DrawCall - Verts");
            for (int j = 0; j < vert_length; ++j)
            {
                combined_verts [j + vert_id_offset].Set(shared_mesh_verts [j].x, shared_mesh_verts [j].y, shared_mesh_verts [j].z);
            }
            UnityEngine.Profiling.Profiler.EndSample();

            // Collect Normals
            UnityEngine.Profiling.Profiler.BeginSample("SetBomberCustomizations_1DrawCall - PreNormals");
            Vector3[] shared_mesh_normals = shared_mesh.normals;
            int       normal_length       = shared_mesh_normals.Length;
            UnityEngine.Profiling.Profiler.EndSample();
            UnityEngine.Profiling.Profiler.BeginSample("SetBomberCustomizations_1DrawCall - Normals");
            for (int j = 0; j < normal_length; ++j)
            {
                combined_normals [j + normal_id_offset].Set(shared_mesh_normals [j].x, shared_mesh_normals [j].y, shared_mesh_normals [j].z);
            }
            UnityEngine.Profiling.Profiler.EndSample();

            // Collect UVs
            UnityEngine.Profiling.Profiler.BeginSample("SetBomberCustomizations_1DrawCall - PreUVs");
            Vector2[] shared_mesh_uvs = shared_mesh.uv;
            int       uv_length       = shared_mesh_uvs.Length;
            UnityEngine.Profiling.Profiler.EndSample();
            UnityEngine.Profiling.Profiler.BeginSample("SetBomberCustomizations_1DrawCall - UVs");
            for (int j = 0; j < uv_length; ++j)
            {
                //mmcmanus
                //combined_uvs [j + uv_id_offset].Set (shared_mesh_uvs [j].x * uv_scales [i] + uv_offsets [i].x,
                //                                     shared_mesh_uvs [j].y * uv_scales [i] + uv_offsets [i].y);
            }
            UnityEngine.Profiling.Profiler.EndSample();

            // Collect Tris
            UnityEngine.Profiling.Profiler.BeginSample("SetBomberCustomizations_1DrawCall - PreTris");
            int[] shared_mesh_tris = shared_mesh.triangles;
            int   tris_length      = shared_mesh_tris.Length;
            UnityEngine.Profiling.Profiler.EndSample();
            UnityEngine.Profiling.Profiler.BeginSample("SetBomberCustomizations_1DrawCall - Tris");
            for (int j = 0; j < tris_length; ++j)
            {
                combined_tris [j + tri_id_offset] = shared_mesh_tris [j] + vert_id_offset;
            }
            UnityEngine.Profiling.Profiler.EndSample();

            // Collect Bones
            UnityEngine.Profiling.Profiler.BeginSample("SetBomberCustomizations_1DrawCall - PreBones");
            Transform[] shared_mesh_bones     = smr.bones;
            int         bones_length          = shared_mesh_bones.Length;
            int         skeleton_bones_length = skeleton_bones.Length;
            UnityEngine.Profiling.Profiler.EndSample();
            UnityEngine.Profiling.Profiler.BeginSample("SetBomberCustomizations_1DrawCall - Bones");
            for (int j = 0; j < bones_length; ++j)
            {
                Transform bone      = shared_mesh_bones [j];
                string    bone_name = bone.name;
                for (int k = 0; k < skeleton_bones_length; ++k)
                {
                    Transform skeleton_bone = skeleton_bones [k];
                    if (skeleton_bone.name != bone_name)
                    {
                        continue;
                    }
                    combined_bones [j + bone_id_offset] = skeleton_bone;
                    break;
                }
            }
            UnityEngine.Profiling.Profiler.EndSample();

            // CollectionBase Bone Weights
            UnityEngine.Profiling.Profiler.BeginSample("SetBomberCustomizations_1DrawCall - PreBoneWeights");
            BoneWeight[] shared_mesh_bone_weights = shared_mesh.boneWeights;
            int          bone_weights_length      = shared_mesh_bone_weights.Length;
            UnityEngine.Profiling.Profiler.EndSample();
            UnityEngine.Profiling.Profiler.BeginSample("SetBomberCustomizations_1DrawCall - Bone Weights");
            for (int j = 0; j < bone_weights_length; ++j)
            {
                combined_bone_weights [j + bone_weight_id_offset].boneIndex0 = shared_mesh_bone_weights [j].boneIndex0 + bone_id_offset;
                combined_bone_weights [j + bone_weight_id_offset].weight0    = shared_mesh_bone_weights [j].weight0;

                combined_bone_weights [j + bone_weight_id_offset].boneIndex1 = shared_mesh_bone_weights [j].boneIndex1 + bone_id_offset;
                combined_bone_weights [j + bone_weight_id_offset].weight1    = shared_mesh_bone_weights [j].weight1;

                combined_bone_weights [j + bone_weight_id_offset].boneIndex2 = shared_mesh_bone_weights [j].boneIndex2 + bone_id_offset;
                combined_bone_weights [j + bone_weight_id_offset].weight2    = shared_mesh_bone_weights [j].weight2;

                combined_bone_weights [j + bone_weight_id_offset].boneIndex3 = shared_mesh_bone_weights [j].boneIndex3 + bone_id_offset;
                combined_bone_weights [j + bone_weight_id_offset].weight3    = shared_mesh_bone_weights [j].weight3;
            }
            UnityEngine.Profiling.Profiler.EndSample();

            // Collect Bind Poses
            UnityEngine.Profiling.Profiler.BeginSample("SetBomberCustomizations_1DrawCall - PreBindPoses");
            Matrix4x4[] shared_mesh_bind_poses = shared_mesh.bindposes;
            int         bind_poses_length      = shared_mesh_bind_poses.Length;
            UnityEngine.Profiling.Profiler.EndSample();
            UnityEngine.Profiling.Profiler.BeginSample("SetBomberCustomizations_1DrawCall - BindPoses");
            for (int j = 0; j < bind_poses_length; ++j)
            {
                Matrix4x4 mm = shared_mesh_bind_poses [j];
                combined_bind_poses [j + bind_pose_id_offset].m00 = mm.m00;
                combined_bind_poses [j + bind_pose_id_offset].m01 = mm.m01;
                combined_bind_poses [j + bind_pose_id_offset].m02 = mm.m02;
                combined_bind_poses [j + bind_pose_id_offset].m03 = mm.m03;
                combined_bind_poses [j + bind_pose_id_offset].m10 = mm.m10;
                combined_bind_poses [j + bind_pose_id_offset].m11 = mm.m11;
                combined_bind_poses [j + bind_pose_id_offset].m12 = mm.m12;
                combined_bind_poses [j + bind_pose_id_offset].m13 = mm.m13;
                combined_bind_poses [j + bind_pose_id_offset].m20 = mm.m20;
                combined_bind_poses [j + bind_pose_id_offset].m21 = mm.m21;
                combined_bind_poses [j + bind_pose_id_offset].m22 = mm.m22;
                combined_bind_poses [j + bind_pose_id_offset].m23 = mm.m23;
                combined_bind_poses [j + bind_pose_id_offset].m30 = mm.m30;
                combined_bind_poses [j + bind_pose_id_offset].m31 = mm.m31;
                combined_bind_poses [j + bind_pose_id_offset].m32 = mm.m32;
                combined_bind_poses [j + bind_pose_id_offset].m33 = mm.m33;
            }
            UnityEngine.Profiling.Profiler.EndSample();

            //GameObject.Destroy (customization_objects [i]);
            customization_objects [i] = null;

            vert_id_offset        += vert_length;
            normal_id_offset      += normal_length;
            uv_id_offset          += uv_length;
            tri_id_offset         += tris_length;
            bone_id_offset        += bones_length;
            bone_weight_id_offset += bone_weights_length;
            bind_pose_id_offset   += bind_poses_length;
            UnityEngine.Profiling.Profiler.EndSample();
        }

        // Create a combined mesh
        UnityEngine.Profiling.Profiler.BeginSample("SetBomberCustomizations_1DrawCall - Combine Mesh");

        Mesh combined_mesh = new Mesh();

        combined_mesh.vertices    = combined_verts;
        combined_mesh.normals     = combined_normals;
        combined_mesh.uv          = combined_uvs;
        combined_mesh.triangles   = combined_tris;
        combined_mesh.boneWeights = combined_bone_weights;
        combined_mesh.bindposes   = combined_bind_poses;

        // Create a combined mesh renderer
        SkinnedMeshRenderer combined_mesh_renderer = bomber_skeleton.AddComponent <SkinnedMeshRenderer> ();

        combined_mesh_renderer.bones = combined_bones;
        //mmcmanus
        //combined_mesh_renderer.sharedMaterial = BomberCustomizationMaterialRenderManager.m_Instance.m_Renderers [customization_material_renderer_id].m_ResultingMaterial;
        combined_mesh_renderer.sharedMesh = combined_mesh;
        //SetDefaultMaterialLightingCubeMap (combined_mesh_renderer.sharedMaterial);
        SetRequiredCustomizationMeshProperties(combined_mesh_renderer);
        //bomber.m_customizations.m_combined_material = combined_mesh_renderer.sharedMaterial;

        // Store customization materials
        //bomber.m_customizations.m_combined_mesh = combined_mesh_renderer;
        UnityEngine.Profiling.Profiler.EndSample();

        /*if (customization_materials.Length > 2) {
         *  bomber.m_customizations.m_body_material = customization_materials [0];
         *  bomber.m_customizations.m_face_material = customization_materials [1];
         *  bomber.m_customizations.m_hair_material = customization_materials [2];
         * }  else if (customization_materials.Length > 1) {
         *  bomber.m_customizations.m_body_material = customization_materials [0];
         *  bomber.m_customizations.m_face_material = customization_materials [1];
         *  bomber.m_customizations.m_hair_material = customization_materials [1];
         * }  else if (customization_materials.Length > 0) {
         *  bomber.m_customizations.m_body_material = customization_materials [0];
         *  bomber.m_customizations.m_face_material = customization_materials [0];
         *  bomber.m_customizations.m_hair_material = customization_materials [0];
         * } */

        // Apply Colors
        //bomber.m_customizations.m_body_color_map = body_color_map;
        //bomber.m_customizations.m_face_color_map = face_color_map;
        //bomber.m_customizations.m_hair_color_map = hair_color_map;
        //bomber.m_customizations.ApplyColors ();

        // Actvate rendering for 1 frame
        //mmcmanus
        //BomberCustomizationMaterialRenderManager.m_Instance.m_Renderers[customization_material_renderer_id].Activate ();

        for (int i = 0; i < meshes.Length; i++)
        {
            GameObject.Destroy(meshes[i]);
        }

        // If necessary remove unused items from memory
        if (should_unload_unused_items)
        {
            //RequestUnloadUnusedItem();
        }

        UnityEngine.Profiling.Profiler.EndSample();
    }
Esempio n. 24
0
    public static void RefreshShader(GameObject obj)
    {
        List<Renderer> meshrs = new List<Renderer>(obj.GetComponentsInChildren<Renderer>(false));
        List<Material> mats = new List<Material>();
        //meshrs.Add(obj.GetComponent<Renderer>());
        for (int i = 0; i < meshrs.Count; i++)
        {
            Material[] mat = meshrs[i].sharedMaterials;
            if (mat == null) mat = meshrs[i].materials;
            if (mat != null)
            {
                mats.AddRange(mat);
            }
        }

        for (int i = 0; i < mats.Count; i++)
        {
            Material mat = mats[i];
            if (mat != null)
            {
                string shaderName = mat.shader.name;
                Shader newShader = Shader.Find(shaderName);
                if (newShader != null)
                {
                    mat.shader = newShader;
                }
            }
        }
    }
Esempio n. 25
0
            void Start()
            {
                if (Nyan.nyan)
                {
                    GameObject galaxy = GameObject.Find("MainMenuGalaxy");
                    nyanMenu = nyanMenu ?? Instantiate(galaxy);

                    Debug.Log("NyanMenuSkyBox.Start", "Applying to skybox = " + nyanMenu);
                    if (nyanMenu == null)
                    {
                        return;
                    }

                    nyanMenu.transform.SetParent(galaxy.transform.parent);
                    nyanMenu.transform.position   = galaxy.transform.position;
                    nyanMenu.transform.localScale = galaxy.transform.localScale * 0.9f;

                    frames = Nyan.nyanSkyBox;
                    none.SetPixel(1, 1, new Color(0, 0, 0, 0));
                    none.Apply();

                    // Set Textures
                    Renderer[] renderers = nyanMenu?.GetComponentsInChildren <Renderer>();

                    for (int i = 0; i < renderers?.Length; i++)
                    {
                        Debug.Log("NyanMenuSkyBox.Start", "Renderer = " + renderers[i]);
                        string   name     = renderers[i]?.name;
                        Material material = renderers[i]?.material;

                        if (material == null)
                        {
                            continue;
                        }

                        material.shader = Shader.Find("Unlit/Transparent");

                        if (name == "XP")
                        {
                            XP = material;
                        }
                        else if (name == "XN")
                        {
                            material.SetTexture(none);
                        }
                        else if (name == "YP")
                        {
                            material.SetTexture(none);
                        }
                        else if (name == "YN")
                        {
                            material.SetTexture(none);
                        }
                        else if (name == "ZN")
                        {
                            material.SetTexture(none);
                        }
                        else if (name == "ZP")
                        {
                            material.SetTexture(none);
                        }
                    }
                }
            }
Esempio n. 26
0
 public void Start()
 {
     inventoryLocations = inventoryLocationHolder.GetComponentsInChildren <Transform>();
     UpdateListItems();
 }
Esempio n. 27
0
        /// <summary>
        /// Find all renderers within a GameObject
        /// </summary>
        /// <param name="gameObject">GameObject</param>
        /// <param name="includeInactive">Include inactive renderers</param>
        public static IEnumerable <Renderer> GetGameObjectRenderer(GameObject gameObject, bool includeInactive = false)
        {
            IEnumerable <Renderer> renderers = gameObject?.GetComponentsInChildren <Renderer>(includeInactive);

            return(renderers ?? Enumerable.Empty <Renderer>());
        }
Esempio n. 28
0
        void OnGUI()
        {
            EditorGUILayout.Space();

            EditorGUI.BeginChangeCheck();
            m_Prefab = (GameObject)EditorGUILayout.ObjectField("Prefab", m_Prefab, typeof(GameObject), true);
            if (EditorGUI.EndChangeCheck())
            {
                var bounds = ObjectUtils.GetBounds(m_Prefab.transform);
                m_Spacing = bounds.size;
            }

            if (!m_Prefab)
            {
                GUILayout.Label("OR");
                m_PrimitiveType = (PrimitiveType)EditorGUILayout.EnumPopup("Primitive", m_PrimitiveType);
            }

            EditorGUILayout.Space();
            EditorGUILayout.Space();


            m_Number  = EditorGUILayout.Vector3Field("Number", m_Number);
            m_Spacing = EditorGUILayout.Vector3Field("Spacing", m_Spacing);

            EditorGUILayout.Space();
            EditorGUILayout.Space();

            m_UniqueMaterials = EditorGUILayout.Toggle("Unique Materials", m_UniqueMaterials);
            m_Material        = (Material)EditorGUILayout.ObjectField("Material", m_Material, typeof(Material), true);

            EditorGUILayout.Space();
            EditorGUILayout.Space();

            if (GUILayout.Button("Create"))
            {
                GameObject parent = new GameObject("Primitives");
                for (int i = 0; i < Mathf.FloorToInt(m_Number.x); i++)
                {
                    for (int j = 0; j < Mathf.FloorToInt(m_Number.y); j++)
                    {
                        for (int k = 0; k < Mathf.FloorToInt(m_Number.z); k++)
                        {
                            GameObject go = m_Prefab ? (GameObject)PrefabUtility.InstantiatePrefab(m_Prefab) : GameObject.CreatePrimitive(m_PrimitiveType);
                            go.name = string.Format("{0} {1}_{2}_{3}", m_Prefab ? m_Prefab.name : m_PrimitiveType.ToString(), i, j, k);
                            go.transform.position = Vector3.right * (m_Spacing.x * i + i) + Vector3.up * (m_Spacing.y * j + j) + Vector3.forward * (m_Spacing.z * k + k);
                            go.transform.parent   = parent.transform;

                            var meshRenderers = go.GetComponentsInChildren <MeshRenderer>();
                            foreach (var mr in meshRenderers)
                            {
                                var sharedMaterials = mr.sharedMaterials;
                                for (int m = 0; m < sharedMaterials.Length; m++)
                                {
                                    var material = m_Material ? m_Material : sharedMaterials[m];
                                    sharedMaterials[m] = m_UniqueMaterials ? Instantiate(material) : material;
                                }
                                mr.sharedMaterials = sharedMaterials;
                            }
                        }
                    }
                }
                Close();
            }
        }
Esempio n. 29
0
    void Update()
    {
        //Click For new point
        if (Input.GetMouseButton(0))
        {
            PaintPath();
        }
        if (move)
        {
            RayCastDown();
            if (speed != 0)
            {
                if (finalPath.Count != 0)
                {
                    FollowPath();
                }
                if (CheckTrafic())
                {
                    var truck = finalPath[index].GetComponent <InspectElement>().carInTheTile;
                    if (truck.transform.forward.x != 1 || truck.transform.forward.x != -1 &&
                        truck.transform.forward.z != 1 || truck.transform.forward.z != -1)
                    {
                        Debug.Log("Truck is Turning");
                        var   heading = car.transform.position - truck.transform.position;
                        float dot     = Vector3.Dot(heading, truck.transform.forward);
                        if (dot < 0)
                        {
                            if (truck.speed != 0)
                            {
                                speed = truck.speed - 0.1f;
                            }
                            else
                            {
                                speed = truck.speed;
                            }
                        }
                        else if (dot > 0)
                        {
                            Debug.Log("Car is front of so Frontal Collision");
                        }
                    }
                    else if (truck.transform.rotation.eulerAngles.y >= car.transform.rotation.eulerAngles.y + threesholdRotation_Traffic &&
                             truck.transform.rotation.eulerAngles.y >= car.transform.rotation.eulerAngles.y + threesholdRotation_Traffic)
                    {
                        Debug.Log("Frontal Collision");
                        Explosion?.transform.SetPositionAndRotation(car.transform.position, Quaternion.identity);
                        Explosion?.gameObject.SetActive(true);
                        Explosion?.GetComponentsInChildren <AudioSource>().ToList().ForEach(sound => sound.Play());
                    }
                }
                else
                {
                    speed = optimalSpeed;
                }
            }
            else
            if (!CheckTrafic())
            {
                speed = optimalSpeed;
            }
        }
        if (mainTarget == currentCube)
        {
            //Level is Over
            Time.timeScale = 0;
            manager.canvasGG.SetActive(true);
        }
        if (index == list_points.Count && move)
        {
            lastWaypointReached = true;
        }

        ChangeColorOnVisited();
    }
Esempio n. 30
0
 internal static void RegisterPrefab(GameObject prefab)
 {
   NetworkIdentity component = prefab.GetComponent<NetworkIdentity>();
   if ((bool) ((Object) component))
   {
     if (LogFilter.logDebug)
       Debug.Log((object) ("Registering prefab '" + prefab.name + "' as asset:" + (object) component.assetId));
     NetworkScene.s_GuidToPrefab[component.assetId] = prefab;
     if (prefab.GetComponentsInChildren<NetworkIdentity>().Length <= 1 || !LogFilter.logWarn)
       return;
     Debug.LogWarning((object) ("The prefab '" + prefab.name + "' has multiple NetworkIdentity components. There can only be one NetworkIdentity on a prefab, and it must be on the root object."));
   }
   else
   {
     if (!LogFilter.logError)
       return;
     Debug.LogError((object) ("Could not register '" + prefab.name + "' since it contains no NetworkIdentity component"));
   }
 }
Esempio n. 31
0
 public static Animator[] GetAnimators(GameObject go)
 {
     return(go?.GetComponentsInChildren <Animator>(true));
 }
Esempio n. 32
0
 public void UpdateObjectElements()
 {
     _meshRenderers        = _tooltippedObject?.GetComponentsInChildren <MeshRenderer>();
     _skinnedMeshRenderers = _tooltippedObject?.GetComponentsInChildren <SkinnedMeshRenderer>();
 }
    private void CreateStatusPanelObject(GameObject statusGameObject, Action cancelButtonAction)
    {
        spObject.GameObject = statusGameObject;


        Dictionary <string, Action <Text> > textDictonary = new Dictionary <string, Action <Text> >();

        textDictonary.Add(TEXT_NAME, spObject.SetNameText);
        textDictonary.Add(TEXT_CLASS_NAME, spObject.SetClassText);
        textDictonary.Add(TEXT_RANK, spObject.SetRankText);
        textDictonary.Add(TEXT_LV, spObject.SetLevelText);
        textDictonary.Add(TEXT_CHARGE, spObject.SetChargeText);
        textDictonary.Add(TEXT_MAXHP, spObject.SetMaxHpText);
        textDictonary.Add(TEXT_MAXHP_SUB, spObject.SetMaxHpSubText);
        textDictonary.Add(TEXT_HP, spObject.SetHpText);
        textDictonary.Add(TEXT_HP_SUB, spObject.SetHpSubText);
        textDictonary.Add(TEXT_BUFHP, spObject.SetBufHpText);
        textDictonary.Add(TEXT_BUFHP_SUB, spObject.SetBufHpSubText);
        textDictonary.Add(TEXT_ATK, spObject.SetAtkText);
        textDictonary.Add(TEXT_ATK_SUB, spObject.SetAtkSubText);
        textDictonary.Add(TEXT_SPD, spObject.SetSpdText);
        textDictonary.Add(TEXT_SPD_SUB, spObject.SetSpdSubText);
        textDictonary.Add(TEXT_MOVE, spObject.SetMoveText);
        textDictonary.Add(TEXT_VIEW, spObject.SetViewText);
        textDictonary.Add(TEXT_CARRY, spObject.SetCarryText);
        textDictonary.Add(TEXT_OVERVIEW_SUB, spObject.SetOverviewText);

        Transform[] childTransformList = statusGameObject.GetComponentsInChildren <Transform>();

        foreach (Transform ts in childTransformList)
        {
            GameObject go = ts.gameObject;

            // 存在したらディクショナリから取得
            bool exists = textDictonary.ContainsKey(go.name);
            if (exists)
            {
                Action <Text> text = textDictonary[go.name];
                text(go.GetComponent <Text>());
            }

            // 顔
            if (go.name == IMAGE_FACE)
            {
                spObject.FaceImage = go;
            }

            // 顔の色
            if (go.name == IMAGE_FACE_COLOR)
            {
                spObject.FaceColorImage = go;
            }

            // 背景の紙
            if (go.name == IMAGE_PAPER)
            {
                spObject.PaperGameObject = go;
            }

            // 背景の紙サブ
            if (go.name == IMAGE_PAPER_SUB)
            {
                spObject.PaperSubGameObject = go;
            }

            // Move
            if (go.name == IMAGE_MOVE)
            {
                spObject.MoveGameObject = go;
            }

            // View
            if (go.name == IMAGE_VIEW)
            {
                spObject.ViewGameObject = go;
            }

            // Carry
            if (go.name == IMAGE_CARRY)
            {
                spObject.CarryGameObject = go;
            }

            // スキルボタン
            if (go.name == BUTTON_SKILL)
            {
                spObject.SkillButton = go;
            }

            // スキルテキスト
            if (go.name == TEXT_SKILL)
            {
                spObject.SkillText = go;
            }

            // キャンセルボタン
            if (go.name == BUTTON_CANCEL)
            {
                spObject.CancelButton = go;
                spObject.CancelButton.GetComponent <Button>().onClick.AddListener(() => cancelButtonAction());
            }
        }
    }