DestroyImmediate() public static method

public static DestroyImmediate ( System obj ) : void
obj System
return void
Example #1
0
 void Update()
 {
     if (this.ignoreFirstFrame)
     {
         this.ignoreFirstFrame = false;
         this.UpdateColliders  = false;
     }
     else if (this.UpdateColliders)
     {
         foreach (RelCol rc in this.GetComponentsInChildren <RelCol>())
         {
             Obj.DestroyImmediate(rc.gameObject);
         }
         this.createEveryDetectors();
         this.UpdateColliders = false;
     }
 }
Example #2
0
    private void createEveryDetectors()
    {
        this.dummy       = new GO();
        this.dummy.layer = this.gameObject.layer;
        RB rb = this.dummy.AddComponent <RB>();

        rb.useGravity  = false;
        rb.isKinematic = true;
        SC sc = this.dummy.AddComponent <SC>();

        sc.radius    = 0.125f;
        sc.isTrigger = true;
        this.dummy.AddComponent <RelCol>();

        this.forEachPos((x) => this.createDetector(x));

        Obj.DestroyImmediate(this.dummy);
    }
Example #3
0
    void Start()
    {
        GO tracker = new GO();

        tracker.layer = this.gameObject.layer;
        RB rb = tracker.AddComponent <RB>();

        rb.useGravity  = false;
        rb.isKinematic = true;
        SC sc = tracker.AddComponent <SC>();

        sc.radius    = 0.125f;
        sc.isTrigger = true;
        tracker.AddComponent <RelCol>();

        /* Generate as many detectors as requested */
        Tr t = this.transform;

        for (int i = 1; i <= this.MaxDepth; i++)
        {
            /* XXX: (again) This was the only way I found to instantiate
             * the clone in local space... */
            GO obj = Obj.Instantiate(tracker, t.position, Quat.identity, t);
            obj.name = $"ShadowTracker_{i}";
            Vec3 pos = new Vec3(0.0f, i * -1.0f, 0.0f);
            obj.transform.Translate(pos, UnityEngine.Space.World);
        }

        Obj.DestroyImmediate(tracker);

        for (int i = 0; i < this.MaxDepth * 2; i++)
        {
            List node = new List();
            node.next      = this.emptyList;
            this.emptyList = node;
        }

        this.touchingList = null;
        this.self         = this.transform;
    }
    public static void SubdivideSplitFaces_SeparatesAndSubdivides()
    {
        var cube = TestUtility.CreateCubeWithNonContiguousMergedFace();

        try
        {
            var res = Subdivision.Subdivide(cube.item1, new List <Face>()
            {
                cube.item2
            });
            // Expected result is that the invalid merged face will be split into two faces, then each face
            // subdivided.
            Assert.That(res, Has.Length.EqualTo(8));
        }
        finally
        {
            if (cube.item1 != null)
            {
                UObject.DestroyImmediate(cube.item1.gameObject);
            }
        }
    }
    public static void SubdivideFirstFace_CreatesValidMesh([ValueSource("shapeTypes")] Type shape)
    {
        var pb = ShapeFactory.Instantiate(shape);

        try
        {
            var faceCount = pb.faceCount;
            var face      = pb.facesInternal.FirstOrDefault();
            Subdivision.Subdivide(pb, new Face[] { face });
            pb.ToMesh();
            pb.Refresh();

            TestUtility.AssertMeshIsValid(pb);
            TestUtility.AssertMeshAttributesValid(pb.mesh);

            Assert.That(faceCount, Is.LessThan(pb.faceCount));
        }
        finally
        {
            UObject.DestroyImmediate(pb.gameObject);
        }
    }
Example #6
0
        /// <inheritdoc />
        protected override GameObject OnCreateControl(Transform subCategoryList)
        {
            var selGo = Object.Instantiate(GameObject.Find("SettingWindow/WinBody/B_Nip/SelectMenu"), subCategoryList);

            selGo.name = "rb";

            var       toggleGroup  = selGo.GetComponent <ToggleGroup>();
            Transform singleButton = null;

            foreach (var c in selGo.transform.Children())
            {
                var singleToggle = c.GetComponent <UI_ToggleEx>();
                toggleGroup.UnregisterToggle(singleToggle);
                if (c.name == "tgl01")
                {
                    singleToggle.onValueChanged.ActuallyRemoveAllListeners();
                    singleButton = c;
                }
                else
                {
                    Object.DestroyImmediate(c.gameObject);
                }
            }

            var txtGo = Object.Instantiate(GameObject.Find("SettingWindow/WinBody/B_Nip/Setting/Setting02/Scroll View/Viewport/Content/ColorSet/Text"), selGo.transform);

            txtGo.transform.SetAsFirstSibling();
            const int textWidth = 110;

            txtGo.AddComponent <LayoutElement>().minWidth = textWidth;
            var txtCmp = txtGo.GetComponent <Text>();

            txtCmp.text  = _settingName;
            txtCmp.color = TextColor;
            SetTextAutosize(txtCmp);

            RemoveLocalisation(selGo);

            var newButtons = new List <Toggle>();

            for (int i = 0; i < _buttons.Length; i++)
            {
                var toggleId = i;

                Transform newBtn;
                if (toggleId <= 0)
                {
                    newBtn = singleButton ?? throw new ArgumentNullException(nameof(singleButton));
                }
                else
                {
                    newBtn      = Object.Instantiate(singleButton, selGo.transform);
                    newBtn.name = "tgl0" + toggleId;
                }

                var newTglText = newBtn.GetComponentInChildren <Text>();
                newTglText.text = _buttons[i];
                SetTextAutosize(newTglText);

                var newTgl = newBtn.GetComponent <UI_ToggleEx>();
                newTgl.group = toggleGroup;

                newTgl.onValueChanged.AddListener(
                    val =>
                {
                    if (val)
                    {
                        SetValue(toggleId);
                    }
                });

                newButtons.Add(newTgl);
            }

            Buttons = newButtons.AsReadOnly();


            var singleToggleWidth = (selGo.GetComponent <RectTransform>().sizeDelta.x - textWidth - 10) / Buttons.Count;

            foreach (var button in Buttons)
            {
                button.GetComponent <LayoutElement>().minWidth = singleToggleWidth;
            }

            BufferedValueChanged.Subscribe(
                i =>
            {
                for (var index = 0; index < Buttons.Count; index++)
                {
                    var tgl  = Buttons[index];
                    tgl.isOn = index == i;
                }
            });

            return(selGo.gameObject);
        }
Example #7
0
 void OnDetach()
 {
     Object.DestroyImmediate(m_Mat);
     m_Mat = null;
 }
