UnityEngine.Object.Destroy(UnityEngine.Object)

Here are the examples of the csharp api UnityEngine.Object.Destroy(UnityEngine.Object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

568 Examples 7

19 Source : ProfileTab.cs
with GNU General Public License v3.0
from Cytoid

public async void SetModel(FullProfile profile)
    {
        Profile = profile;
        characterTransitionElement.Leave(false, true);
        characterTransitionElement.enterDuration = 1.2f;
        characterTransitionElement.enterDelay = 0.4f;
        characterTransitionElement.onEnterStarted.SetListener(() =>
        {
            characterTransitionElement.enterDuration = 0.4f;
            characterTransitionElement.enterDelay = 0;
        });

        avatar.SetModel(profile.User);
        levelProgressImage.fillAmount = (profile.Exp.TotalExp - profile.Exp.CurrentLevelExp)
                                        / (profile.Exp.NextLevelExp - profile.Exp.CurrentLevelExp);
        uidText.text = profile.User.Uid;

        void MarkOffline()
        {
            statusCircleImage.color = "#757575".ToColor();
            statusText.text = "PROFILE_STATUS_OFFLINE".Get();
        }
        void MarkOnline()
        {
            statusCircleImage.color = "#47dc47".ToColor();
            statusText.text = "PROFILE_STATUS_ONLINE".Get();
        }
        if (profile.User.Uid == Context.OnlinePlayer.LastProfile?.User.Uid)
        {
            if (Context.IsOffline())
            {
                MarkOffline();
            }
            else
            {
                MarkOnline();
            }
        }
        else
        {
            if (profile.LastActive == null)
            {
                MarkOffline();
            }
            else
            {
                var lastActive = profile.LastActive.Value.LocalDateTime;
                if (DateTime.Now - lastActive <= TimeSpan.FromMinutes(30))
                {
                    MarkOnline();
                }
                else
                {
                    statusCircleImage.color = "#757575".ToColor();
                    statusText.text = "PROFILE_STATUS_LAST_SEEN_X".Get(lastActive.Humanize());
                }
            }
        }

        if (profile.Tier == null)
        {
            tierText.transform.parent.gameObject.SetActive(false);
        }
        else
        {
            tierText.transform.parent.gameObject.SetActive(true);
            tierText.text = profile.Tier.name;
            tierGradient.SetGradient(new ColorGradient(profile.Tier.colorPalette.background));
        }
        ratingText.text = $"{"PROFILE_WIDGET_RATING".Get()} {profile.Rating:0.00}";
        levelText.text = $"{"PROFILE_WIDGET_LEVEL".Get()} {profile.Exp.CurrentLevel}";
        expText.text = $"{"PROFILE_WIDGET_EXP".Get()} {(int) profile.Exp.TotalExp}/{(int) profile.Exp.NextLevelExp}";
        totalRankedPlaysText.text = profile.Activities.TotalRankedPlays.ToString("N0");
        totalClearedNotesText.text = profile.Activities.ClearedNotes.ToString("N0");
        highestMaxComboText.text = profile.Activities.MaxCombo.ToString("N0");
        avgRankedAccuracyText.text = ((profile.Activities.AverageRankedAccuracy ?? 0) * 100).ToString("0.00") + "%";
        totalRankedScoreText.text = (profile.Activities.TotalRankedScore ?? 0).ToString("N0");
        totalPlayTimeText.text = TimeSpan.FromSeconds(profile.Activities.TotalPlayTime)
            .Let(it => it.ToString(it.Days > 0 ? @"d\d\ h\h\ m\m\ s\s" : @"h\h\ m\m\ s\s"));

        chartRadioGroup.onSelect.SetListener(type => UpdateChart((ChartType) Enum.Parse(typeof(ChartType), type, true)));
        UpdateChart(ChartType.AvgRating);
        
        pillRows.ForEach(it => LayoutFixer.Fix(it));
        if (Context.IsOnline())
        {
            var eventBadges = profile.GetEventBadges();
            if (eventBadges.Any())
            {
                badgeGrid.gameObject.SetActive(true);
                badgeGrid.SetModel(eventBadges);
            }
            else
            {
                badgeGrid.gameObject.SetActive(false);
            }
        }

        foreach (Transform child in recordSection.recordCardHolder) Destroy(child.gameObject);
        foreach (Transform child in levelSection.levelCardHolder) Destroy(child.gameObject);
        foreach (Transform child in collectionSection.collectionCardHolder) Destroy(child.gameObject);

        if (profile.RecentRecords.Count > 0)
        {
            recordSection.gameObject.SetActive(true);
            foreach (var record in profile.RecentRecords.Take(6))
            {
                var recordCard = Instantiate(recordCardPrefab, recordSection.recordCardHolder);
                recordCard.SetModel(new RecordView{DisplayOwner = false, Record = record});
            }
        }
        else
        {
            recordSection.gameObject.SetActive(false);
        }

        if (profile.LevelCount > 0)
        {
            levelSection.gameObject.SetActive(true);
            foreach (var level in profile.Levels.Take(6))
            {
                var levelCard = Instantiate(levelCardPrefab, levelSection.levelCardHolder);
                levelCard.SetModel(new LevelView {DisplayOwner = false, Level = level.ToLevel(LevelType.User)});
            }

            viewAllLevelsButton.GetComponentInChildren<Text>().text = "PROFILE_VIEW_ALL_X".Get(profile.LevelCount);
            viewAllLevelsButton.onPointerClick.SetListener(_ =>
            {
                Context.ScreenManager.ChangeScreen(CommunityLevelSelectionScreen.Id, ScreenTransition.In, 0.4f,
                    transitionFocus: ((RectTransform) viewAllLevelsButton.transform).GetScreenSpaceCenter(),
                    payload: new CommunityLevelSelectionScreen.Payload
                        {
                            Query = new OnlineLevelQuery{owner = profile.User.Uid, category = "all", sort = "creation_date", order = "desc"},
                        });
            });
            if (profile.FeaturedLevelCount > 0)
            {
                viewAllFeaturedLevelsButton.gameObject.SetActive(true);
                viewAllFeaturedLevelsButton.GetComponentInChildren<Text>().text =
                    "PROFILE_VIEW_FEATURED_X".Get(profile.FeaturedLevelCount);
                viewAllFeaturedLevelsButton.onPointerClick.SetListener(_ =>
                {
                    Context.ScreenManager.ChangeScreen(CommunityLevelSelectionScreen.Id, ScreenTransition.In, 0.4f,
                        transitionFocus: ((RectTransform) viewAllFeaturedLevelsButton.transform).GetScreenSpaceCenter(),
                        payload: new CommunityLevelSelectionScreen.Payload
                        {
                            Query = new OnlineLevelQuery{owner = profile.User.Uid, category = "featured", sort = "creation_date", order = "desc"},
                        });
                });
            }
            else
            {
                viewAllFeaturedLevelsButton.gameObject.SetActive(false);
            }
            
            viewAllLevelsButton.transform.parent.RebuildLayout();
        }
        else
        {
            levelSection.gameObject.SetActive(false);
        }

        if (profile.CollectionCount > 0)
        {
            collectionSection.gameObject.SetActive(true);
            foreach (var collection in profile.Collections.Take(6))
            {
                var collectionCard = Instantiate(collectionCardPrefab, collectionSection.collectionCardHolder);
                collectionCard.SetModel(collection);
            }
        }
        else
        {
            collectionSection.gameObject.SetActive(false);
        }

        LayoutFixer.Fix(sectionParent);

        await UniTask.DelayFrame(5);
        
        transform.RebuildLayout();
        
        await UniTask.DelayFrame(0);
        
        characterTransitionElement.Enter();
    }

19 Source : TierCard.cs
with GNU General Public License v3.0
from Cytoid

public void SetModel(TierData tier)
    {
        Tier = tier;
        IsScrollRectFix = tier.isScrollRectFix;
        if (IsScrollRectFix)
        {
            foreach (Transform child in transform)
            {
                child.gameObject.SetActive(false);
            }
        }
        else
        {
            Index = tier.index;
            canvasGroup.alpha = 1f;
            foreach (Transform child in transform)
            {
                child.gameObject.SetActive(true);
            }

            active = true;
            screenCenter = this.GetScreenParent<TierSelectionScreen>().ScreenCenter;

            characterRoot.gameObject.SetActive(tier.Meta.character != null);
            if (tier.Meta.character != null)
            {
                characterDisplay.Load(Characterreplacedet.GetTachieBundleId(tier.Meta.character.replacedetId));
                characterDisplay.canvasGroup.alpha = 0;
            }

            gradientPane.SetModel(tier);

            for (var stage = 0; stage < Math.Min(3, tier.Meta.stages.Count); stage++)
            {
                stageCards[stage].SetModel(
                    tier.Meta.parsedStages[stage], 
                    new ColorGradient(tier.Meta.colorPalette.stages[stage], 90f)
                );
            }
            
            lockedOverlayRoot.SetActive(tier.locked || !tier.StagesValid);
            if (tier.locked)
            {
                lockedOverlayIcon.sprite = lockedIcon;
                lockedOverlayText.text = "TIER_LOCKED".Get();
            } 
            else if (!tier.StagesValid)
            {
                lockedOverlayIcon.sprite = unlockedIcon;
                lockedOverlayText.text = "TIER_NOT_DOWNLOADED".Get();
            }

            foreach (Transform child in criteriaHolder.transform) Destroy(child.gameObject);
            foreach (var criterion in tier.Meta.parsedCriteria)
            {
                var criterionEntry = Instantiate(criterionEntryPrefab, criteriaHolder.transform);
                criterionEntry.SetModel(criterion.Description, CriterionState.Preplaceded);
            }

            LayoutFixer.Fix(criteriaHolder.transform);
        }
    }

19 Source : LineRenderer.cs
with GNU General Public License v3.0
from Cytoid

public override void Dispose()
        { 
            Destroy(Line.gameObject);
        }

19 Source : NoteControllerRenderer.cs
with GNU General Public License v3.0
from Cytoid

public override void Dispose()
        {
            if (notePlaceholderTransform != null)
            {
                UnityEngine.Object.Destroy(notePlaceholderTransform.gameObject);
            }
            notePlaceholderTransform = null;
            noteGameObject = null;
        }

19 Source : SpriteRenderer.cs
with GNU General Public License v3.0
from Cytoid

public override void Dispose()
        {
            if (MainRenderer.SpritePathRefCount.ContainsKey(LoadPath))
            {
                MainRenderer.SpritePathRefCount[LoadPath]--;
                if (MainRenderer.SpritePathRefCount[LoadPath] == 0)
                {
                    Context.replacedetMemory.Disposereplacedet(LoadPath, replacedetTag.Storyboard);
                }
            }
            Destroy(Image.gameObject);
            Image = null;
        }

19 Source : TextRenderer.cs
with GNU General Public License v3.0
from Cytoid

public override void Dispose()
        {
            Destroy(Text.gameObject);
            Text = null;
        }

19 Source : AssetMemory.cs
with GNU General Public License v3.0
from Cytoid

public async UniTask<T> Loadreplacedet<T>(string path, replacedetTag tag, CancellationToken cancellationToken = default, 
        replacedetOptions options = default, bool useFileCacheOnly = false) where T : Object
    {
        if (!taggedMemoryCache.ContainsKey(tag)) taggedMemoryCache[tag] = new SimplePriorityQueue<Entry>();
        
        var suffix = "";
        if (typeof(T) == typeof(Sprite))
        {
            if (options != default)
            {
                if (options is SpritereplacedetOptions spriteOptions)
                {
                    suffix = $".{spriteOptions.FitCropSize[0]}.{spriteOptions.FitCropSize[1]}";
                }
            }
        }

        string variantPath;
        if (!path.StartsWith("file://"))
        {
            variantPath = "file://" + GetCacheFilePath(path) + suffix;
        }
        else
        {
            variantPath = path + suffix;
        }
        var variantExists = File.Exists(variantPath.Substring("file://".Length));
        
        var cachedreplacedet = GetCachedreplacedetEntry<T>(variantPath);
        if (cachedreplacedet != null)
        {
            if (PrintDebugMessages) Debug.Log($"replacedetMemory: Returning cached replacedet {variantPath}");
            cachedreplacedet.Tags.Add(tag);
            var taggedMemory = taggedMemoryCache[tag];
            if (taggedMemory.Contains(cachedreplacedet))
            {
                taggedMemory.UpdatePriority(cachedreplacedet, queuePriority++);
            }
            else
            {
                taggedMemory.Enqueue(cachedreplacedet, queuePriority++);
            }
            return cachedreplacedet.replacedet;
        }

        // Currently loading
        if (isLoading.Contains(path))
        {
            if (PrintDebugMessages) Debug.Log($"replacedetMemory: Already loading {path}. Waiting...");
            await UniTask.WaitUntil(() => !isLoading.Contains(path), cancellationToken: cancellationToken);
            if (PrintDebugMessages) Debug.Log($"replacedetMemory: Wait {path} complete.");
            
            return await Loadreplacedet<T>(path, tag, cancellationToken, options);
        }

        CheckIfExceedTagLimit(tag);

        if (PrintDebugMessages) Debug.Log($"replacedetMemory: Started loading {path} with variant {suffix}.");
        isLoading.Add(path);

        var time = DateTimeOffset.Now.ToUnixTimeMilliseconds();
        var loadPath = path;
        
        // Cache remote
        if (!path.StartsWith("file://"))
        {
            var cachePath = GetCacheFilePath(path);

            if (!File.Exists(cachePath))
            {
                if (!useFileCacheOnly)
                {
                    using (var request = UnityWebRequest.Get(path))
                    {
                        request.downloadHandler =
                            new DownloadHandlerFile(cachePath).Also(it => it.removeFileOnAbort = true);
                        await request.SendWebRequest();
                        if (cancellationToken != default && cancellationToken.IsCancellationRequested)
                        {
                            isLoading.Remove(path);
                            return default;
                        }

                        if (request.isNetworkError || request.isHttpError)
                        {
                            // TODO: Neo, fix your image CDN :)
                            if (request.responseCode != 422)
                            {
                                if (path.Contains("gravatar"))
                                {
                                    Debug.LogWarning($"replacedetMemory: Failed to download {path}");
                                    Debug.LogWarning(request.error);
                                }
                                else
                                {
                                    Debug.LogError($"replacedetMemory: Failed to download {path}");
                                    Debug.LogError(request.error);
                                }
                            }
                            isLoading.Remove(path);
                            return default;
                        }
                       
                        if (PrintDebugMessages) Debug.Log($"replacedetMemory: Saved {path} to {cachePath}");
                    }
                }
                else
                {
                    isLoading.Remove(path);
                    return default;
                }
            }

            if (PrintDebugMessages) Debug.Log($"replacedetMemory: Cached at {cachePath}");
            loadPath = "file://" + cachePath;
        }

        T replacedet = default;
        if (typeof(T) == typeof(Sprite))
        {
            // Fit crop
            loadPath = variantExists ? variantPath : loadPath;
            
            using (var request = UnityWebRequest.Get(loadPath))
            {
                await request.SendWebRequest();

                if (cancellationToken != default && cancellationToken.IsCancellationRequested)
                {
                    isLoading.Remove(path);
                    return default;
                }

                if (request.isNetworkError || request.isHttpError)
                {
                    // TODO: Neo, fix your image CDN :)
                    if (request.responseCode != 422)
                    {
                        Debug.LogError(
                            $"replacedetMemory: Failed to load {loadPath}");
                        Debug.LogError(request.error);
                        isLoading.Remove(path);
                        return default;
                    }
                }

                var bytes = request.downloadHandler.data;
                if (bytes == null)
                {
                    isLoading.Remove(path);
                    return default;
                }

                var texture = request.downloadHandler.data.ToTexture2D();
                texture.name = variantPath;
                
                // Fit crop
                if (!variantExists && options != default)
                {
                    if (!(options is SpritereplacedetOptions spriteOptions))
                    {
                        throw new ArgumentException();
                    }

                    if (texture.width != spriteOptions.FitCropSize[0] || texture.height != spriteOptions.FitCropSize[1])
                    {
                        var croppedTexture = TextureScaler.FitCrop(texture, spriteOptions.FitCropSize[0],
                            spriteOptions.FitCropSize[1]);
                        croppedTexture.name = variantPath;
                        Object.Destroy(texture);
                        texture = croppedTexture;
                        bytes = texture.EncodeToJPG();

                        var completed = false;
                        async void Task()
                        {
                            await UniTask.SwitchToThreadPool();
                            var cleanPath = variantPath.Substring("file://".Length);
                            Directory.CreateDirectory(Path.GetDirectoryName(cleanPath));
                            File.WriteAllBytes(cleanPath, bytes);
                            completed = true;
                        }
                        Task();
                        await UniTask.WaitUntil(() => completed);
                    }
                    else
                    {
                        var completed = false;
                        async void Task()
                        {
                            await UniTask.SwitchToThreadPool();
                            var cleanPath = variantPath.Substring("file://".Length);
                            Directory.CreateDirectory(Path.GetDirectoryName(cleanPath));
                            File.Copy(loadPath.Substring("file://".Length), cleanPath);
                            completed = true;
                        }
                        Task();
                        await UniTask.WaitUntil(() => completed);
                    }
                }

                var sprite = texture.CreateSprite();
                memoryCache[variantPath] = new SpriteEntry(variantPath, tag, sprite);
                replacedet = (T) Convert.ChangeType(sprite, typeof(T));
            }
        }
        else if (typeof(T) == typeof(AudioClip))
        {
            var loader = new AudioClipLoader(variantPath);
            await loader.Load();
            
            if (cancellationToken != default && cancellationToken.IsCancellationRequested)
            {
                isLoading.Remove(path);
                loader.Unload();
                return default;
            }
            
            if (loader.Error != null)
            {
                isLoading.Remove(path);
                Debug.LogError($"replacedetMemory: Failed to download audio from {variantPath}");
                Debug.LogError(loader.Error);
                return default;
            }

            var audioClip = loader.AudioClip;
            memoryCache[variantPath] = new AudioEntry(variantPath, tag, loader);
            replacedet = (T) Convert.ChangeType(audioClip, typeof(T));
        }
        
        taggedMemoryCache[tag].Enqueue(memoryCache[variantPath], queuePriority++);
        
        time = DateTimeOffset.Now.ToUnixTimeMilliseconds() - time;
        if (PrintDebugMessages) Debug.Log($"replacedetMemory: Loaded {variantPath} in {time}ms");

        isLoading.Remove(path);
        return replacedet;
    }

19 Source : VideoRenderer.cs
with GNU General Public License v3.0
from Cytoid

public override void Dispose()
        {
            Destroy(VideoPlayer.gameObject);
            Destroy(RawImage.gameObject);
            Destroy(RenderTexture);
        }

19 Source : AssetMemory.cs
with GNU General Public License v3.0
from Cytoid

public override void Dispose()
        {
            if (PrintDebugMessages) Debug.Log($"replacedetMemory: Disposed {Key} with tag {string.Join(",", Tags.Select(it => Enum.GetName(typeof(replacedetTag), it)))}");
            
            try
            {
                Object.Destroy(replacedet.texture);
                Object.Destroy(replacedet);
            }
            catch (Exception e)
            {
                Debug.LogWarning(e);
            }

            replacedet = null;
        }

19 Source : TapToPlace.cs
with MIT License
from dag10

private void Start()
        {
            // Make sure we have all the components in the scene we need.
            anchorManager = WorldAnchorManager.Instance;
            if (anchorManager == null)
            {
                Debug.LogError("This script expects that you have a WorldAnchorManager component in your scene.");
            }

            spatialMappingManager = SpatialMappingManager.Instance;
            if (spatialMappingManager == null)
            {
                Debug.LogError("This script expects that you have a SpatialMappingManager component in your scene.");
            }

            if (anchorManager != null && spatialMappingManager != null)
            {
                anchorManager.AttachAnchor(this.gameObject, SavedAnchorFriendlyName);
            }
            else
            {
                // If we don't have what we need to proceed, we may as well remove ourselves.
                Destroy(this);
            }
        }

19 Source : AudioSourcesReference.cs
with MIT License
from dag10

private void OnDestroy()
        {
            // AudioSourcesReference created all these components and nothing else should use them.
            foreach (AudioSource audioSource in audioSources)
            {
                Object.Destroy(audioSource);
            }

            audioSources = null;
        }

19 Source : DeleteLine.cs
with MIT License
from dag10

public void OnSelect()
    {
        var parent = gameObject.transform.parent.gameObject;
        if (parent != null)
        {
            Destroy(parent);
        }
    }

19 Source : LineDrawer.cs
with MIT License
from dag10

protected virtual void OnDestroy()
    {
        // Line renderer
        if (lineData != null)
        {
            if (lineData.Renderer != null)
            {
                Destroy(lineData.Renderer);
            }
            if (lineData.Filter != null)
            {
                Destroy(lineData.Filter);
            }
        }
        lineData = null;
    }

19 Source : AlignmentClient.cs
with MIT License
from dag10

[Client]
    private void ApplyAlignment(Vector3 position, float rotation)
    {
        if (isLocalPlayer && isClient)
        {
            alignmentManager.ApplyLocalAlignment(position, rotation);
            playerController.ApplyRelativeAlignment(position, rotation);
            Destroy(controllerTarget);
        }
    }

19 Source : ControllerHoverHighlight.cs
with MIT License
from dag10

private void OnRenderModelLoaded( SteamVR_RenderModel renderModel, bool success )
		{
			if ( renderModel != this.renderModel )
			{
				return;
			}

			Transform bodyTransform = transform.Find( "body" );
			if ( bodyTransform != null )
			{
				bodyMeshRenderer = bodyTransform.GetComponent<MeshRenderer>();
				bodyMeshRenderer.material = highLightMaterial;
				bodyMeshRenderer.enabled = false;
			}

			Transform trackingHatTransform = transform.Find( "trackhat" );
			if ( trackingHatTransform != null )
			{
				trackingHatMeshRenderer = trackingHatTransform.GetComponent<MeshRenderer>();
				trackingHatMeshRenderer.material = highLightMaterial;
				trackingHatMeshRenderer.enabled = false;
			}

			foreach ( Transform child in transform )
			{
				if ( ( child.name != "body" ) && ( child.name != "trackhat" ) )
				{
					Destroy( child.gameObject );
				}
			}

			renderModelLoaded = true;
		}

19 Source : DestroyOnDetachedFromHand.cs
with MIT License
from dag10

private void OnDetachedFromHand( Hand hand )
		{
			Destroy( gameObject );
		}

19 Source : DestroyOnParticleSystemDeath.cs
with MIT License
from dag10

private void CheckParticleSystem()
		{
			if ( !particles.IsAlive() )
			{
				Destroy( this.gameObject );
			}
		}

19 Source : ItemPackageSpawner.cs
with MIT License
from dag10

private void ClearPreview()
		{
			foreach ( Transform child in transform )
			{
				if ( Time.time > 0 )
				{
					GameObject.Destroy( child.gameObject );
				}
				else
				{
					GameObject.DestroyImmediate( child.gameObject );
				}
			}
		}

19 Source : SpatialMappingSource.cs
with MIT License
from dag10

protected void RemoveSurfaceObject(GameObject surface, bool removeAndDestroy = true)
        {
            // Remove it from our list
            for (int index = 0; index < SurfaceObjects.Count; index++)
            {
                if (SurfaceObjects[index].Object == surface)
                {
                    if (removeAndDestroy)
                    {
                        Destroy(SurfaceObjects[index].Object);
                    }
                    SurfaceObjects.RemoveAt(index);
                    break;
                }
            }
        }

19 Source : SpatialMappingSource.cs
with MIT License
from dag10

protected void Cleanup()
        {
            for (int index = 0; index < SurfaceObjects.Count; index++)
            {
                Destroy(SurfaceObjects[index].Object);
            }
            SurfaceObjects.Clear();
        }

19 Source : SteamVR_LaserPointer.cs
with MIT License
from dag10

void Start ()
    {
        holder = new GameObject();
        holder.transform.parent = this.transform;
        holder.transform.localPosition = Vector3.zero;
		holder.transform.localRotation = Quaternion.idenreplacedy;

		pointer = GameObject.CreatePrimitive(PrimitiveType.Cube);
        pointer.transform.parent = holder.transform;
        pointer.transform.localScale = new Vector3(thickness, thickness, 100f);
        pointer.transform.localPosition = new Vector3(0f, 0f, 50f);
		pointer.transform.localRotation = Quaternion.idenreplacedy;
		BoxCollider collider = pointer.GetComponent<BoxCollider>();
        if (addRigidBody)
        {
            if (collider)
            {
                collider.isTrigger = true;
            }
            Rigidbody rigidBody = pointer.AddComponent<Rigidbody>();
            rigidBody.isKinematic = true;
        }
        else
        {
            if(collider)
            {
                Object.Destroy(collider);
            }
        }
        Material newMaterial = new Material(Shader.Find("Unlit/Color"));
        newMaterial.SetColor("_Color", color);
        pointer.GetComponent<MeshRenderer>().material = newMaterial;
	}

19 Source : ComplexThrowable.cs
with MIT License
from dag10

private bool PhysicsDetach( Hand hand )
		{
			int i = holdingHands.IndexOf( hand );

			if ( i != -1 )
			{
				// Detach this object from the hand
				holdingHands[i].DetachObject( this.gameObject, false );

				// Allow the hand to do other things
				holdingHands[i].HoverUnlock( null );

				// Delete any existing joints from the hand
				if ( attachMode == AttachMode.FixedJoint )
				{
					Destroy( holdingHands[i].GetComponent<FixedJoint>() );
				}

				Util.FastRemove( holdingHands, i );
				Util.FastRemove( holdingBodies, i );
				Util.FastRemove( holdingPoints, i );

				return true;
			}

			return false;
		}

19 Source : Hand.cs
with MIT License
from dag10

private void UpdateDebugText()
		{
			if ( showDebugText )
			{
				if ( debugText == null )
				{
					debugText = new GameObject( "_debug_text" ).AddComponent<TextMesh>();
					debugText.fontSize = 120;
					debugText.characterSize = 0.001f;
					debugText.transform.parent = transform;

					debugText.transform.localRotation = Quaternion.Euler( 90.0f, 0.0f, 0.0f );
				}

				if ( GuessCurrentHandType() == HandType.Right )
				{
					debugText.transform.localPosition = new Vector3( -0.05f, 0.0f, 0.0f );
					debugText.alignment = TextAlignment.Right;
					debugText.anchor = TextAnchor.UpperRight;
				}
				else
				{
					debugText.transform.localPosition = new Vector3( 0.05f, 0.0f, 0.0f );
					debugText.alignment = TextAlignment.Left;
					debugText.anchor = TextAnchor.UpperLeft;
				}

				debugText.text = string.Format(
					"Hovering: {0}\n" +
					"Hover Lock: {1}\n" +
					"Attached: {2}\n" +
					"Total Attached: {3}\n" +
					"Type: {4}\n",
					( hoveringInteractable ? hoveringInteractable.gameObject.name : "null" ),
					hoverLocked,
					( currentAttachedObject ? currentAttachedObject.name : "null" ),
					attachedObjects.Count,
					GuessCurrentHandType().ToString() );
			}
			else
			{
				if ( debugText != null )
				{
					Destroy( debugText.gameObject );
				}
			}
		}

19 Source : ItemPackageSpawner.cs
with MIT License
from dag10

private void ItemPackageNotValid()
		{
			Debug.LogError( "ItemPackage replacedigned to " + gameObject.name + " is not valid. Destroying this game object." );
			Destroy( gameObject );
		}

19 Source : SpawnAndAttachAfterControllerIsTracking.cs
with MIT License
from dag10

void Update()
		{
			if ( itemPrefab != null )
			{
				if ( hand.controller != null )
				{
					if ( hand.controller.hasTracking )
					{
						GameObject objectToAttach = GameObject.Instantiate( itemPrefab );
						objectToAttach.SetActive( true );
						hand.AttachObject( objectToAttach );
						hand.controller.TriggerHapticPulse( 800 );
						Destroy( gameObject );

						// If the player's scale has been changed the object to attach will be the wrong size.
						// To fix this we change the object's scale back to its original, pre-attach scale.
						objectToAttach.transform.localScale = itemPrefab.transform.localScale;
					}
				}
			}
		}

19 Source : Unparent.cs
with MIT License
from dag10

void Update()
		{
			if ( oldParent == null )
				Object.Destroy( gameObject );
		}

19 Source : Util.cs
with MIT License
from dag10

private IEnumerator Wait()
		{
			yield return new WaitForSeconds( triggerTime );
			timerActive = false;
			callback.Invoke();
			Destroy( this );
		}

19 Source : Arrow.cs
with MIT License
from dag10

public void ArrowReleased( float inputVelocity )
		{
			inFlight = true;
			released = true;

			airReleaseSound.Play();

			if ( glintParticle != null )
			{
				glintParticle.Play();
			}

			if ( gameObject.GetComponentInChildren<FireSource>().isBurning )
			{
				fireReleaseSound.Play();
			}

			// Check if arrow is shot inside or too close to an object
			RaycastHit[] hits = Physics.SphereCastAll( transform.position, 0.01f, transform.forward, 0.80f, Physics.DefaultRaycastLayers, QueryTriggerInteraction.Ignore );
			foreach ( RaycastHit hit in hits )
			{
				if ( hit.collider.gameObject != gameObject && hit.collider.gameObject != arrowHeadRB.gameObject && hit.collider != Player.instance.headCollider )
				{
					Destroy( gameObject );
					return;
				}
			}

			travelledFrames = 0;
			prevPosition = transform.position;
			prevRotation = transform.rotation;
			prevHeadPosition = arrowHeadRB.transform.position;
			prevVelocity = GetComponent<Rigidbody>().velocity;

			Destroy( gameObject, 30 );
		}

19 Source : Arrow.cs
with MIT License
from dag10

private void StickInTarget( Collision collision, bool bSkipRayCast )
		{
			Vector3 prevForward = prevRotation * Vector3.forward;

			// Only stick in target if the collider is front of the arrow head
			if ( !bSkipRayCast )
			{
				RaycastHit[] hitInfo;
				hitInfo = Physics.RaycastAll( prevHeadPosition - prevVelocity * Time.deltaTime, prevForward, prevVelocity.magnitude * Time.deltaTime * 2.0f );
				bool properHit = false;
				for ( int i = 0; i < hitInfo.Length; ++i )
				{
					RaycastHit hit = hitInfo[i];

					if ( hit.collider == collision.collider )
					{
						properHit = true;
						break;
					}
				}

				if ( !properHit )
				{
					return;
				}
			}

			Destroy( glintParticle );

			inFlight = false;

			shaftRB.velocity = Vector3.zero;
			shaftRB.angularVelocity = Vector3.zero;
			shaftRB.isKinematic = true;
			shaftRB.useGravity = false;
			shaftRB.transform.GetComponent<BoxCollider>().enabled = false;

			arrowHeadRB.velocity = Vector3.zero;
			arrowHeadRB.angularVelocity = Vector3.zero;
			arrowHeadRB.isKinematic = true;
			arrowHeadRB.useGravity = false;
			arrowHeadRB.transform.GetComponent<BoxCollider>().enabled = false;

			hitTargetSound.Play();


			// If the hit item has a parent, dock an empty object to that
			// this fixes an issue with scaling hierarchy. I suspect this is not sustainable for a large object / scaling hierarchy.
			scaleParentObject = new GameObject( "Arrow Scale Parent" );
			Transform parentTransform = collision.collider.transform;

			// Don't do this for weebles because of how it has a fixed joint
			ExplosionWobble wobble = collision.collider.gameObject.GetComponent<ExplosionWobble>();
			if ( !wobble )
			{
				if ( parentTransform.parent )
				{
					parentTransform = parentTransform.parent;
				}
			}

			scaleParentObject.transform.parent = parentTransform;

			// Move the arrow to the place on the target collider we were expecting to hit prior to the impact itself knocking it around
			transform.parent = scaleParentObject.transform;
			transform.rotation = prevRotation;
			transform.position = prevPosition;
			transform.position = collision.contacts[0].point - transform.forward * ( 0.75f - ( Util.RemapNumberClamped( prevVelocity.magnitude, 0f, 10f, 0.0f, 0.1f ) + Random.Range( 0.0f, 0.05f ) ) );
		}

19 Source : Arrow.cs
with MIT License
from dag10

void OnDestroy()
		{
			if ( scaleParentObject != null )
			{
				Destroy( scaleParentObject );
			}
		}

19 Source : ArrowHand.cs
with MIT License
from dag10

private GameObject InstantiateArrow()
		{
			GameObject arrow = Instantiate( arrowPrefab, arrowNockTransform.position, arrowNockTransform.rotation ) as GameObject;
			arrow.name = "Bow Arrow";
			arrow.transform.parent = arrowNockTransform;
			Util.ResetTransform( arrow.transform );

			arrowList.Add( arrow );

			while ( arrowList.Count > maxArrowCount )
			{
				GameObject oldArrow = arrowList[0];
				arrowList.RemoveAt( 0 );
				if ( oldArrow )
				{
					Destroy( oldArrow );
				}
			}

			return arrow;
		}

19 Source : Balloon.cs
with MIT License
from dag10

void Update()
		{
			if ( ( destructTime != 0 ) && ( Time.time > destructTime ) )
			{
				if ( burstOnLifetimeEnd )
				{
					SpawnParticles( lifetimeEndParticlePrefab, lifetimeEndSound );
				}

				Destroy( gameObject );
			}
		}

19 Source : Balloon.cs
with MIT License
from dag10

private void ApplyDamage()
		{
			SpawnParticles( popPrefab, null );
			Destroy( gameObject );
		}

19 Source : BalloonColliders.cs
with MIT License
from dag10

void OnDisable()
		{
			for ( int i = 0; i < colliders.Length; ++i )
			{
				if ( colliders[i] != null )
				{
					Destroy( colliders[i].GetComponent<FixedJoint>() );

					colliders[i].SetActive( false );
				}
			}
		}

19 Source : BalloonColliders.cs
with MIT License
from dag10

void OnDestroy()
		{
			for ( int i = 0; i < colliders.Length; ++i )
			{
				Destroy( colliders[i] );
			}
		}

19 Source : FireSource.cs
with MIT License
from dag10

void Update()
		{
			if ( ( burnTime != 0 ) && ( Time.time > ( ignitionTime + burnTime ) ) && isBurning )
			{
				isBurning = false;
				if ( customParticles != null )
				{
					customParticles.Stop();
				}
				else
				{
					Destroy( fireObject );
				}
			}
		}

19 Source : TeleportArc.cs
with MIT License
from dag10

private void CreateLineRendererObjects()
		{
			//Destroy any existing line renderer objects
			if ( arcObjectsTransfrom != null )
			{
				Destroy( arcObjectsTransfrom.gameObject );
			}

			GameObject arcObjectsParent = new GameObject( "ArcObjects" );
			arcObjectsTransfrom = arcObjectsParent.transform;
			arcObjectsTransfrom.SetParent( this.transform );

			//Create new line renderer objects
			lineRenderers = new LineRenderer[segmentCount];
			for ( int i = 0; i < segmentCount; ++i )
			{
				GameObject newObject = new GameObject( "LineRenderer_" + i );
				newObject.transform.SetParent( arcObjectsTransfrom );

				lineRenderers[i] = newObject.AddComponent<LineRenderer>();

				lineRenderers[i].receiveShadows = false;
				lineRenderers[i].reflectionProbeUsage = UnityEngine.Rendering.ReflectionProbeUsage.Off;
				lineRenderers[i].lightProbeUsage = UnityEngine.Rendering.LightProbeUsage.Off;
				lineRenderers[i].shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
				lineRenderers[i].material = material;
#if (UNITY_5_4)
				lineRenderers[i].SetWidth( thickness, thickness );
#else
				lineRenderers[i].startWidth = thickness;
				lineRenderers[i].endWidth = thickness;
#endif
				lineRenderers[i].enabled = false;
			}
		}

19 Source : DirectionIndicator.cs
with MIT License
from dag10

public void OnDestroy()
        {
            GameObject.Destroy(DirectionIndicatorObject);
        }

19 Source : DirectionIndicator.cs
with MIT License
from dag10

private GameObject InstantiateDirectionIndicator(GameObject directionIndicator)
        {
            if (directionIndicator == null)
            {
                return null;
            }

            GameObject indicator = Instantiate(directionIndicator);

            // Set local variables for the indicator.
            directionIndicatorDefaultRotation = indicator.transform.rotation;
            directionIndicatorRenderer = indicator.GetComponent<Renderer>();

            // Start with the indicator disabled.
            directionIndicatorRenderer.enabled = false;

            // Remove any colliders and rigidbodies so the indicators do not interfere with Unity's physics system.
            foreach (Collider collider in indicator.GetComponents<Collider>())
            {
                Destroy(collider);
            }

            foreach (Rigidbody rigidBody in indicator.GetComponents<Rigidbody>())
            {
                Destroy(rigidBody);
            }

            Material indicatorMaterial = directionIndicatorRenderer.material;
            indicatorMaterial.color = DirectionIndicatorColor;
            indicatorMaterial.SetColor("_TintColor", DirectionIndicatorColor);

            return indicator;
        }

19 Source : DestroyOnTriggerEnter.cs
with MIT License
from dag10

void OnTriggerEnter( Collider collider )
		{
			if ( !useTag || ( useTag && collider.gameObject.tag == tagFilter ) )
			{
				Destroy( collider.gameObject.transform.root.gameObject );
			}
		}

19 Source : Teleport.cs
with MIT License
from dag10

void Start()
		{
			teleportMarkers = GameObject.FindObjectsOfType<TeleportMarkerBase>();

			HidePointer();

			player = InteractionSystem.Player.instance;

			if ( player == null )
			{
				Debug.LogError( "Teleport: No Player instance found in map." );
				Destroy( this.gameObject );
				return;
			}

			CheckForSpawnPoint();

			Invoke( "ShowTeleportHint", 5.0f );
		}

19 Source : SteamVR_ControllerManager.cs
with MIT License
from dag10

private void ShowObject(Transform t, string name)
	{
		var hidden = t.parent;
		if (hidden.gameObject.name != name)
			return;
		t.parent = hidden.parent;
		Destroy(hidden.gameObject);
	}

19 Source : SteamVR_LoadLevel.cs
with MIT License
from dag10

IEnumerator LoadLevel()
	{
		// Optionally rotate loading screen transform around the camera into view.
		// We replacedume here that the loading screen is already facing toward the origin,
		// and that the progress bar transform (if any) is a child and will follow along.
		if (loadingScreen != null && loadingScreenDistance > 0.0f)
		{
			// Wait until we have tracking.
			var hmd = SteamVR_Controller.Input((int)OpenVR.k_unTrackedDeviceIndex_Hmd);
			while (!hmd.hasTracking)
				yield return null;

			var tloading = hmd.transform;
			tloading.rot = Quaternion.Euler(0.0f, tloading.rot.eulerAngles.y, 0.0f);
			tloading.pos += tloading.rot * new Vector3(0.0f, 0.0f, loadingScreenDistance);

			var t = loadingScreenTransform != null ? loadingScreenTransform : transform;
			t.position = tloading.pos;
			t.rotation = tloading.rot;
		}

		_active = this;

		SteamVR_Events.Loading.Send(true);

		// Calculate rate for fading in loading screen and progress bar.
		if (loadingScreenFadeInTime > 0.0f)
		{
			fadeRate = 1.0f / loadingScreenFadeInTime;
		}
		else
		{
			alpha = 1.0f;
		}

		var overlay = OpenVR.Overlay;

		// Optionally create our loading screen overlay.
		if (loadingScreen != null && overlay != null)
		{
			loadingScreenOverlayHandle = GetOverlayHandle("loadingScreen", loadingScreenTransform != null ? loadingScreenTransform : transform, loadingScreenWidthInMeters);
			if (loadingScreenOverlayHandle != OpenVR.k_ulOverlayHandleInvalid)
			{
				var texture = new Texture_t();
				texture.handle = loadingScreen.GetNativeTexturePtr();
				texture.eType = SteamVR.instance.textureType;
				texture.eColorSpace = EColorSpace.Auto;
				overlay.SetOverlayTexture(loadingScreenOverlayHandle, ref texture);
			}
		}

		bool fadedForeground = false;

		// Fade out to compositor
		SteamVR_Events.LoadingFadeOut.Send(fadeOutTime);

		// Optionally set a skybox to use as a backdrop in the compositor.
		var compositor = OpenVR.Compositor;
		if (compositor != null)
		{
			if (front != null)
			{
				SteamVR_Skybox.SetOverride(front, back, left, right, top, bottom);

				// Explicitly fade to the compositor since loading will cause us to stop rendering.
				compositor.FadeGrid(fadeOutTime, true);
				yield return new WaitForSeconds(fadeOutTime);
			}
			else if (backgroundColor != Color.clear)
			{
				// Otherwise, use the specified background color.
				if (showGrid)
				{
					// Set compositor background color immediately, and start fading to it.
					compositor.FadeToColor(0.0f, backgroundColor.r, backgroundColor.g, backgroundColor.b, backgroundColor.a, true);
					compositor.FadeGrid(fadeOutTime, true);
					yield return new WaitForSeconds(fadeOutTime);
				}
				else
				{
					// Fade the foreground color in (which will blend on top of the scene), and then cut to the compositor.
					compositor.FadeToColor(fadeOutTime, backgroundColor.r, backgroundColor.g, backgroundColor.b, backgroundColor.a, false);
					yield return new WaitForSeconds(fadeOutTime + 0.1f);
					compositor.FadeGrid(0.0f, true);
					fadedForeground = true;
				}
			}
		}

		// Now that we're fully faded out, we can stop submitting frames to the compositor.
		SteamVR_Render.pauseRendering = true;

		// Continue waiting for the overlays to fully fade in before continuing.
		while (alpha < 1.0f)
			yield return null;

		// Keep us from getting destroyed when loading the new level, otherwise this coroutine will get stopped prematurely.
		transform.parent = null;
		DontDestroyOnLoad(gameObject);

		if (!string.IsNullOrEmpty(internalProcessPath))
		{
			Debug.Log("Launching external application...");
			var applications = OpenVR.Applications;
			if (applications == null)
			{
				Debug.Log("Failed to get OpenVR.Applications interface!");
			}
			else
			{
				var workingDirectory = Directory.GetCurrentDirectory();
				var fullPath = Path.Combine(workingDirectory, internalProcessPath);
				Debug.Log("LaunchingInternalProcess");
				Debug.Log("ExternalAppPath = " + internalProcessPath);
				Debug.Log("FullPath = " + fullPath);
				Debug.Log("ExternalAppArgs = " + internalProcessArgs);
				Debug.Log("WorkingDirectory = " + workingDirectory);
				var error = applications.LaunchInternalProcess(fullPath, internalProcessArgs, workingDirectory);
				Debug.Log("LaunchInternalProcessError: " + error);
#if UNITY_EDITOR
				UnityEditor.EditorApplication.isPlaying = false;
#elif UNITY_STANDALONE
 
				System.Diagnostics.Process.GetCurrentProcess().Kill();
#endif
            }
        }
		else
		{
			var mode = loadAdditive ? UnityEngine.SceneManagement.LoadSceneMode.Additive : UnityEngine.SceneManagement.LoadSceneMode.Single;
			if (loadAsync)
			{
				Application.backgroundLoadingPriority = ThreadPriority.Low;
				async = UnityEngine.SceneManagement.SceneManager.LoadSceneAsync(levelName, mode);

				// Performing this in a while loop instead seems to help smooth things out.
				//yield return async;
				while (!async.isDone)
				{
					yield return null;
				}
			}
			else
			{
				UnityEngine.SceneManagement.SceneManager.LoadScene(levelName, mode);
			}
		}

		yield return null;

		System.GC.Collect();

		yield return null;

		Shader.WarmupAllShaders();

		// Optionally wait a short period of time after loading everything back in, but before we start rendering again
		// in order to give everything a change to settle down to avoid any hitching at the start of the new level.
		yield return new WaitForSeconds(postLoadSettleTime);

		SteamVR_Render.pauseRendering = false;

		// Fade out loading screen.
		if (loadingScreenFadeOutTime > 0.0f)
		{
			fadeRate = -1.0f / loadingScreenFadeOutTime;
		}
		else
		{
			alpha = 0.0f;
		}

		// Fade out to compositor
		SteamVR_Events.LoadingFadeIn.Send(fadeInTime);

		if (compositor != null)
		{
			// Fade out foreground color if necessary.
			if (fadedForeground)
			{
				compositor.FadeGrid(0.0f, false);
				compositor.FadeToColor(fadeInTime, 0.0f, 0.0f, 0.0f, 0.0f, false);
				yield return new WaitForSeconds(fadeInTime);
			}
			else
			{
				// Fade scene back in, and reset skybox once no longer visible.
				compositor.FadeGrid(fadeInTime, false);
				yield return new WaitForSeconds(fadeInTime);

				if (front != null)
				{
					SteamVR_Skybox.ClearOverride();
				}
			}
		}

		// Finally, stick around long enough for our overlays to fully fade out.
		while (alpha > 0.0f)
			yield return null;

		if (overlay != null)
		{
			if (progressBarOverlayHandle != OpenVR.k_ulOverlayHandleInvalid)
				overlay.HideOverlay(progressBarOverlayHandle);
			if (loadingScreenOverlayHandle != OpenVR.k_ulOverlayHandleInvalid)
				overlay.HideOverlay(loadingScreenOverlayHandle);
		}

		Destroy(gameObject);

		_active = null;

		SteamVR_Events.Loading.Send(false);
	}

19 Source : SteamVR_TrackedCamera.cs
with MIT License
from dag10

public ulong Release()
		{
			var result = videostream.Release();

			if (videostream.handle == 0)
			{
				Object.Destroy(_texture);
				_texture = null;
			}

			return result;
		}

19 Source : VisualizationJoint.cs
with MIT License
from Daimler

public void Destroy()
        {
            GameObject.Destroy(this.gameJoint);
        }

19 Source : DrawingUtils.cs
with MIT License
from Daimler

private static GameObject DrawPoint3D(Vector3 position, Color color, float scale = 0.01f)
        {
            GameObject point = GameObject.CreatePrimitive(PrimitiveType.Sphere);
            point.transform.localScale = new Vector3(scale, scale, scale);
            point.transform.position = position;
            point.GetComponent<Renderer>().material.color = color;
            GameObject.Destroy(point.GetComponent<Collider>());
            return point;
        }

19 Source : DrawingUtils.cs
with MIT License
from Daimler

private static GameObject DrawPoint2D(Vector2 position, Color color, float scale = 0.01f)
        {
            GameObject point = GameObject.CreatePrimitive(PrimitiveType.Sphere);
            point.transform.localScale = new Vector3(scale, scale, scale);
            point.transform.position = new Vector3(position.x, scale / 2f, position.y);
            point.GetComponent<Renderer>().material.color = color;
            GameObject.Destroy(point.GetComponent<Collider>());
            return point;
        }

19 Source : LocalCoSimulation.cs
with MIT License
from Daimler

protected override void HandleDrawingCalls(MSimulationResult mmuResult, MMUContainer instance)
        {

            MainThreadDispatcher.Instance.ExecuteNonBlocking(() =>
            {


                try
                {
                    ////Draw the avatar
                    //if (instance.PostureDraw != null)
                    //{
                    //    GameObject.Destroy(instance.PostureDraw);
                    //}

                    //instance.PostureDraw = DrawingUtils.DrawAvatarPosture(mmuResult.Posture);
                    //instance.PostureDraw.name = instance.MMU.Name;

                    //Disable the history drawings
                    foreach (MotionTask task in instance.History)
                    {
                        if (task.Drawings != null)
                        {
                            foreach (GameObject obj in task.Drawings)
                                if (obj != null)
                                    obj.SetActive(false);
                        }
                    }


                    //Remove(disable all temporary drawings
                    if (!resetThisFrame)
                    {
                        for (int i = this.temporaryDrawings.Count - 1; i >= 0; i--)
                        {
                            this.temporaryDrawings[i].SetActive(false);
                            UnityEngine.Object.Destroy(this.temporaryDrawings[i]);
                            this.temporaryDrawings.RemoveAt(i);
                        }
                        resetThisFrame = true;
                    }



                    if (mmuResult.DrawingCalls == null)
                        return;

                    foreach (MDrawingCall drawingCall in mmuResult.DrawingCalls)
                    {
                        if (drawingCall == null)
                            continue;

                        GameObject drawingObject = null;

                        switch (drawingCall.Type)
                        {
                            case MDrawingCallType.DrawLine2D:
                                GameObject line2D = DrawingUtils.DrawLine2D(drawingCall.Data);
                                line2D.name = instance.MMU.Name + "_" + instance.CurrentTasks[0].Instruction.Name;
                                instance.CurrentTasks[0].Drawings.Add(line2D);

                                //replacedign the created object
                                drawingObject = line2D;

                                break;

                            case MDrawingCallType.DrawLine3D:
                                GameObject line3D = DrawingUtils.DrawLine3D(drawingCall.Data);
                                line3D.name = instance.MMU.Name + "_" + instance.CurrentTasks[0].Instruction.Name;
                                instance.CurrentTasks[0].Drawings.Add(line3D);

                                //replacedign the created object
                                drawingObject = line3D;

                                break;

                            case MDrawingCallType.DrawPoint3D:
                                GameObject point = DrawingUtils.DrawPoint(drawingCall.Data);
                                point.name = instance.MMU.Name + "_" + instance.CurrentTasks[0].Instruction.Name;
                                instance.CurrentTasks[0].Drawings.Add(point);

                                //replacedign the created object
                                drawingObject = point;
                                break;

                            case MDrawingCallType.DrawText:
                                GameObject label = new GameObject(instance.MMU.Name + "_" + instance.CurrentTasks[0].Instruction.Name);
                                TextMesh textMesh = label.AddComponent<TextMesh>();
                                label.transform.localPosition = new Vector3(0, 2.0f, 0);
                                label.transform.parent = this.avatar.transform;
                                label.transform.localScale = new Vector3(0.01f, 0.01f, 0.01f);
                                textMesh.fontSize = 100;

                                if (drawingCall.Properties.ContainsKey("Text"))
                                    textMesh.text = drawingCall.Properties["Text"];
                                else
                                    textMesh.text = instance.MMU.Name + "_" + instance.CurrentTasks[0].Instruction.Name;

                                instance.CurrentTasks[0].Drawings.Add(label);

                                //replacedign the created object
                                drawingObject = label;

                                break;

                        }


                        //Check if the drawing call has properties
                        if (drawingObject != null && drawingCall.Properties != null && drawingCall.Properties.ContainsKey("DrawingMode"))
                        {
                            if (drawingCall.Properties["DrawingMode"] == "Frame")
                            {
                                //Remove after next frame
                                this.temporaryDrawings.Add(drawingObject);
                            }
                        }
                    }
                }
                catch (System.Exception e)
                {
                    Debug.Log("Exception at handling drawing calls: " + e.Message + " " + e.StackTrace);
                }
            });
        }

19 Source : SubUIButtonLayoutGroup.cs
with Apache License 2.0
from DarkLop

protected void DestroyAllItems()
        {
            if (m_Items.Count > 0)
            {
                for (int i = 0; i < m_Items.Count; i++)
                {
                    GameObject.Destroy(m_Items[i].gameObject);
                }
                m_Items.Clear();
            }
        }

19 Source : ColorChart.cs
with Apache License 2.0
from DarkLop

public bool TryGetSwapTexture(Texture2D srcTexture, ColorChart srcChart, out Texture2D swapTexture)
        {
            swapTexture = null;
            if (srcTexture == null || srcChart == null)
            {
                return false;
            }

            // 动态创建没有命名,或动态把名称更改成了空。
            if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(srcTexture.name))
            {
                Debug.LogError("Name of SwapChart or Name of SrcTexture is null or empty.");
                return false;
            }

            // 尝试获取缓存Texture2D
            if (SwapTextureCache.TryGetTexture2D(name, srcTexture.name, out swapTexture))
            {
                return true;
            }

            // 获取源图所有颜色,并转换颜色
            Color[] colors = srcTexture.GetPixels();
            for (int i = 0; i < colors.Length; i++)
            {
                if (colors[i].a != 0)
                {
                    colors[i] = GetSwapColor(colors[i], srcChart);
                }                
            }

            // 和源相同的设置创建Texture2D
            Texture2D clone = new Texture2D(srcTexture.width, srcTexture.height)
            {
                alphaIsTransparency = srcTexture.alphaIsTransparency,
                wrapMode = srcTexture.wrapMode,
                filterMode = srcTexture.filterMode,
            };
            // 填充转换后的颜色,并保存
            clone.SetPixels(colors);
            clone.Apply();

            /// 如果加入缓存失败,销毁swapTexture,
            /// 重新尝试获取,
            /// 异步执行有极小的可能发生。
            if (!SwapTextureCache.AddTexture2D(name, srcTexture.name, clone))
            {
                Texture2D.Destroy(clone);
                return TryGetSwapTexture(srcTexture, srcChart, out swapTexture);
            }

            swapTexture = clone;
            return true;
        }

See More Examples