Example #8
0
        /// <summary>
        ///     Assetディレクトリに追加されたファイルを確認、インポート処理を行う
        /// </summary>
        /// <param name="importedAssetPaths"></param>
        /// <param name="optionOverwriteImport"></param>
        /// <param name="optionDeleteImportedAssets"></param>
        private static async Task <int> Import(string baseFolderPath, IEnumerable <string> importedAssetPaths,
                                               bool optionOverwriteImport,
                                               bool optionDeleteImportedAssets)
        {
            var importedPaths = importedAssetPaths.ToList();

            _progressTotal = importedPaths.Count();
            if (_progressTotal == 0)
            {
                return(0);
            }
            _progressCount = 0;

            // Png->Spriteに変換するリストをクリアする
            PreprocessTexture.SlicedTextures = null;

            // インポートされたファイルからフォルダパスリストを作成する
            // Key: AssetPath
            // Value: ディレクトリにあるファイルの拡張子
            var importedFolderAssetPaths = new FolderInfos();

            foreach (var importedAssetPath in importedAssetPaths)
            {
                if (EditorUtil.IsFolder(importedAssetPath) == true)
                {
                    // すでにフォルダパスはスルー
                    continue;
                }

                var folderPath = Path.GetDirectoryName(importedAssetPath);
                var extension  = Path.GetExtension(importedAssetPath);
                importedFolderAssetPaths.Add(folderPath, extension);
            }

            // 出力フォルダの作成
            foreach (var importedFolderInfo in importedFolderAssetPaths)
            {
                if (EditorUtil.IsFolder(importedFolderInfo.Key) != true)
                {
                    continue;
                }

                // フォルダであった場合
                var importedFullPath = Path.GetFullPath(importedFolderInfo.Key);
                var subFolderName    = EditorUtil.GetSubFolderName(baseFolderPath, importedFolderInfo.Key + "/file.tmp");

                // このフォルダには.pngファイルがあるか
                var isSpriteFolder = importedFolderInfo.Value.Contains(".png");

                // スプライト出力フォルダの準備
                if (isSpriteFolder)
                {
                    var outputSpritesFolderAssetPath = Path.Combine(
                        EditorUtil.GetOutputSpritesFolderAssetPath(), subFolderName);
                    if (Directory.Exists(outputSpritesFolderAssetPath))
                    {
                        // フォルダがすでにある インポートファイルと比較して、出力先にある必要のないファイルを削除する
                        // ダブっている分は比較し、異なっている場合に上書きするようにする
                        var outputFolderInfo = new DirectoryInfo(outputSpritesFolderAssetPath);
                        var importFolderInfo = new DirectoryInfo(importedFullPath);

                        var existSpritePaths  = outputFolderInfo.GetFiles("*.png", SearchOption.AllDirectories);
                        var importSpritePaths = importFolderInfo.GetFiles("*.png", SearchOption.AllDirectories);

                        // outputフォルダにある importにはないファイルをリストアップする
                        // そしてそれを削除するという処理であったが不具合が発生する
                        // 別のLayout.Jsonから参照されているテクスチャも消えてしまう
                        // テクスチャについて未使用を削除するには
                        // - フォルダを消して再インポート
                        // - imageHashMapキャッシュファイルからつかわれていないものを削除する という処理をいれなければならない
                        // var deleteEntries = existSpritePaths.Except(importSpritePaths, new FileInfoComparer()).ToList();
                        var deleteEntries = new List <FileInfo>();

                        // スプライト出力フォルダがすでにある場合はTextureハッシュキャッシュを削除する
                        deleteEntries.Add(new FileInfo(outputSpritesFolderAssetPath + "/" +
                                                       TextureUtil.ImageHashMapCacheFileName));
                        deleteEntries.Add(new FileInfo(outputSpritesFolderAssetPath + "/" +
                                                       TextureUtil.ImagePathMapCacheFileName));
                        if (!optionOverwriteImport)
                        {
                            // 削除する
                            foreach (var fileInfo in deleteEntries)
                            {
                                AssetDatabase.DeleteAsset(EditorUtil.ToAssetPath(fileInfo.FullName));
                            }
                        }
                    }
                    else
                    {
                        // Debug.Log($"[{Importer.Name}] Create Folder: {subFolderName}");
                        EditorUtil.CreateFolder(outputSpritesFolderAssetPath);
                    }
                }

                var outputPrefabsFolderAssetPath = Path.Combine(EditorUtil.GetOutputPrefabsFolderAssetPath(), subFolderName);
                if (!Directory.Exists(outputPrefabsFolderAssetPath))
                {
                    EditorUtil.CreateFolder(outputPrefabsFolderAssetPath);
                }

                UpdateDisplayProgressBar($"Import Folder Preparation: {subFolderName}");
            }

            await Task.Delay(1000);

            // ディレクトリが作成されたり、画像が削除されるためRefresh
            AssetDatabase.Refresh();

            // フォルダが作成され、そこに画像を出力する場合
            // Refresh後、DelayCallで画像生成することで、処理が安定した
            // await Task.Delay(1000);

            // SpriteイメージのハッシュMapをクリアしたかどうかのフラグ
            // importedAssetsに一気に全部の新規ファイルが入ってくる前提の処理
            // 全スライス処理が走る前、最初にClearImageMapをする
            var clearedImageMap = false;
            // 画像コンバート スライス処理
            var messageCounter = new Dictionary <string, int>();
            var total          = 0;

            try
            {
                foreach (var pngAssetPath in importedPaths)
                {
                    // Debug.Log($"Slice: {importedAsset}");
                    if (!pngAssetPath.EndsWith(".png", StringComparison.Ordinal))
                    {
                        continue;
                    }
                    //
                    if (!clearedImageMap)
                    {
                        clearedImageMap = true;
                    }

                    var subFolderName    = EditorUtil.GetSubFolderName(baseFolderPath, pngAssetPath);
                    var outputFolderPath = Path.Combine(EditorUtil.GetOutputSpritesFolderAssetPath(), subFolderName);
                    var outputFilePath   = Path.Combine(outputFolderPath, Path.GetFileName(pngAssetPath));
                    // スライス処理
                    var message = TextureUtil.SliceSprite(outputFilePath, pngAssetPath);

                    total++;
                    _progressCount += 2; // pngファイル と png.jsonファイル
                    UpdateDisplayProgressBar(message);

                    // 出力されたログをカウントする
                    if (messageCounter.ContainsKey(message))
                    {
                        messageCounter[message] = messageCounter[message] + 1;
                    }
                    else
                    {
                        messageCounter.Add(message, 1);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.LogAssertion(ex.Message);
                Debug.LogAssertion(ex.StackTrace);
            }

            foreach (var keyValuePair in messageCounter)
            {
                Debug.Log($"[{Importer.NAME}] {keyValuePair.Key} {keyValuePair.Value}/{total}");
            }


            var importLayoutFilePaths = new List <string>();

            foreach (var layoutFilePath in importedPaths)
            {
                if (!layoutFilePath.EndsWith(".layout.json", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }
                importLayoutFilePaths.Add(layoutFilePath);
            }

            string GetPrefabPath(string layoutFilePath)
            {
                var prefabFileName = Path.GetFileName(layoutFilePath).Replace(".layout.json", "") + ".prefab";
                var subFolderName  = EditorUtil.GetSubFolderName(baseFolderPath, layoutFilePath);
                var saveAssetPath  =
                    Path.Combine(Path.Combine(EditorUtil.GetOutputPrefabsFolderAssetPath(),
                                              subFolderName), prefabFileName);

                return(saveAssetPath);
            }

            string GetPrefabName(string layoutFilePath)
            {
                var prefabFileName = Path.GetFileName(layoutFilePath).Replace(".layout.json", "");
                var subFolderName  = EditorUtil.GetSubFolderName(baseFolderPath, layoutFilePath);

                return(subFolderName + "/" + prefabFileName);
            }

            // 出力されたスライスPNGをSpriteに変換する処理を走らせるために必須
            // ここでPreprocessTextureが実行されなければいけない
            AssetDatabase.Refresh();
            await Task.Delay(1000);

            if (PreprocessTexture.SlicedTextures != null && PreprocessTexture.SlicedTextures.Count != 0)
            {
                // Debug.LogWarning($"[{Importer.Name}] SlicedTextures is still available.");
            }

            var prefabs = new List <GameObject>();

            // .layout.jsonを全て読み込んで、コンバート順をソートする
            // Item1: prefab name dependensyチェック用
            // Item2: file path
            // Item3: json data
            var layoutJsons = new List <Tuple <string, string, Dictionary <string, object> > >();

            foreach (var layoutFilePath in importLayoutFilePaths)
            {
                var prefabName = GetPrefabName(layoutFilePath);
                // Load JSON
                var jsonText = File.ReadAllText(layoutFilePath);
                var json     = Json.Deserialize(jsonText) as Dictionary <string, object>;
                layoutJsons.Add(
                    new Tuple <string, string, Dictionary <string, object> >(prefabName, layoutFilePath, json));
            }

            // コンバートする順番を決める
            layoutJsons.Sort((a, b) =>
            {
                List <object> GetDependency(Dictionary <string, object> json)
                {
                    return(json.GetDic("info")?.GetArray("dependency"));
                }

                int GetDependencyCount(Dictionary <string, object> json)
                {
                    var dr = GetDependency(json);
                    return(dr?.Count ?? 0);
                }

                bool Check(string name, Dictionary <string, object> json)
                {
                    var nameList = GetDependency(json);
                    if (nameList == null)
                    {
                        return(false);
                    }
                    return(nameList.Any(o => name == o as string));
                }

                // aはbより先に処理すべきか
                if (Check(a.Item1, b.Item3))
                {
                    return(-1);
                }
                // bはaより先に処理すべきか
                if (Check(b.Item1, a.Item3))
                {
                    return(1);
                }

                // 依存ファイル数で決着をつける
                return(GetDependencyCount(a.Item3) - GetDependencyCount(b.Item3));
            });

            // Create Prefab
            foreach (var layoutJson in layoutJsons)
            {
                UpdateDisplayProgressBar($"Layout: {layoutJson.Item1}");
                _progressCount += 1;

                var layoutFilePath = layoutJson.Item2;
                var subFolderName  = EditorUtil.GetSubFolderName(baseFolderPath, layoutFilePath);

                GameObject go = null;
                try
                {
                    // Debug.Log($"[{Importer.Name}] in process...{Path.GetFileName(layoutFilePath)}");
                    var saveAssetPath = GetPrefabPath(layoutFilePath);
                    var spriteOutputFolderAssetPath =
                        Path.Combine(EditorUtil.GetOutputSpritesFolderAssetPath(), subFolderName);
                    var fontAssetPath = EditorUtil.GetFontsFolderAssetPath();

                    // overwriteImportFlagがTrueなら、ベースとなるPrefab上に生成していく
                    // 利用できるオブジェクトは利用していく
                    if (optionOverwriteImport)
                    {
                        // すでにあるプレハブを読み込む
                        var prefab = AssetDatabase.LoadAssetAtPath <GameObject>(saveAssetPath);
                        if (prefab != null)
                        {
                            go = PrefabUtility.InstantiatePrefab(prefab) as GameObject;
                            PrefabUtility.UnpackPrefabInstance(go, PrefabUnpackMode.OutermostRoot,
                                                               InteractionMode.AutomatedAction);
                        }
                    }

                    // Render Context
                    var renderContext = new RenderContext(spriteOutputFolderAssetPath, fontAssetPath, go);
                    if (optionOverwriteImport)
                    {
                        renderContext.OptionAddXdGuidComponent = true;
                    }

                    // Load JSON
                    var jsonText = File.ReadAllText(layoutFilePath);
                    var json     = Json.Deserialize(jsonText) as Dictionary <string, object>;
                    //var info = json.GetDic("info");
                    //Validation(info);
                    var rootJson = json.GetDic("root");

                    // Create Prefab
                    var prefabCreator = new PrefabCreator(prefabs);
                    prefabCreator.Create(ref go, renderContext, rootJson);

                    // Save Prefab
                    EditorUtil.CreateFolder(Path.GetDirectoryName(saveAssetPath));
                    var savedAsset = PrefabUtility.SaveAsPrefabAsset(go, saveAssetPath);
                    Debug.Log($"[{Importer.NAME}] Created: <color=#7FD6FC>{Path.GetFileName(saveAssetPath)}</color>",
                              savedAsset);
                }
                catch (Exception ex)
                {
                    Debug.LogAssertion($"[{Importer.NAME}] " + ex.Message + "\n" + ex.StackTrace);
                    // 変換中例外が起きた場合もテンポラリGameObjectを削除する
                    EditorUtility.ClearProgressBar();
                    EditorUtility.DisplayDialog("Import Failed", ex.Message, "Close");
                    throw;
                }
                finally
                {
                    Object.DestroyImmediate(go);
                }

                AssetDatabase.Refresh();
                await Task.Delay(100);
            }


            // インポートしたファイルを削除し、そのフォルダが空になったらフォルダも削除する
            if (optionDeleteImportedAssets)
            {
                foreach (var forImportAssetPath in importedAssetPaths)
                {
                    // フォルダの場合はスルー
                    if (EditorUtil.IsFolder(forImportAssetPath) == true)
                    {
                        continue;
                    }

                    // インポートするファイルを削除
                    AssetDatabase.DeleteAsset(forImportAssetPath);
                    // ファイルがあったフォルダが空になったかチェック
                    var folderName = Path.GetDirectoryName(forImportAssetPath);
                    var files      = Directory.GetFiles(folderName);
                    if (files.Length == 0)
                    {
                        // フォルダの削除
                        // Debug.Log($"ディレクトリ削除{folderName}");
                        AssetDatabase.DeleteAsset(folderName);
                    }
                }
            }

            AssetDatabase.Refresh();
            EditorUtility.ClearProgressBar();
            return(0);
        }
Example #9
0
        private static void CreateSpinePrefabInternal(SkeletonDataAsset skeletonDataAsset)
        {
            var assetPath           = AssetDatabase.GetAssetPath(skeletonDataAsset);
            var assetFolderPath     = assetPath.Replace(Path.GetFileName(assetPath), "");
            var animationAssetsPath = Path.Combine(assetFolderPath, "ReferenceAssets");
            var split      = assetPath.Split('/');
            var prefabName = split[split.Length > 1 ? split.Length - 2 : 0];
            var prefabPath = GetPrefabPath(prefabName);

            if (!ValidateSpineResource(prefabName, skeletonDataAsset))
            {
                return;
            }

            CreateAnimationReferenceAssets(skeletonDataAsset);

            var skeletonAnimation =
                SpineEditorUtilities.EditorInstantiation.InstantiateSkeletonAnimation(
                    skeletonDataAsset);

            skeletonAnimation.AnimationName = nameof(CharacterAnimation.Type.Idle);

            var gameObject = skeletonAnimation.gameObject;

            gameObject.name  = prefabName;
            gameObject.layer = LayerMask.NameToLayer("Character");
            gameObject.transform.position   = Position;
            gameObject.transform.localScale = GetPrefabLocalScale(prefabName);

            var meshRenderer = gameObject.GetComponent <MeshRenderer>();

            meshRenderer.lightProbeUsage      = LightProbeUsage.Off;
            meshRenderer.reflectionProbeUsage = ReflectionProbeUsage.Off;
            meshRenderer.shadowCastingMode    = ShadowCastingMode.Off;
            meshRenderer.receiveShadows       = false;
            meshRenderer.sortingLayerName     = "Character";

            var animatorControllerGuidArray = AssetDatabase.FindAssets(FindAssetFilter);

            if (animatorControllerGuidArray.Length == 0)
            {
                Object.DestroyImmediate(gameObject);
                throw new AssetNotFoundException(
                          $"AssetDatabase.FindAssets(\"{FindAssetFilter}\")");
            }

            var animatorControllerPath =
                AssetDatabase.GUIDToAssetPath(animatorControllerGuidArray[0]);
            var animator = gameObject.AddComponent <Animator>();

            animator.runtimeAnimatorController =
                AssetDatabase.LoadAssetAtPath <AnimatorController>(animatorControllerPath);

            var controller = GetOrCreateSpineController(prefabName, gameObject);

            // 지금은 예상 외의 애니메이션을 찾지 못하는 로직이다.
            // animationAssetsPath 하위에 있는 모든 것을 검사..?
            // 애초에 CreateAnimationReferenceAssets() 단계에서 검사할 수 있겠다.
            foreach (var animationType in CharacterAnimation.List)
            {
                assetPath = Path.Combine(animationAssetsPath, $"{animationType}.asset");
                var asset = AssetDatabase.LoadAssetAtPath <AnimationReferenceAsset>(assetPath);
                if (asset is null)
                {
                    switch (animationType)
                    {
                    // todo: `CharacterAnimation.Type.Appear`와 `CharacterAnimation.Type.Disappear`는 없어질 예정.
                    default:
                        assetPath = Path.Combine(
                            animationAssetsPath,
                            $"{nameof(CharacterAnimation.Type.Idle)}.asset");
                        asset = AssetDatabase.LoadAssetAtPath <AnimationReferenceAsset>(
                            assetPath);
                        break;

                    case CharacterAnimation.Type.Idle:
                        Object.DestroyImmediate(gameObject);
                        throw new AssetNotFoundException(assetPath);

                    case CharacterAnimation.Type.Win_02:
                    case CharacterAnimation.Type.Win_03:
                        assetPath = Path.Combine(
                            animationAssetsPath,
                            $"{nameof(CharacterAnimation.Type.Win)}.asset");
                        asset = AssetDatabase.LoadAssetAtPath <AnimationReferenceAsset>(
                            assetPath);
                        break;

                    case CharacterAnimation.Type.Touch:
                    case CharacterAnimation.Type.CastingAttack:
                    case CharacterAnimation.Type.CriticalAttack:
                        assetPath = Path.Combine(
                            animationAssetsPath,
                            $"{nameof(CharacterAnimation.Type.Attack)}.asset");
                        asset = AssetDatabase.LoadAssetAtPath <AnimationReferenceAsset>(
                            assetPath);
                        break;

                    case CharacterAnimation.Type.TurnOver_01:
                    case CharacterAnimation.Type.TurnOver_02:
                        assetPath = Path.Combine(
                            animationAssetsPath,
                            $"{nameof(CharacterAnimation.Type.Die)}.asset");
                        asset = AssetDatabase.LoadAssetAtPath <AnimationReferenceAsset>(
                            assetPath);
                        break;
                    }

                    if (asset is null)
                    {
                        assetPath = Path.Combine(
                            animationAssetsPath,
                            $"{nameof(CharacterAnimation.Type.Idle)}.asset");
                        asset = AssetDatabase.LoadAssetAtPath <AnimationReferenceAsset>(assetPath);
                    }

                    if (asset is null)
                    {
                        Object.DestroyImmediate(gameObject);
                        throw new AssetNotFoundException(assetPath);
                    }
                }

                controller.statesAndAnimations.Add(
                    new SpineController.StateNameToAnimationReference
                {
                    stateName = animationType.ToString(),
                    animation = asset
                });
            }

            // 헤어타입을 결정한다.
            if (controller is PlayerSpineController playerSpineController)
            {
                playerSpineController.hairTypeIndex = HairType1Names.Contains(prefabName)
                    ? 1
                    : 0;
            }

            if (File.Exists(prefabPath))
            {
                var boxCollider       = controller.GetComponent <BoxCollider>();
                var sourceBoxCollider = AssetDatabase.LoadAssetAtPath <BoxCollider>(prefabPath);
                boxCollider.center = sourceBoxCollider.center;
                boxCollider.size   = sourceBoxCollider.size;

                AssetDatabase.DeleteAsset(prefabPath);
            }

            try
            {
                var prefab = PrefabUtility.SaveAsPrefabAsset(gameObject, prefabPath);
                Object.DestroyImmediate(gameObject);
                Selection.activeObject = prefab;
            }
            catch
            {
                Object.DestroyImmediate(gameObject);
                throw new FailedToSaveAsPrefabAssetException(prefabPath);
            }
        }
Example #10
0
        private static void CleanAvatar(VRCAvatarManager avatarManager, GameObject go)
        {
            if (!AdvancedSafetySettings.AvatarFilteringEnabled)
            {
                return;
            }

            if (AdvancedSafetySettings.AvatarFilteringOnlyInPublic &&
                RoomManager.field_Internal_Static_ApiWorldInstance_0?.InstanceType != ApiWorldInstance.AccessType.Public)
            {
                return;
            }

            var vrcPlayer = avatarManager.field_Private_VRCPlayer_0;

            if (vrcPlayer == null)
            {
                return;
            }

            var userId = vrcPlayer.prop_Player_0?.prop_APIUser_0?.id ?? "";

            if (!AdvancedSafetySettings.IncludeFriends && APIUser.IsFriendsWith(userId))
            {
                return;
            }

            if (AdvancedSafetySettings.AbideByShowAvatar && IsAvatarExplicitlyShown(userId))
            {
                return;
            }

            var start            = Stopwatch.StartNew();
            var scannedObjects   = 0;
            var destroyedObjects = 0;

            var seenTransforms           = 0;
            var seenPolys                = 0;
            var seenMaterials            = 0;
            var seenAudioSources         = 0;
            var seenConstraints          = 0;
            var seenClothVertices        = 0;
            var seenColliders            = 0;
            var seenRigidbodies          = 0;
            var seenAnimators            = 0;
            var seenLights               = 0;
            var seenComponents           = 0;
            var seenParticles            = 0;
            var seenMeshParticleVertices = 0;

            var animator = go.GetComponent <Animator>();

            var componentList           = new Il2CppSystem.Collections.Generic.List <Component>();
            var audioSourcesList        = new List <AudioSource>();
            var skinnedRendererListList = new List <SkinnedMeshRenderer>();

            void Bfs(GameObjectWithPriorityData objWithPriority)
            {
                var obj = objWithPriority.GameObject;

                if (obj == null)
                {
                    return;
                }
                scannedObjects++;

                if (animator?.IsBoneTransform(obj.transform) != true && seenTransforms++ >= AdvancedSafetySettings.MaxTransforms)
                {
                    Object.DestroyImmediate(obj, true);
                    destroyedObjects++;
                    return;
                }

                if (objWithPriority.Depth >= AdvancedSafetySettings.MaxDepth)
                {
                    Object.DestroyImmediate(obj, true);
                    destroyedObjects++;
                    return;
                }

                if (!AdvancedSafetySettings.AllowUiLayer && (obj.layer == 12 || obj.layer == 5))
                {
                    obj.layer = 9;
                }

                obj.GetComponents(componentList);
                foreach (var component in componentList)
                {
                    if (component == null)
                    {
                        continue;
                    }

                    component.TryCast <AudioSource>()?.VisitAudioSource(ref scannedObjects, ref destroyedObjects, ref seenAudioSources, obj, audioSourcesList, objWithPriority.IsActiveInHierarchy);
                    component.TryCast <IConstraint>()?.VisitConstraint(ref scannedObjects, ref destroyedObjects, ref seenConstraints, obj);
                    component.TryCast <Cloth>()?.VisitCloth(ref scannedObjects, ref destroyedObjects, ref seenClothVertices, obj);
                    component.TryCast <Rigidbody>()?.VisitGeneric(ref scannedObjects, ref destroyedObjects, ref seenRigidbodies, AdvancedSafetySettings.MaxRigidBodies);

                    component.TryCast <Collider>()?.VisitCollider(ref scannedObjects, ref destroyedObjects, ref seenColliders, obj);
                    component.TryCast <Animator>()?.VisitGeneric(ref scannedObjects, ref destroyedObjects, ref seenAnimators, AdvancedSafetySettings.MaxAnimators);
                    component.TryCast <Light>()?.VisitGeneric(ref scannedObjects, ref destroyedObjects, ref seenLights, AdvancedSafetySettings.MaxLights);

                    component.TryCast <Renderer>()?.VisitRenderer(ref scannedObjects, ref destroyedObjects, ref seenPolys, ref seenMaterials, obj, skinnedRendererListList);
                    component.TryCast <ParticleSystem>()?.VisitParticleSystem(component.GetComponent <ParticleSystemRenderer>(), ref scannedObjects, ref destroyedObjects, ref seenParticles, ref seenMeshParticleVertices, obj);

                    if (ReferenceEquals(component.TryCast <Transform>(), null))
                    {
                        component.VisitGeneric(ref scannedObjects, ref destroyedObjects, ref seenComponents, AdvancedSafetySettings.MaxComponents);
                    }
                }

                foreach (var child in obj.transform)
                {
                    ourBfsQueue.Enqueue(new GameObjectWithPriorityData(child.Cast <Transform>().gameObject, objWithPriority.Depth + 1, objWithPriority.IsActiveInHierarchy));
                }
            }

            Bfs(new GameObjectWithPriorityData(go, 0, true, true));
            while (ourBfsQueue.Count > 0)
            {
                Bfs(ourBfsQueue.Dequeue());
            }

            ComponentAdjustment.PostprocessSkinnedRenderers(skinnedRendererListList);

            if (!AdvancedSafetySettings.AllowSpawnSounds)
            {
                MelonCoroutines.Start(CheckSpawnSounds(go, audioSourcesList));
            }

            if (MelonDebug.IsEnabled() || destroyedObjects > 100)
            {
                MelonLogger.Msg($"Cleaned avatar ({avatarManager.prop_ApiAvatar_0?.name}) used by \"{vrcPlayer.prop_VRCPlayerApi_0?.displayName}\" in {start.ElapsedMilliseconds}ms, scanned {scannedObjects} things, destroyed {destroyedObjects} things");
            }
        }
Example #11
0
 public void OnDestroy()
 {
     Object.DestroyImmediate(searchWindowProvider);
 }
        private static Texture2D Render(
            Camera camera,
            Shader shader,
            Renderer[] renderers,
            int width  = -1,
            int height = -1)
        {
            bool autoSize = width < 0 || height < 0;

            int _width  = autoSize ? (int)camera.pixelRect.width : width;
            int _height = autoSize ? (int)camera.pixelRect.height : height;

            GameObject go        = new GameObject();
            Camera     renderCam = go.AddComponent <Camera>();

            renderCam.CopyFrom(camera);

            renderCam.renderingPath   = RenderingPath.Forward;
            renderCam.enabled         = false;
            renderCam.clearFlags      = CameraClearFlags.SolidColor;
            renderCam.backgroundColor = Color.white;
            renderCam.cullingMask     = 0;

            IRenderPipelineCameraUtility cameraUtility = IOC.Resolve <IRenderPipelineCameraUtility>();

            if (cameraUtility != null)
            {
                cameraUtility.EnablePostProcessing(renderCam, false);
                cameraUtility.SetBackgroundColor(renderCam, Color.white);
            }

            renderCam.allowHDR  = false;
            renderCam.allowMSAA = false;
            renderCam.forceIntoRenderTexture = true;

            float aspect = renderCam.aspect;

            renderCam.rect   = new Rect(Vector2.zero, Vector2.one);
            renderCam.aspect = aspect;

            RenderTextureDescriptor descriptor = new RenderTextureDescriptor()
            {
                width             = _width,
                height            = _height,
                colorFormat       = RenderTextureFormat,
                autoGenerateMips  = false,
                depthBufferBits   = 16,
                dimension         = TextureDimension.Tex2D,
                enableRandomWrite = false,
                memoryless        = RenderTextureMemoryless.None,
                sRGB        = true,
                useMipMap   = false,
                volumeDepth = 1,
                msaaSamples = 1
            };
            RenderTexture rt = RenderTexture.GetTemporary(descriptor);

            RenderTexture prev = RenderTexture.active;

            renderCam.targetTexture = rt;
            RenderTexture.active    = rt;

            Material replacementMaterial = new Material(shader);

            IRTEGraphics graphics  = IOC.Resolve <IRTEGraphics>();
            IRTECamera   rteCamera = graphics.CreateCamera(renderCam, CameraEvent.AfterForwardAlpha, false, true);

            rteCamera.RenderersCache.MaterialOverride = replacementMaterial;
            rteCamera.Camera.name = "BoxSelectionCamera";
            foreach (Renderer renderer in renderers)
            {
                Material[] materials = renderer.sharedMaterials;
                for (int i = 0; i < materials.Length; ++i)
                {
                    if (materials[i] != null)
                    {
                        rteCamera.RenderersCache.Add(renderer);
                    }
                }
            }
            rteCamera.RefreshCommandBuffer();

            if (RenderPipelineInfo.Type != RPType.Standard)
            {
                bool invertCulling = GL.invertCulling;
                GL.invertCulling            = true;
                renderCam.projectionMatrix *= Matrix4x4.Scale(new Vector3(1, -1, 1));
                renderCam.Render();
                GL.invertCulling = invertCulling;
            }
            else
            {
                renderCam.Render();
            }

            Texture2D img = new Texture2D(_width, _height, TextureFormat, false, false);

            img.ReadPixels(new Rect(0, 0, _width, _height), 0, 0);
            img.Apply();

            RenderTexture.active = prev;
            RenderTexture.ReleaseTemporary(rt);

            UnityObject.DestroyImmediate(go);
            UnityObject.Destroy(replacementMaterial);

            rteCamera.Destroy();
            //System.IO.File.WriteAllBytes("Assets/box_selection.png", img.EncodeToPNG());

            return(img);
        }
 public void Kill()
 {
     Object.DestroyImmediate(go);
 }
Example #14
0
 public void DestroyTextures()
 {
     texturesHaveBeenDestroyed = true;
     UnityObject.DestroyImmediate(FirstStyle.normal.background);
     UnityObject.DestroyImmediate(SecondStyle.normal.background);
 }
Example #15
0
        private LogEntry Match(Transform local, Transform model)
        {
            Component[] components = model.GetComponents <Component>();

            if (components.Any(c => c is MultiModel))
            {
                return(new LogEntry("Nested multimodel", local, model));
            }

            LogEntry log = new LogEntry("Transforms", local, model);

            if (!dryRun)
            {
                local.gameObject.SetActive(model.gameObject.activeSelf);
            }

            foreach (Component modelComponent in components)
            {
                if (modelComponent is Transform)
                {
                    continue;
                }

                Type      type           = modelComponent.GetType();
                Component localComponent = local.GetComponent(type);
                if (!dryRun && localComponent == null)
                {
                    local.gameObject.AddComponent(type);
                }

#if UNITY_EDITOR
                if (local.GetComponents(type).Length > 1)
                {
                    throw new Exception();
                }
#endif
                log.Add(Match(localComponent, modelComponent));
            }

            Dictionary <string, Transform> childDictionary = CreateChildDictionary(local);

            foreach (Transform modelChild in model)
            {
                Transform localChild;
                string    name         = modelChild.name;
                bool      missingChild = false;
                if (childDictionary.ContainsKey(name))
                {
                    localChild = childDictionary[name];
                    childDictionary.Remove(name);
                }
                else
                {
                    missingChild = true;
                    localChild   = new GameObject(name).transform;
                    localChild.SetParent(local);
                }


                localChild.localPosition = modelChild.localPosition;
                localChild.localRotation = modelChild.localRotation;
                localChild.localScale    = modelChild.localScale;

                log.Add(Match(localChild, modelChild));

                if (missingChild && dryRun)
                {
                    Object.DestroyImmediate(localChild.gameObject);
                }
            }

            foreach (Transform unvisited in childDictionary.Values)
            {
                //IDEA: check if this was in the _currentModel
                if (!dryRun && unvisited.GetComponent <SkinnedMeshRenderer>() != null)
                {
                    unvisited.gameObject.SetActive(false);
                }
                log.Add(new LogEntry("unvisited", unvisited, null));
            }

            return(log);
        }
Example #16
0
 public static void DestroyStyleTexture(GUIStyle style)
 {
     UnityObject.DestroyImmediate(style.normal.background);
 }
Example #17
0
 public override void ExtraTearDown()
 {
     // set isServer is false. otherwise Destroy instead of
     // DestroyImmediate is called internally, giving an error in Editor
     Object.DestroyImmediate(gameObject);
 }
Example #18
0
        // the actual bake procedure
        public void Bake(int raySamples, List <Renderer> renderers, Action <SDFVolume, float[], float, object> bakeComplete, object passthrough = null)
        {
            onBakeComplete = bakeComplete;

            int progressInterval = _settings.CellCount / 4;
            //int progress = 0;

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            vec3 halfVoxel = _settings.HalfVoxel;
            //float maxDistance = 0f;

            // adjusted to best timings from testing but it could vary by CPU
            int calcRayLengthBatchCount = 32;

            calcRayLengthBatchCount = Mathf.Clamp(calcRayLengthBatchCount, 1, raySamples);
            int raycastBatchCount = 8;

            raycastBatchCount = Mathf.Clamp(raycastBatchCount, 1, raySamples);
            int prepareRaysBatchCount = 64;

            prepareRaysBatchCount = Mathf.Clamp(prepareRaysBatchCount, 1, raySamples);
            int compareBatchCount = 128;

            // for raycast method front facing geo and flipped backfacing geo is required
            List <Collider> geoFront = new List <Collider>();
            List <Collider> geoBack  = new List <Collider>();

            CreateColliders(ref renderers, ref geoFront, ref geoBack);

            // prepare data
            NativeArray <float>       distances  = new NativeArray <float>(_settings.CellCount, Allocator.TempJob);
            NativeArray <CellResults> allResults = new NativeArray <CellResults>(_settings.CellCount, Allocator.TempJob);

            // constant for all cells
            NativeArray <vec3> sphereSamples = new NativeArray <vec3>(raySamples, Allocator.TempJob);
            // NativeArray<vec3> randomDirections = new NativeArray<vec3>(raySamples, Allocator.TempJob);
            NativeArray <vec4> volumePlanes = new NativeArray <vec4>(6, Allocator.TempJob);

            GetUniformPointsOnSphereNormalized(ref sphereSamples);
            // GetRandomDirections( _halfVoxel*settings.JitterScale, settings.JitterSeed, ref randomDirections);

            vec3 aabbMin = BoundsWorldAABB.min;
            vec3 aabbMax = BoundsWorldAABB.max;
            // the max ray length, used to normalize all resulting distances
            // so they are treated as 0 to 1 within a volume
            float aabbMagnitude = BoundsWorldAABB.size.magnitude;

            Plane pl = new Plane(Vector3.right, aabbMin);
            Plane pr = new Plane(Vector3.left, aabbMax);
            Plane pd = new Plane(Vector3.up, aabbMin);
            Plane pu = new Plane(Vector3.down, aabbMax);
            Plane pb = new Plane(Vector3.forward, aabbMin);
            Plane pf = new Plane(Vector3.back, aabbMax);

            volumePlanes[0] = new vec4(pl.normal.x, pl.normal.y, pl.normal.z, pl.distance);
            volumePlanes[1] = new vec4(pr.normal.x, pr.normal.y, pr.normal.z, pr.distance);
            volumePlanes[2] = new vec4(pd.normal.x, pd.normal.y, pd.normal.z, pd.distance);
            volumePlanes[3] = new vec4(pu.normal.x, pu.normal.y, pu.normal.z, pu.distance);
            volumePlanes[4] = new vec4(pb.normal.x, pb.normal.y, pb.normal.z, pb.distance);
            volumePlanes[5] = new vec4(pf.normal.x, pf.normal.y, pf.normal.z, pf.distance);

            // iterate each cell performing raycasted samples
            for (int i = 0; i < _settings.CellCount; i++)
            {
#if UNITY_EDITOR
                if (i % progressInterval == 0)
                {
                    EditorUtility.DisplayProgressBar(strProgressTitle, strProgress, i / (float)_settings.CellCount);
                }
#endif

                vec3 positionWS    = _settings.ToPositionWS(i, LocalToWorldNoScale);
                vec3 centerVoxelWS = positionWS + halfVoxel;

                NativeArray <float>          rayLengths       = new NativeArray <float>(raySamples, Allocator.TempJob);
                NativeArray <RaycastCommand> allRaycastsFront = new NativeArray <RaycastCommand>(raySamples, Allocator.TempJob);
                NativeArray <RaycastCommand> allRaycastsBack  = new NativeArray <RaycastCommand>(raySamples, Allocator.TempJob);
                NativeArray <RaycastHit>     frontHits        = new NativeArray <RaycastHit>(raySamples, Allocator.TempJob);
                NativeArray <RaycastHit>     backHits         = new NativeArray <RaycastHit>(raySamples, Allocator.TempJob);

                // calculate the ray lengths, just so rays are clipped within the volume when raycasting
                CalculateRayLengths calcRayLengths = new CalculateRayLengths
                {
                    Samples      = sphereSamples,
                    VolumePlanes = volumePlanes,
                    // tempBound = BoundsWorldAABB,
                    RayLengths = rayLengths,
                    RayLength  = aabbMagnitude,
                    RayOrigin  = centerVoxelWS
                };
                JobHandle rayLengthHandle = calcRayLengths.Schedule(raySamples, calcRayLengthBatchCount);

                // prepare raycasts front
                PrepareRaycastCommands frontPrc = new PrepareRaycastCommands
                {
                    Samples    = sphereSamples,
                    RayLengths = rayLengths,
                    LayerMask  = LAYER_MASK_FRONT,
                    Raycasts   = allRaycastsFront,
                    RayOrigin  = centerVoxelWS,
                };
                // prepare raycasts back
                PrepareRaycastCommands backPrc = new PrepareRaycastCommands
                {
                    Samples    = sphereSamples,
                    RayLengths = rayLengths,
                    LayerMask  = LAYER_MASK_BACK,
                    Raycasts   = allRaycastsBack,
                    RayOrigin  = centerVoxelWS,
                };

                // schedule front raycasts
                JobHandle prepareFrontHandle = frontPrc.Schedule(
                    raySamples, prepareRaysBatchCount, rayLengthHandle);
                JobHandle scheduleFrontHandle = RaycastCommand.ScheduleBatch(
                    allRaycastsFront, frontHits, raycastBatchCount, prepareFrontHandle);

                // schedule back raycasts
                JobHandle prepareBackHandle = backPrc.Schedule(
                    raySamples, prepareRaysBatchCount, rayLengthHandle);
                JobHandle scheduleBackHandle = RaycastCommand.ScheduleBatch(
                    allRaycastsBack, backHits, raycastBatchCount, prepareBackHandle);

                // combine handles
                JobHandle frontBackHandle = JobHandle.CombineDependencies(scheduleFrontHandle, scheduleBackHandle);

                // process results and put into current cell index
                ProcessHits processHits = new ProcessHits
                {
                    FrontHits = frontHits,
                    BackHits  = backHits,
                    Results   = allResults.Slice(i, 1),
                };

                JobHandle cellHandle = processHits.Schedule(frontBackHandle);
                cellHandle.Complete();

                rayLengths.Dispose();
                allRaycastsFront.Dispose();
                allRaycastsBack.Dispose();
                frontHits.Dispose();
                backHits.Dispose();
            } // for each cell

            // final distances
            CompareDistances compareDistances = new CompareDistances
            {
                Distances = distances,
                Results   = allResults
            };

            JobHandle compareDistancesHandle = compareDistances.Schedule(_settings.CellCount, compareBatchCount);
            compareDistancesHandle.Complete();

            stopwatch.Stop();
            Debug.Log("SDF bake completed in " + stopwatch.Elapsed.ToString("mm\\:ss\\.ff"));
#if UNITY_EDITOR
            EditorUtility.ClearProgressBar();
#endif
            float[] distancesOut = new float[_settings.CellCount];
            distances.CopyTo(distancesOut);

            // cleanup all the temp arrays
            distances.Dispose();
            allResults.Dispose();
            sphereSamples.Dispose();
            // randomDirections.Dispose();
            volumePlanes.Dispose();

            foreach (var c in geoFront)
            {
                Object.DestroyImmediate(c.gameObject);
            }
            foreach (var c in geoBack)
            {
                Object.DestroyImmediate(c.gameObject);
            }

            // NOTE do not use max distance, instead use aabbMagnitude so distance fields are interchangeable
            bakeComplete?.Invoke(this, distancesOut, aabbMagnitude, passthrough);
        }
Example #19
0
        private static void SpawnCrestActionPoint()
        {
            LewdCrestXPlugin.Logger.LogDebug("Spawning crest action point");

            if (_iconOff == null)
            {
                _iconOff = (LewdCrestXPlugin.Bundle.LoadAsset <Texture2D>("action_icon_crest_off") ??
                            throw new Exception("asset not found - action_icon_crest_off")).ToSprite();
                Object.DontDestroyOnLoad(_iconOff);
            }

            if (_iconOn == null)
            {
                _iconOn = (LewdCrestXPlugin.Bundle.LoadAsset <Texture2D>("action_icon_crest_on") ??
                           throw new Exception("asset not found - action_icon_crest_on")).ToSprite();
                Object.DontDestroyOnLoad(_iconOn);
            }

            var inst   = CommonLib.LoadAsset <GameObject>("map/playeractionpoint/00.unity3d", "PlayerActionPoint_05", true);
            var parent = GameObject.Find("Map/ActionPoints");

            inst.transform.SetParent(parent.transform, true);

            var pap               = inst.GetComponentInChildren <PlayerActionPoint>();
            var iconRootObject    = pap.gameObject;
            var iconRootTransform = pap.transform;

            Object.DestroyImmediate(pap, false);

            // position above the small table
            iconRootTransform.position = new Vector3(-3.1f, -0.4f, 1.85f);

            var evt          = iconRootObject.AddComponent <TriggerEnterExitEvent>();
            var animator     = iconRootObject.GetComponentInChildren <Animator>();
            var rendererIcon = iconRootObject.GetComponentInChildren <SpriteRenderer>();

            rendererIcon.sprite = _iconOff;
            var playerInRange = false;

            evt.onTriggerEnter += c =>
            {
                if (!c.CompareTag("Player"))
                {
                    return;
                }
                playerInRange = true;
                animator.Play("icon_action");
                rendererIcon.sprite = _iconOn;
                c.GetComponent <Player>().actionPointList.Add(evt);
            };
            evt.onTriggerExit += c =>
            {
                if (!c.CompareTag("Player"))
                {
                    return;
                }
                playerInRange = false;
                animator.Play("icon_stop");
                rendererIcon.sprite = _iconOff;
                c.GetComponent <Player>().actionPointList.Remove(evt);
            };

            var player = LewdCrestXGameController.GetActionScene().Player;

            evt.UpdateAsObservable()
            .Subscribe(_ =>
            {
                // Hide in H scenes and other places
#if KK
                var isVisible = Game.IsInstance() && !Game.instance.IsRegulate(true);
#else
                var isVisible = !Game.IsRegulate(true);
#endif
                if (rendererIcon.enabled != isVisible)
                {
                    rendererIcon.enabled = isVisible;
                }

                // Check if player clicked this point
                if (isVisible && playerInRange && ActionInput.isAction && !player.isActionNow)
                {
                    ClubInterface.ShowWindow = true;
                }
            })
            .AddTo(evt);
            evt.OnGUIAsObservable()
            .Subscribe(ClubInterface.OnGui)
            .AddTo(evt);
        }
Example #20
0
        // ----------------------------------------------------------------------------
        // fix missing component
        // ----------------------------------------------------------------------------

        private static bool FixMissingComponents(GameObjectIssueRecord issue, GameObject go, bool alternative)
        {
            var touched = false;

#if UNITY_2019_1_OR_NEWER
            var removedCount = GameObjectUtility.RemoveMonoBehavioursWithMissingScript(go);
            if (removedCount > 0)
            {
                touched = true;
            }
#else
            if (!alternative)
            {
                CSObjectTools.SelectGameObject(go, issue.Location == RecordLocation.Scene);
            }

            var tracker = CSEditorTools.GetActiveEditorTrackerForSelectedObject();
            if (tracker == null)
            {
                Debug.LogError(Maintainer.ConstructError("Can't get active tracker."));
                return(false);
            }
            tracker.RebuildIfNecessary();

            var activeEditors = tracker.activeEditors;
            for (var i = activeEditors.Length - 1; i >= 0; i--)
            {
                var editor = activeEditors[i];
                if (editor.serializedObject.targetObject == null)
                {
                    Object.DestroyImmediate(editor.target, true);
                    touched = true;
                }
            }

            if (alternative)
            {
                return(touched);
            }

            if (!touched)
            {
                // missing script could be hidden with hide flags, so let's try select it directly and repeat
                var serializedObject = new SerializedObject(go);
                var componentsArray  = serializedObject.FindProperty("m_Component");
                if (componentsArray != null)
                {
                    for (var i = componentsArray.arraySize - 1; i >= 0; i--)
                    {
                        var componentPair   = componentsArray.GetArrayElementAtIndex(i);
                        var nestedComponent = componentPair.FindPropertyRelative("component");
                        if (nestedComponent != null)
                        {
                            if (MissingReferenceDetector.IsPropertyHasMissingReference(nestedComponent))
                            {
                                var instanceId = nestedComponent.objectReferenceInstanceIDValue;
                                if (instanceId == 0)
                                {
                                    var fileId = nestedComponent.FindPropertyRelative("m_FileID");
                                    if (fileId != null)
                                    {
                                        instanceId = fileId.intValue;
                                    }
                                }

                                Selection.instanceIDs = new [] { instanceId };
                                touched |= FixMissingComponents(issue, go, true);
                            }
                        }
                        else
                        {
                            Debug.LogError(Maintainer.LogPrefix + "Couldn't find component in component pair!");
                            break;
                        }
                    }

                    if (touched)
                    {
                        CSObjectTools.SelectGameObject(go, issue.Location == RecordLocation.Scene);
                    }
                }
                else
                {
                    Debug.LogError(Maintainer.LogPrefix + "Couldn't find components array!");
                }
            }
#endif
            if (touched)
            {
                if (issue.Location == RecordLocation.Scene)
                {
                    CSSceneTools.MarkSceneDirty();
                }
                else
                {
                    EditorUtility.SetDirty(go);
                }
            }

            return(touched);
        }
Example #21
0
        public static Texture2D GenerateModel(Transform model, int width = 64, int height = 64)
        {
            if (model == null || model.Equals(null))
            {
                return(null);
            }

            Texture2D result = null;

            Transform previewObject;

            previewObject = Object.Instantiate(model, null, false);
            previewObject.gameObject.hideFlags = HideFlags.HideAndDontSave;

            SceneManager.MoveGameObjectToScene(previewObject.gameObject, m_Scene);
            previewObject.transform.position = Vector3.zero;

            bool wasActive = previewObject.gameObject.activeSelf;
            var  prevPos   = previewObject.position;
            var  prevRot   = previewObject.rotation;

            try
            {
                SetupCamera();
                SetLayerRecursively(previewObject);

                if (!wasActive)
                {
                    previewObject.gameObject.SetActive(true);
                }

                var previewDir = previewObject.rotation * m_previewDirection;

                renderersList.Clear();
                previewObject.GetComponentsInChildren(renderersList);

                var  previewBounds = new Bounds();
                bool init          = false;
                for (int i = 0; i < renderersList.Count; i++)
                {
                    if (!renderersList[i].enabled)
                    {
                        continue;
                    }

                    if (!init)
                    {
                        previewBounds = renderersList[i].bounds;
                        init          = true;
                    }
                    else
                    {
                        previewBounds.Encapsulate(renderersList[i].bounds);
                    }
                }

                if (!init)
                {
                    return(null);
                }

                boundsCenter = previewBounds.center;
                var boundsExtents = previewBounds.extents;
                var boundsSize    = 2f * boundsExtents;

                aspect = (float)width / height;
                renderCamera.aspect             = aspect;
                renderCamera.transform.rotation = Quaternion.LookRotation(previewDir, previewObject.up);

                float distance;
                if (OrthographicMode)
                {
                    renderCamera.transform.position = boundsCenter;

                    minX = minY = Mathf.Infinity;
                    maxX = maxY = Mathf.NegativeInfinity;

                    var point = boundsCenter + boundsExtents;
                    ProjectBoundingBoxMinMax(point);
                    point.x -= boundsSize.x;
                    ProjectBoundingBoxMinMax(point);
                    point.y -= boundsSize.y;
                    ProjectBoundingBoxMinMax(point);
                    point.x += boundsSize.x;
                    ProjectBoundingBoxMinMax(point);
                    point.z -= boundsSize.z;
                    ProjectBoundingBoxMinMax(point);
                    point.x -= boundsSize.x;
                    ProjectBoundingBoxMinMax(point);
                    point.y += boundsSize.y;
                    ProjectBoundingBoxMinMax(point);
                    point.x += boundsSize.x;
                    ProjectBoundingBoxMinMax(point);

                    distance = boundsExtents.magnitude + 1f;
                    renderCamera.orthographicSize = (1f + m_padding * 2f) * Mathf.Max(maxY - minY, (maxX - minX) / aspect) * 0.5f;
                }
                else
                {
                    projectionPlaneHorizontal = new ProjectionPlane(renderCamera.transform.up, boundsCenter);
                    projectionPlaneVertical   = new ProjectionPlane(renderCamera.transform.right, boundsCenter);

                    maxDistance = Mathf.NegativeInfinity;

                    var point = boundsCenter + boundsExtents;
                    CalculateMaxDistance(point);
                    point.x -= boundsSize.x;
                    CalculateMaxDistance(point);
                    point.y -= boundsSize.y;
                    CalculateMaxDistance(point);
                    point.x += boundsSize.x;
                    CalculateMaxDistance(point);
                    point.z -= boundsSize.z;
                    CalculateMaxDistance(point);
                    point.x -= boundsSize.x;
                    CalculateMaxDistance(point);
                    point.y += boundsSize.y;
                    CalculateMaxDistance(point);
                    point.x += boundsSize.x;
                    CalculateMaxDistance(point);

                    distance = (1f + m_padding * 2f) * Mathf.Sqrt(maxDistance);
                }

                renderCamera.transform.position = boundsCenter - previewDir * distance;
                renderCamera.farClipPlane       = distance * 4f;

                var temp      = RenderTexture.active;
                var renderTex = RenderTexture.GetTemporary(width, height, 16);
                RenderTexture.active = renderTex;

                if (TransparentBackground)
                {
                    GL.Clear(false, true, BackgroundColor);
                }

                renderCamera.targetTexture = renderTex;

                renderCamera.Render();
                renderCamera.targetTexture = null;

                result = new Texture2D(width, height, TransparentBackground ? TextureFormat.RGBA32 : TextureFormat.RGB24, false);
                result.ReadPixels(new Rect(0, 0, width, height), 0, 0, false);
                result.Apply(false, true);

                RenderTexture.active = temp;
                RenderTexture.ReleaseTemporary(renderTex);
            }
            catch (Exception e)
            {
                Debug.LogException(e);
            }
            finally
            {
                Object.DestroyImmediate(previewObject.gameObject);

                if (renderCamera == PreviewRenderCamera)
                {
                    cameraSetup.ApplySetup(renderCamera);
                }
            }

            return(result);
        }
 private void CleanupTestHeirarchy()
 {
     Object.DestroyImmediate(parent1Child1);
     Object.DestroyImmediate(parent1);
     Object.DestroyImmediate(root);
 }
Example #23
0
 protected void PlayerDataSchemaTestsTearDown()
 {
     Object.DestroyImmediate(m_BuildScript);
     EditorBuildSettings.scenes = m_ScenesBkp;
 }
        public void RenderPreviews()
        {
            UpdateShaders();
            UpdateTimedNodeList();

            PropagateNodeList(m_NodesToDraw, PropagationDirection.Downstream);
            m_NodesToDraw.UnionWith(m_TimedNodes);

            var time           = Time.realtimeSinceStartup;
            var timeParameters = new Vector4(time, Mathf.Sin(time), Mathf.Cos(time), 0.0f);

            foreach (var node in m_NodesToDraw)
            {
                if (node == null || !node.hasPreview || !node.previewExpanded)
                {
                    continue;
                }

                var renderData = GetRenderData(node.tempId);

                CollectShaderProperties(node, renderData);
                renderData.shaderData.mat.SetVector("_TimeParameters", timeParameters);

                if (renderData.shaderData.shader == null)
                {
                    renderData.texture = null;
                    renderData.NotifyPreviewChanged();
                    continue;
                }
                if (renderData.shaderData.hasError)
                {
                    renderData.texture = m_ErrorTexture;
                    renderData.NotifyPreviewChanged();
                    continue;
                }

                if (renderData.previewMode == PreviewMode.Preview2D)
                {
                    m_RenderList2D.Add(renderData);
                }
                else
                {
                    m_RenderList3D.Add(renderData);
                }
            }

            EditorUtility.SetCameraAnimateMaterialsTime(m_SceneResources.camera, time);

            m_SceneResources.light0.enabled            = true;
            m_SceneResources.light0.intensity          = 1.0f;
            m_SceneResources.light0.transform.rotation = Quaternion.Euler(50f, 50f, 0);
            m_SceneResources.light1.enabled            = true;
            m_SceneResources.light1.intensity          = 1.0f;
            m_SceneResources.camera.clearFlags         = CameraClearFlags.Color;

            // Render 2D previews
            m_SceneResources.camera.transform.position = -Vector3.forward * 2;
            m_SceneResources.camera.transform.rotation = Quaternion.identity;
            m_SceneResources.camera.orthographicSize   = 0.5f;
            m_SceneResources.camera.orthographic       = true;

            foreach (var renderData in m_RenderList2D)
            {
                RenderPreview(renderData, m_SceneResources.quad, Matrix4x4.identity);
            }

            // Render 3D previews
            m_SceneResources.camera.transform.position = -Vector3.forward * 5;
            m_SceneResources.camera.transform.rotation = Quaternion.identity;
            m_SceneResources.camera.orthographic       = false;

            foreach (var renderData in m_RenderList3D)
            {
                RenderPreview(renderData, m_SceneResources.sphere, Matrix4x4.identity);
            }

            var renderMasterPreview = masterRenderData != null && m_NodesToDraw.Contains(masterRenderData.shaderData.node);

            if (renderMasterPreview)
            {
                CollectShaderProperties(masterRenderData.shaderData.node, masterRenderData);

                if (m_NewMasterPreviewSize.HasValue)
                {
                    if (masterRenderData.renderTexture != null)
                    {
                        Object.DestroyImmediate(masterRenderData.renderTexture, true);
                    }
                    masterRenderData.renderTexture = new RenderTexture((int)m_NewMasterPreviewSize.Value.x, (int)m_NewMasterPreviewSize.Value.y, 16, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default)
                    {
                        hideFlags = HideFlags.HideAndDontSave
                    };
                    masterRenderData.renderTexture.Create();
                    masterRenderData.texture = masterRenderData.renderTexture;
                    m_NewMasterPreviewSize   = null;
                }
                var mesh             = m_Graph.previewData.serializedMesh.mesh ? m_Graph.previewData.serializedMesh.mesh :  m_SceneResources.sphere;
                var previewTransform = Matrix4x4.Rotate(m_Graph.previewData.rotation);
                var scale            = m_Graph.previewData.scale;
                previewTransform *= Matrix4x4.Scale(scale * Vector3.one * (Vector3.one).magnitude / mesh.bounds.size.magnitude);
                previewTransform *= Matrix4x4.Translate(-mesh.bounds.center);

                RenderPreview(masterRenderData, mesh, previewTransform);
            }

            m_SceneResources.light0.enabled = false;
            m_SceneResources.light1.enabled = false;

            foreach (var renderData in m_RenderList2D)
            {
                renderData.NotifyPreviewChanged();
            }
            foreach (var renderData in m_RenderList3D)
            {
                renderData.NotifyPreviewChanged();
            }
            if (renderMasterPreview)
            {
                masterRenderData.NotifyPreviewChanged();
            }

            m_RenderList2D.Clear();
            m_RenderList3D.Clear();
            m_NodesToDraw.Clear();
        }
Example #25
0
        public override GameObject Render(Renderer renderer, GameObject parentObject)
        {
            var go   = CreateSelf(renderer);
            var rect = go.GetComponent <RectTransform>();

            if (parentObject)
            {
                //親のパラメータがある場合、親にする 後のAnchor定義のため
                rect.SetParent(parentObject.transform);
            }

            var children = RenderChildren(renderer, go);

            var button = go.AddComponent <Button>();

            if (_button != null)
            {
                var type = _button.Get("transition");
                switch (type)
                {
                case "sprite-swap":
                    button.transition = Selectable.Transition.SpriteSwap;
                    break;

                case "color-tint":
                    button.transition = Selectable.Transition.ColorTint;
                    break;

                case "animation":
                    button.transition = Selectable.Transition.Animation;
                    break;

                case "none":
                    button.transition = Selectable.Transition.None;
                    break;

                default:
                    button.transition = Selectable.Transition.ColorTint;
                    break;
                }

                var targetImage = FindImageByClassName(children, _button.Get("target_graphic_class"));
                if (targetImage != null)
                {
                    button.targetGraphic = targetImage;
                }

                var spriteStateJson = _button.GetDic("sprite_state");
                if (spriteStateJson != null)
                {
                    var spriteState = new SpriteState();
                    var image       = FindImageByClassName(children, spriteStateJson.Get("highlighted_sprite_class"));
                    if (image != null)
                    {
                        spriteState.highlightedSprite = image.sprite;
                        Object.DestroyImmediate(image.gameObject);
                    }

                    image = FindImageByClassName(children, spriteStateJson.Get("pressed_sprite_class"));
                    if (image != null)
                    {
                        spriteState.pressedSprite = image.sprite;
                        Object.DestroyImmediate(image.gameObject);
                    }

                    image = FindImageByClassName(children, spriteStateJson.Get("selected_sprite_class"));
                    if (image != null)
                    {
                        spriteState.selectedSprite = image.sprite;
                        Object.DestroyImmediate(image.gameObject);
                    }

                    image = FindImageByClassName(children, spriteStateJson.Get("disabled_sprite_class"));
                    if (image != null)
                    {
                        spriteState.disabledSprite = image.sprite;
                        Object.DestroyImmediate(image.gameObject);
                    }

                    button.spriteState = spriteState;
                }
            }

            // TargetGraphicが設定されなかった場合
            if (button.targetGraphic == null)
            {
                // 子供からImage持ちを探す

                var image = go.GetComponentInChildren <Image>();
                if (image == null)
                {
                    // componentでないか探す
                    image = go.GetComponent <Image>();
                }

                button.targetGraphic = image;
            }

            SetAnchor(go, renderer);
            SetupComponents(go, componentsJson);
            return(go);
        }
 private void AllComplete()
 {
     Selection.activeGameObject = builder.RootRect.gameObject;
     Object.DestroyImmediate(builder.gameObject);
     builder = null;
 }
Example #27
0
        public static Texture2D GenerateModelPreviewWithShader(Transform model, Shader shader, string replacementTag, int width = 64, int height = 64, bool shouldCloneModel = false)
        {
            if (model == null || model.Equals(null))
            {
                return(null);
            }

            Texture2D result = null;

            if (!model.gameObject.scene.IsValid() || !model.gameObject.scene.isLoaded)
            {
                shouldCloneModel = true;
            }

            Transform previewObject;

            if (shouldCloneModel)
            {
                previewObject = (Transform)Object.Instantiate(model, null, false);
                previewObject.gameObject.hideFlags = HideFlags.HideAndDontSave;
            }
            else
            {
                previewObject = model;

                layersList.Clear();
                GetLayerRecursively(previewObject);
            }

            bool       isStatic  = IsStatic(model);
            bool       wasActive = previewObject.gameObject.activeSelf;
            Vector3    prevPos   = previewObject.position;
            Quaternion prevRot   = previewObject.rotation;

            try
            {
                SetupCamera();
                SetLayerRecursively(previewObject);

                if (!isStatic)
                {
                    previewObject.position = PREVIEW_POSITION;
                    previewObject.rotation = Quaternion.identity;
                }

                if (!wasActive)
                {
                    previewObject.gameObject.SetActive(true);
                }

                Vector3 previewDir = previewObject.rotation * m_previewDirection;

                renderersList.Clear();
                previewObject.GetComponentsInChildren(renderersList);

                Bounds previewBounds = new Bounds();
                bool   init          = false;
                for (int i = 0; i < renderersList.Count; i++)
                {
                    if (!renderersList[i].enabled)
                    {
                        continue;
                    }

                    if (!init)
                    {
                        previewBounds = renderersList[i].bounds;
                        init          = true;
                    }
                    else
                    {
                        previewBounds.Encapsulate(renderersList[i].bounds);
                    }
                }

                if (!init)
                {
                    return(null);
                }

                boundsCenter = previewBounds.center;
                Vector3 boundsExtents = previewBounds.extents;
                Vector3 boundsSize    = 2f * boundsExtents;

                aspect = (float)width / height;
                renderCamera.aspect             = aspect;
                renderCamera.transform.rotation = Quaternion.LookRotation(previewDir, previewObject.up);

#if DEBUG_BOUNDS
                boundsDebugCubes.Clear();
#endif

                float distance;
                if (m_orthographicMode)
                {
                    renderCamera.transform.position = boundsCenter;

                    minX = minY = Mathf.Infinity;
                    maxX = maxY = Mathf.NegativeInfinity;

                    Vector3 point = boundsCenter + boundsExtents;
                    ProjectBoundingBoxMinMax(point);
                    point.x -= boundsSize.x;
                    ProjectBoundingBoxMinMax(point);
                    point.y -= boundsSize.y;
                    ProjectBoundingBoxMinMax(point);
                    point.x += boundsSize.x;
                    ProjectBoundingBoxMinMax(point);
                    point.z -= boundsSize.z;
                    ProjectBoundingBoxMinMax(point);
                    point.x -= boundsSize.x;
                    ProjectBoundingBoxMinMax(point);
                    point.y += boundsSize.y;
                    ProjectBoundingBoxMinMax(point);
                    point.x += boundsSize.x;
                    ProjectBoundingBoxMinMax(point);

                    distance = boundsExtents.magnitude + 1f;
                    renderCamera.orthographicSize = (1f + m_padding * 2f) * Mathf.Max(maxY - minY, (maxX - minX) / aspect) * 0.5f;
                }
                else
                {
                    projectionPlaneHorizontal = new ProjectionPlane(renderCamera.transform.up, boundsCenter);
                    projectionPlaneVertical   = new ProjectionPlane(renderCamera.transform.right, boundsCenter);

                    maxDistance = Mathf.NegativeInfinity;

                    Vector3 point = boundsCenter + boundsExtents;
                    CalculateMaxDistance(point);
                    point.x -= boundsSize.x;
                    CalculateMaxDistance(point);
                    point.y -= boundsSize.y;
                    CalculateMaxDistance(point);
                    point.x += boundsSize.x;
                    CalculateMaxDistance(point);
                    point.z -= boundsSize.z;
                    CalculateMaxDistance(point);
                    point.x -= boundsSize.x;
                    CalculateMaxDistance(point);
                    point.y += boundsSize.y;
                    CalculateMaxDistance(point);
                    point.x += boundsSize.x;
                    CalculateMaxDistance(point);

                    distance = (1f + m_padding * 2f) * Mathf.Sqrt(maxDistance);
                }

                renderCamera.transform.position = boundsCenter - previewDir * distance;
                renderCamera.farClipPlane       = distance * 4f;

                RenderTexture temp      = RenderTexture.active;
                RenderTexture renderTex = RenderTexture.GetTemporary(width, height, 16);
                RenderTexture.active = renderTex;
                if (m_backgroundColor.a < 1f)
                {
                    GL.Clear(false, true, m_backgroundColor);
                }

                renderCamera.targetTexture = renderTex;

                if (shader == null)
                {
                    renderCamera.Render();
                }
                else
                {
                    renderCamera.RenderWithShader(shader, replacementTag == null ? string.Empty : replacementTag);
                }

                renderCamera.targetTexture = null;

                result = new Texture2D(width, height, m_backgroundColor.a < 1f ? TextureFormat.RGBA32 : TextureFormat.RGB24, false);
                result.ReadPixels(new Rect(0, 0, width, height), 0, 0, false);
                result.Apply(false, m_markTextureNonReadable);

                RenderTexture.active = temp;
                RenderTexture.ReleaseTemporary(renderTex);
            }
            catch (Exception e)
            {
                Debug.LogException(e);
            }
            finally
            {
#if DEBUG_BOUNDS
                for (int i = 0; i < boundsDebugCubes.Count; i++)
                {
                    Object.DestroyImmediate(boundsDebugCubes[i].gameObject);
                }

                boundsDebugCubes.Clear();
#endif

                if (shouldCloneModel)
                {
                    Object.DestroyImmediate(previewObject.gameObject);
                }
                else
                {
                    if (!wasActive)
                    {
                        previewObject.gameObject.SetActive(false);
                    }

                    if (!isStatic)
                    {
                        previewObject.position = prevPos;
                        previewObject.rotation = prevRot;
                    }

                    int index = 0;
                    SetLayerRecursively(previewObject, ref index);
                }

                if (renderCamera == m_previewRenderCamera)
                {
                    cameraSetup.ApplySetup(renderCamera);
                }
            }

            return(result);
        }
        private void BuildLegoUI(object data)
        {
            var selectRect = SelectGo.GetComponent <RectTransform>();

            if (selectRect == null)
            {
                EditorUtility.DisplayDialog(
                    "错误",
                    "乐高UI组件必须挂载在RectTransform组件下!",
                    "OK"
                    );

                return;
            }

            var uiId = (string)data;

            if (uiId.StartsWith("LegoView"))
            {
                if (SelectGo.GetComponentInParent <YuLegoViewHelper>() != null)
                {
                    EditorUtility.DisplayDialog(
                        "错误",
                        "乐高视图不允许嵌套挂载!",
                        "OK"
                        );

                    return;
                }
            }

            if (selectRect.name == uiId)
            {
                if (SelectGo.GetComponentInParent <YuLegoViewHelper>() != null)
                {
                    EditorUtility.DisplayDialog(
                        "错误",
                        "挂载父物体的名子和组件名不能相同!",
                        "OK"
                        );

                    return;
                }
            }

            var lowerId = uiId.ToLower();

            if (!Application.isPlaying)
            {
                var tempBuilders = Resources.FindObjectsOfTypeAll <LegoBuilder>();
                if (tempBuilders != null && tempBuilders.Length > 0)
                {
                    foreach (var b in tempBuilders)
                    {
                        Object.DestroyImmediate(b.gameObject);
                    }
                }

                var tempGo = new GameObject("TempBuilder");
                builder = tempGo.AddComponent <LegoBuilder>();
                var task = builder.CreateTask(lowerId, OnUiBuilded, selectRect, 1000, AllComplete);
                builder.PushSonTask(task);
                builder.StartBuild();
            }
            else
            {
                if (builder == null)
                {
                    builder = Injector.Instance.Get <LegoBuilder>();
                }

                var task = builder.CreateTask(lowerId, OnUiBuilded, selectRect, 1000);
                builder.PushSonTask(task);
                builder.StartBuild();
            }
        }
Example #29
0
        public static void SetObjectRef2Property(GameObject obj, string behaviourName, Assembly assembly,
                                                 List <IBind> processedMarks = null)
        {
            if (null == processedMarks)
            {
                processedMarks = new List <IBind>();
            }

            var uiMark    = obj.GetComponent <IBind>();
            var className = string.Empty;

            if (uiMark != null)
            {
                className = UIKitSettingData.GetProjectNamespace() + "." + uiMark.ComponentName;

                // 这部分
                if (uiMark.GetBindType() != BindType.DefaultUnityElement)
                {
                    var ptuimark = obj.GetComponent <UIMark>();
                    if (ptuimark != null)
                    {
                        Object.DestroyImmediate(ptuimark, true);
                    }
                }
            }
            else
            {
                className = UIKitSettingData.GetProjectNamespace() + "." + behaviourName;
            }

            var t = assembly.GetType(className);

            var com         = obj.GetComponent(t) ?? obj.AddComponent(t);
            var sObj        = new SerializedObject(com);
            var bindScripts = obj.GetComponentsInChildren <IBind>(true);

            foreach (var elementMark in bindScripts)
            {
                if (processedMarks.Contains(elementMark) || elementMark.GetBindType() == BindType.DefaultUnityElement)
                {
                    continue;
                }

                processedMarks.Add(elementMark);

                var uiType       = elementMark.ComponentName;
                var propertyName = string.Format("{0}", elementMark.Transform.gameObject.name);

                if (sObj.FindProperty(propertyName) == null)
                {
                    Log.I("sObj is Null:{0} {1} {2}", propertyName, uiType, sObj);
                    continue;
                }

                sObj.FindProperty(propertyName).objectReferenceValue = elementMark.Transform.gameObject;
                SetObjectRef2Property(elementMark.Transform.gameObject, elementMark.ComponentName, assembly, processedMarks);
            }

            var marks = obj.GetComponentsInChildren <IBind>(true);

            foreach (var elementMark in marks)
            {
                if (processedMarks.Contains(elementMark))
                {
                    continue;
                }

                processedMarks.Add(elementMark);

                var propertyName = elementMark.Transform.name;
                sObj.FindProperty(propertyName).objectReferenceValue = elementMark.Transform.gameObject;
            }

            sObj.ApplyModifiedPropertiesWithoutUndo();
        }
 public void TearDown()
 {
     Object.DestroyImmediate(m_TestObject);
 }