UnityEngine.Object.FindObjectsOfType()

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

58 Examples 7

19 Source : ClothFactory.cs
with GNU General Public License v3.0
from aelariane

public static string GetDebugInfo()
    {
        int num = 0;
        foreach (KeyValuePair<string, List<GameObject>> keyValuePair in ClothFactory.clothCache)
        {
            num += ClothFactory.clothCache[keyValuePair.Key].Count;
        }
        int num2 = 0;
        foreach (Cloth cloth in UnityEngine.Object.FindObjectsOfType<Cloth>())
        {
            bool enabled = cloth.enabled;
            if (enabled)
            {
                num2++;
            }
        }
        return string.Format("{0} cached cloths, {1} active cloths, {2} types cached", num, num2, ClothFactory.clothCache.Keys.Count);
    }

19 Source : Minimap.cs
with GNU General Public License v3.0
from aelariane

private void AutomaticSetCameraProperties(Camera cam)
    {
        Renderer[] array = FindObjectsOfType<Renderer>();
        bool flag = array.Length != 0;
        if (flag)
        {
            this.minimapOrthographicBounds = new Bounds(array[0].transform.position, Vectors.zero);
            for (int i = 0; i < array.Length; i++)
            {
                bool flag2 = array[i].gameObject.layer == 9;
                if (flag2)
                {
                    this.minimapOrthographicBounds.Encapsulate(array[i].bounds);
                }
            }
        }
        Vector3 size = this.minimapOrthographicBounds.size;
        float num = (size.x > size.z) ? size.x : size.z;
        size.z = (size.x = num);
        this.minimapOrthographicBounds.size = size;
        cam.orthographic = true;
        cam.orthographicSize = num * 0.5f;
        Vector3 center = this.minimapOrthographicBounds.center;
        center.y = cam.farClipPlane * 0.5f;
        Transform transform = cam.transform;
        transform.position = center;
        transform.eulerAngles = new Vector3(90f, 0f, 0f);
        cam.aspect = 1f;
        this.lastMinimapCenter = center;
        this.lastMinimapOrthoSize = cam.orthographicSize;
    }

19 Source : Minimap.cs
with GNU General Public License v3.0
from aelariane

private void AutomaticSetOrthoBounds()
    {
        Renderer[] array = UnityEngine.Object.FindObjectsOfType<Renderer>();
        bool flag = array.Length != 0;
        if (flag)
        {
            this.minimapOrthographicBounds = new Bounds(array[0].transform.position, Vectors.zero);
            for (int i = 0; i < array.Length; i++)
            {
                this.minimapOrthographicBounds.Encapsulate(array[i].bounds);
            }
        }
        Vector3 size = this.minimapOrthographicBounds.size;
        float num = (size.x > size.z) ? size.x : size.z;
        size.z = (size.x = num);
        this.minimapOrthographicBounds.size = size;
        this.lastMinimapCenter = this.minimapOrthographicBounds.center;
        this.lastMinimapOrthoSize = num * 0.5f;
    }

19 Source : ItemsManager.cs
with GNU General Public License v3.0
from Athlon007

void InitializeList()
        {
            // Find shopping bags in the list
            GameObject[] items = UnityEngine.Object.FindObjectsOfType<GameObject>()
                                .Where(gm => gm.name.ContainsAny(NameList) && gm.name.ContainsAny("(itemx)", "(Clone)") & gm.GetComponent<ItemBehaviour>() == null)
                                .ToArray();

            if (items.Length > 0)
            {
                for (int i = 0; i < items.Length; i++)
                {
                    if (items[i] == null) continue;

                    try
                    {
                        items[i].AddComponent<ItemBehaviour>();
                    }
                    catch { }
                }
            }

            // CD Player Enhanced compatibility
            if (ModLoader.GetMod("CDPlayer") != null)
            {
                GameObject[] cdEnchancedObjects = Resources.FindObjectsOfTypeAll<GameObject>()
                .Where(gm => gm.name.ContainsAny("cd case(itemy)", "CD Rack(itemy)", "cd(itemy)") && gm.activeSelf).ToArray();

                for (int i = 0; i < cdEnchancedObjects.Length; i++)
                {
                    cdEnchancedObjects[i].AddComponent<ItemBehaviour>();
                }

                // Create shop table check, for when the CDs are bought
                GameObject itemCheck = new GameObject("MOP_ItemAreaCheck");
                itemCheck.transform.localPosition = new Vector3(-1551.303f, 4.883998f, 1182.904f);
                itemCheck.transform.localEulerAngles = new Vector3(0f, 58.00043f, 0f);
                itemCheck.transform.localScale = new Vector3(1f, 1f, 1f);
                itemCheck.AddComponent<ShopModItemSpawnCheck>();
            }
            else
            {
                foreach (GameObject cd in Resources.FindObjectsOfTypeAll<GameObject>().Where(g => g.name.ContainsAny("cd case(item", "cd(item")).ToArray())
                    cd.AddComponent<ItemBehaviour>();
            }

            // Get items from ITEMS object.
            GameObject itemsObject = GameObject.Find("ITEMS");
            for (int i = 0; i < itemsObject.transform.childCount; i++)
            {
                GameObject item = itemsObject.transform.GetChild(i).gameObject;
                if (item.name == "CDs") continue;

                try
                {
                    if (item.GetComponent<ItemBehaviour>() != null)
                        continue;

                    item.AddComponent<ItemBehaviour>();
                }
                catch (System.Exception ex)
                {
                    ExceptionManager.New(ex, false, "ITEM_LIST_AT_ITEMS_LOAD_ERROR");
                }
            }

            // Also disable the restart for that sunnuva replaced.
            itemsObject.GetComponent<PlayMakerFSM>().Fsm.RestartOnEnable = false;

            // replaced wheels.
            foreach (GameObject wheel in UnityEngine.Object.FindObjectsOfType<GameObject>().Where(gm => gm.name.EqualsAny("wheel_regula", "wheel_offset") && gm.activeSelf).ToArray())
                wheel.AddComponent<ItemBehaviour>();

            // Tires trigger at Fleetari's.
            GameObject wheelTrigger = new GameObject("MOP_WheelTrigger");
            wheelTrigger.transform.localPosition = new Vector3(1555.49f, 4.8f, 737);
            wheelTrigger.transform.localEulerAngles = new Vector3(1.16f, 335, 1.16f);
            wheelTrigger.AddComponent<WheelRepairJobTrigger>();

            // Hook up the envelope.
            foreach (var g in Resources.FindObjectsOfTypeAll<GameObject>().Where(g => g.name.EqualsAny("envelope(xxxxx)", "lottery ticket(xxxxx)")).ToArray())
                g.AddComponent<ItemBehaviour>();

            // Unparent all childs of CDs object.
            Transform cds = GameObject.Find("ITEMS").transform.Find("CDs");
            if (cds)
            {
                for (int i = 0; i < cds.childCount; i++)
                    cds.GetChild(i).parent = null;
            }
        }

19 Source : LPConvert.cs
with MIT License
from BelkinAndrey

static void ConvertCircles()
    {
        foreach (CircleCollider2D circle in FindObjectsOfType<CircleCollider2D>())
        {
            GameObject ob = circle.gameObject;
            LPFixtureCircle lpcircle = Undo.AddComponent<LPFixtureCircle>(ob);

            CopyGeneric(circle, lpcircle);
            float mult = 1f;

            if (ob.transform.lossyScale.x != ob.transform.lossyScale.y)
            {
                if (ob.transform.lossyScale.x > ob.transform.lossyScale.y)
                {
                    mult = ob.transform.lossyScale.x / ob.transform.lossyScale.y;
                }
                else 
                {
                    mult = ob.transform.lossyScale.y / ob.transform.lossyScale.x;
                }
            }

            lpcircle.Radius = circle.radius*mult;

            Undo.DestroyObjectImmediate(circle);

            Setupdynamics(ob);
        }
    }

19 Source : LPConvert.cs
with MIT License
from BelkinAndrey

static void ConvertBoxes()
    {
        foreach (BoxCollider2D Box in FindObjectsOfType<BoxCollider2D>())
        {
            GameObject ob = Box.gameObject;
            LPFixtureBox lpBox = Undo.AddComponent<LPFixtureBox>(ob);

            lpBox.Size = Box.size ;
            CopyGeneric(Box, lpBox);

            Undo.DestroyObjectImmediate(Box);

            Setupdynamics(ob);
        }
    }

19 Source : LPConvert.cs
with MIT License
from BelkinAndrey

static void ConvertEdges()
    {
        foreach (EdgeCollider2D Edge in FindObjectsOfType<EdgeCollider2D>())
        {
            GameObject ob = Edge.gameObject;
            LPFixtureChainShape lpEdge = Undo.AddComponent<LPFixtureChainShape>(ob);

            lpEdge.DefinePoints(LPShapeTools.Vec2ArrayToVec3Array(Edge.points));
            CopyGeneric(Edge, lpEdge);

            Undo.DestroyObjectImmediate(Edge);

            Setupdynamics(ob);
        }
    }

19 Source : LPConvert.cs
with MIT License
from BelkinAndrey

static void ConvertPolys()
    {
        foreach (PolygonCollider2D poly in FindObjectsOfType<PolygonCollider2D>())
        {
            GameObject ob = poly.gameObject;

            for (int i = 0; i < poly.pathCount; i++)
            {
                LPFixturePoly lppoly = Undo.AddComponent<LPFixturePoly>(ob);
                lppoly.DefinePoints(LPShapeTools.Vec2ArrayToVec3Array(poly.GetPath(i)));
                CopyGeneric(poly, lppoly);
            }

            Undo.DestroyObjectImmediate(poly);

            Setupdynamics(ob);
        }
    }

19 Source : LPManager.cs
with MIT License
from BelkinAndrey

void Awake() 
	{
		//Always turn off debug messages in a build (Debug.Log writes to a log file and costs performance)
		if ( !Application.isEditor && !Debug.isDebugBuild)
		{
			DebugMessages = false;
		}
		
		//Check for duplicate LPmanagers
		if(GameObject.FindObjectsOfType<LPManager>().Length > 1)
		{  
			Debug.LogError("There is more than one LiquidFunManager in your scene. There can be only one!");
		}
		else
		{
			//Create contact listener c# object
			ContactListener = new LPContactListener();
			//Create World
			worldPtr = LPAPIWorld.CreateWorld(Gravity.x,Gravity.y);
			if (DebugMessages) Debug.Log("World Created at: 0x" + worldPtr.ToInt64());
			
			//Initialise Contact Listener
			if (UseContactListener)
			{
				ContactListener.Initialise(worldPtr);
			}
			
			//Create bodies
			LPBody[] bodies = GameObject.FindObjectsOfType<LPBody>();
			foreach (LPBody bod in bodies) 
			{
				if (bod.SpawnOnPlay) 
				{
					bod.Initialise(this);
				}
            }
			if (DebugMessages) Debug.Log(bodies.Length + " Bodies created");
			
			//Create Joints
			foreach (LPJoint joint in GameObject.FindObjectsOfType<LPJoint>()) 
			{
				if (joint.GetType() != typeof(LPJointGear))
				{
                    if (joint.SpawnOnPlay)
                    {
                        joint.Initialise(this);
                    }
				}		
			}
			foreach (LPJoint joint in GameObject.FindObjectsOfType<LPJointGear>()) 
			{
                if (joint.SpawnOnPlay)
                {
                    joint.Initialise(this);
                }
			} 
			       
            //Create Particles
			ParticleSystems =  GameObject.FindObjectsOfType<LPParticleSystem>();
			for (int i = 0; i < ParticleSystems.Length; i++)
			{
				ParticleSystems[i].Initialise(worldPtr,DebugMessages,i);	
			}			
			//Set or Determine recommended number of particle iterations
			if (OverrideParticleIterations)
			{
				m_particleIterations = ParticleIterationsOverride;
			}
			else
			{
				m_particleIterations = LPAPIParticleSystems.GetParticleIterations(Gravity.magnitude,ParticleSystems[0].ParticleRadius,TimeStep);
				if (DebugMessages) Debug.Log("Recommended number of particle iterations is "+ m_particleIterations.ToString());
			}
        }
    }

19 Source : LPParticleSystem.cs
with MIT License
from BelkinAndrey

public void Initialise(IntPtr world, bool debug, int index)
    {
        lpMan = FindObjectOfType<LPManager>();
        if (Particles != null) Debug.Log(Particles.Count);
        Index = index;
        //PartSysPtr = LPAPIParticleSystems.CreateParticleSystem(world, ParticleRadius, Damping, GravityScale, Index);
        PartSysPtr = LPAPIParticleSystems.CreateParticleSystem2(world,ParticleRadius,Damping,GravityScale,Index,
        SurfaceTensionNormalStrenght,SurfaceTensionPressureStrenght,ViscousStrenght);
        LPAPIParticleSystems.SetDestructionByAge(PartSysPtr, DestroyByAgeAllowed);

        if (ParticleAmountLimit > 0)
        {
			LPAPIParticleSystems.SetMaxParticleCount(PartSysPtr,ParticleAmountLimit);
        }

		LPAPIParticleSystems.SetParticleSystemIndex(PartSysPtr,Index);

		if (debug)Debug.Log("Particle System Created at: 0x" + PartSysPtr.ToInt64());

        foreach (LPParticleGroup _shape in GameObject.FindObjectsOfType<LPParticleGroup>())
        {
            if (Index == _shape.ParticleSystemImIn && _shape.SpawnOnPlay)
            {
                _shape.Initialise(this);
            }
        }
        if (debug)Debug.Log(LPAPIParticleSystems.GetNumberOfParticles(PartSysPtr)+ " Particles created");
        Drawers = GetComponentsInChildren<LPDrawParticleSystem>();
        for (int i = 0; i < Drawers.Length; i++)
        {
            Drawers[i].Initialise(this);
        }

        particlesCountArray = new float[1];
        Particles = new List<LPParticle>();
        particleData = new float[0];
    }

19 Source : WorldContextsManager.cs
with Apache License 2.0
from bnoazx005

public void PrepareViews()
        {
            IDependencyInjector[] viewsInjectors = GameObject.FindObjectsOfType<DependencyInjector>();
            for (int i = 0; i < viewsInjectors.Length; ++i)
            {
                viewsInjectors[i]?.Init();
            }
        }

19 Source : CleanerGameMode.cs
with GNU General Public License v2.0
from CheepYT

public void removeBody(byte bodyId)
        {
            foreach (var body in UnityEngine.Object.FindObjectsOfType<DeadBody>())
                if (body.ParentId == bodyId)
                {
                    body.gameObject.SetActive(false);
                    UnityEngine.Object.Destroy(body);
                }
        }

19 Source : CleanerGameMode.cs
with GNU General Public License v2.0
from CheepYT

private void SetOutline(byte bodyId, Color color, bool enabled)
        {
            float active = enabled ? 1 : 0;

            SpriteRenderer renderer = null;

            foreach (var body in UnityEngine.Object.FindObjectsOfType<DeadBody>())
                if (body.ParentId == bodyId)
                    renderer = body.GetComponent<SpriteRenderer>();

            renderer.material.SetFloat("_Outline", active);

            if (enabled)
                renderer.material.SetColor("_OutlineColor", color);
        }

19 Source : CleanerGameMode.cs
with GNU General Public License v2.0
from CheepYT

public override void Loop()
        {
            base.Loop();

            string add = $"\nCleaner Role: {Functions.ColorPurple}Active[]\n[]Clean Cooldown: {Functions.ColorPurple}{CleanCooldown}s";

            if (!CheepsAmongUsMod.CheepsAmongUsMod.SettingsAddition.Contains(add) && Enabled)
                CheepsAmongUsMod.CheepsAmongUsMod.SettingsAddition = CheepsAmongUsMod.CheepsAmongUsMod.SettingsAddition.Replace(prevAdd, "") + add;
            else if (CheepsAmongUsMod.CheepsAmongUsMod.SettingsAddition.Contains(prevAdd) && !Enabled)
                CheepsAmongUsMod.CheepsAmongUsMod.SettingsAddition = CheepsAmongUsMod.CheepsAmongUsMod.SettingsAddition.Replace(prevAdd, "");

            prevAdd = add;

            if (AllRolePlayers.Count == 0)
                return;

            var cleaner = AllRolePlayers.First();

            if (PlayerController.LocalPlayer.PlayerData.IsImpostor)
                cleaner.PlayerController.PlayerControl.nameText.Color = cleaner.NameColor;

            if (!cleaner.AmRolePlayer)
                return;

            if (CleanButtonSprite == null)
            {
                CleanButtonSprite = Functions.LoadSpriteFromreplacedemblyResource(replacedembly.GetExecutingreplacedembly(), "CleanerRoleGameMode.replacedets.clean.png"); // Load sprite

                KillSprite = PlayerHudManager.HudManager.KillButton.renderer.sprite;

                PlayerHudManager.HudManager.KillButton.renderer.sprite = CleanButtonSprite;
            }

            if (CleanStopwatch.Elapsed.TotalSeconds < CleanCooldown)
                PlayerHudManager.HudManager.KillButton.SetCoolDown(CleanCooldown - (float)CleanStopwatch.Elapsed.TotalSeconds, CleanCooldown);
            else
                PlayerHudManager.HudManager.KillButton.SetCoolDown(0, CleanCooldown);

            #region ---------- Manage Dead Body Target ----------
            var bodies = UnityEngine.Object.FindObjectsOfType<DeadBody>();

            DeadBody closest = null;

            #region ----- Find closest body -----
            foreach (var body in bodies)
            {
                try
                {
                    var distToObject = Vector2.Distance(body.transform.position, PlayerController.LocalPlayer.GameObject.transform.position);

                    var prevDist = float.MaxValue;

                    if(closest != null)
                        prevDist = Vector2.Distance(closest.transform.position, PlayerController.LocalPlayer.GameObject.transform.position);

                    if (distToObject < prevDist)
                    {
                        closest = body;
                    }
                }
                catch { }
            }
            #endregion

            #region ----- If distance too large, set target to null -----
            if(closest != null)
                if (Vector2.Distance(closest.transform.position, PlayerController.LocalPlayer.GameObject.transform.position) > CleanDistance)
                    closest = null;
            #endregion

            #region ----- Remove outline from previous target -----
            if (Patching.Patch_KillButtonManager_PerformKill.TargetId != byte.MaxValue)
            {
                if(closest == null || Patching.Patch_KillButtonManager_PerformKill.TargetId != closest.ParentId)
                    try
                    {
                        SetOutline(Patching.Patch_KillButtonManager_PerformKill.TargetId, Color.blue, false);
                    } catch { }
            }
            #endregion

            if (closest != null)
                Patching.Patch_KillButtonManager_PerformKill.TargetId = closest.ParentId; // update target
            else
                Patching.Patch_KillButtonManager_PerformKill.TargetId = byte.MaxValue;

            if (closest != null)
            {
                SetOutline(closest.ParentId, Color.blue, true); // set target outline
                PlayerHudManager.HudManager.KillButton.renderer.color = EnabledColor;
                PlayerHudManager.HudManager.KillButton.renderer.material.SetFloat("_Desat", 0f);
            } else
            {
                PlayerHudManager.HudManager.KillButton.renderer.color = DisabledColor;
                PlayerHudManager.HudManager.KillButton.renderer.material.SetFloat("_Desat", 1f);
            }
            #endregion

        }

19 Source : BattleRoyaleGameMode.cs
with GNU General Public License v2.0
from CheepYT

public override void OnStart()
        {
            base.OnStart();

            Task.Run(async () =>
            {
                await Task.Delay(2500);

                MaxPlayerCount = PlayerController.AllPlayerControls.Count;

                Started = true;
                LastKilled = 0;

                PlayerController.LocalPlayer.ClearTasks();

                #region ---------- Send Start Location ----------
                if (RandomStartLocation && CheepsAmongUsMod.CheepsAmongUsMod.IsDecidingClient && MapLocations.ContainsKey(GameOptions.Map))
                {
                    List<Vector2> Locations = new List<Vector2>(MapLocations[GameOptions.Map]);
                    System.Random rnd = new System.Random();

                    foreach (var player in PlayerController.AllPlayerControls)
                    {
                        if (Locations.Count == 0)
                            Locations.AddRange(MapLocations[GameOptions.Map]); // If there are not enough start locations, refill list

                        var location = Locations[rnd.Next(Locations.Count)];
                        Locations.Remove(location);

                        if (!player.IsLocalPlayer)
                        {
                            var writer = RpcManager.StartRpc(BattleRoyale.BattleRoyalRpc);
                            writer.Write((byte)BattleRoyale.CustomRpcCalls.SendStartLocation);
                            writer.Write(player.PlayerId);
                            writer.Write(location.x);
                            writer.Write(location.y);
                            writer.EndMessage();
                        } else
                        {
                            player.RpcSnapTo(location);
                        }
                    }
                }
                #endregion

                #region ---------- Open All Doors ----------
                await Task.Delay(2500);

                foreach (var door in UnityEngine.Object.FindObjectsOfType<DeconDoor>())
                    door.SetDoorway(true);
                #endregion

                LastKilled = Functions.GetUnixTime();
            });
        }

19 Source : InfiniteKillDistance.cs
with GNU General Public License v2.0
from CheepYT

public static void Postfix()
            {
                foreach (var obj in UnityEngine.Object.FindObjectsOfType<OptionBehaviour>())
                    if (obj.replacedle == StringNames.GameKillDistance)
                    {
                        StringOption option = new StringOption(obj.Pointer);

                        List<StringNames> StrNames = new List<StringNames>(option.Values);
                        StrNames.Add(StringNames.Accept);

                        option.Values = StrNames.ToArray();
                    }
            }

19 Source : InfiniteKillDistance.cs
with GNU General Public License v2.0
from CheepYT

public static void Postfix()
            {
                foreach (var obj in UnityEngine.Object.FindObjectsOfType<OptionBehaviour>())
                {
                    if (obj.replacedle == StringNames.GameKillDistance)
                    {
                        StringOption option = new StringOption(obj.Pointer);

                        if (option.Values[option.Value] == StringNames.Accept)
                            option.ValueText.Text = InfiniteName;
                    }
                }
            }

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

[TearDown]
        public static void TearDown()
        {
            GameObject[] gameObjectsInScene = GameObject.FindObjectsOfType<GameObject>()
                .Where(go => go.tag != "MainCamera").ToArray();

            foreach (GameObject obj in gameObjectsInScene)
            {
                GameObject.DestroyImmediate(obj, false);
            }
        }

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

protected void Find()
			{
				var marker = default(LeanMarker);

				if (instances.TryGetValue(name, out marker) == true)
				{
					Build(marker);

					return;
				}
				else
				{
					var markers = FindObjectsOfType<LeanMarker>();

					for (var i = markers.Length - 1; i >= 0; i--)
					{
						marker = markers[i];

						if (marker.name == name)
						{
							Build(marker);

							return;
						}
					}
				}

				throw new System.NullReferenceException("Failed to find LeanMarker in scene with name: " + name);
			}

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

public static void Install(bool silent = true)
        {
            string prefabPath = EditorConstants.PrefabPath;
            string messagereplacedle = Constants.PluginDisplayName;

            string objectName = Path.GetFileNameWithoutExtension(prefabPath);

            if (!silent && !Utils.ShowDialog(messagereplacedle, "This will create " + objectName + " (" + prefabPath + ") game object in your scene.\n\nYou only need to do it once for the very first scene of your game\n\nContinue?"))
            {
                return;
            }

            LunarConsole[] existing = GameObject.FindObjectsOfType<LunarConsole>();
            if (existing != null)
            {
                foreach (LunarConsole c in existing)
                {
                    GameObject.DestroyImmediate(c.gameObject);
                }
            }

            GameObject lunarConsolePrefab = replacedetDatabase.LoadreplacedetAtPath(prefabPath, typeof(GameObject)) as GameObject;
            if (lunarConsolePrefab == null)
            {
                if (!silent)
                {
                    Utils.ShowDialog(messagereplacedle, "Can't instantiate " + prefabPath + ": replacedet not found");
                }
                return;
            }

            GameObject lunarConsole = PrefabUtility.InstantiatePrefab(lunarConsolePrefab) as GameObject;
            lunarConsole.name = objectName;

            // starting Unity 5.3 we need to add an undo operation or the scene would not be marked dirty
            #if UNITY_5_3_OR_NEWER
            Undo.RegisterCreatedObjectUndo(lunarConsole, "Install Lunar Console");
            #endif

            if (!silent)
            {
                Utils.ShowDialog(messagereplacedle, objectName + " game object created!\n\nDon't forget to save your scene changes!", "OK");
            }
        }

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

public static void CullAllExcessDispatchers()
        {
            var dispatchers = GameObject.FindObjectsOfType<MainThreadDispatcher>();
            for (int i = 0; i < dispatchers.Length; i++)
            {
                DestroyDispatcher(dispatchers[i]);
            }
        }

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

public static async UniTask<DialogueHighlightTarget> Find(string id)
    {
        if (id.StartsWith("@"))
        {
            var lookup = id.Substring(1);
            switch (lookup)
            {
                case "LevelSelectionScreen/HighlightedLevelCard":
                    await UniTask.WaitUntil(() => Context.ScreenManager.ActiveScreen is LevelSelectionScreen);
                    await UniTask.DelayFrame(5);
                    var card = ((LevelSelectionScreen) Context.ScreenManager.ActiveScreen).scrollRect.content
                        .GetComponentsInChildren<LevelCard>()
                        .FirstOrDefault(it => it.Level.Id == LevelSelectionScreen.HighlightedLevelId);
                    if (card == null)
                    {
                        Debug.LogWarning($"Could not find LevelCard with ID {LevelSelectionScreen.HighlightedLevelId}");
                        return null;
                    }
                    return card.gameObject.GetComponent<DialogueHighlightTarget>();
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
        return FindObjectsOfType<DialogueHighlightTarget>().ToList().Find(it => it.id == id);
    }

19 Source : SteamVR_GazeTracker.cs
with MIT License
from dag10

void Update ()
    {
        // If we haven't set up hmdTrackedObject find what the user is looking at
        if (hmdTrackedObject == null)
        {
            SteamVR_TrackedObject[] trackedObjects = FindObjectsOfType<SteamVR_TrackedObject>();
            foreach (SteamVR_TrackedObject tracked in trackedObjects)
            {
                if (tracked.index == SteamVR_TrackedObject.EIndex.Hmd)
                {
                    hmdTrackedObject = tracked.transform;
                    break;
                }
            }
        }

        if (hmdTrackedObject)
        {
            Ray r = new Ray(hmdTrackedObject.position, hmdTrackedObject.forward);
            Plane p = new Plane(hmdTrackedObject.forward, transform.position);

            float enter = 0.0f;
            if (p.Raycast(r, out enter))
            {
                Vector3 intersect = hmdTrackedObject.position + hmdTrackedObject.forward * enter;
                float dist = Vector3.Distance(intersect, transform.position);
                //Debug.Log("Gaze dist = " + dist);
                if (dist < gazeInCutoff && !isInGaze)
                {
                    isInGaze = true;
                    GazeEventArgs e;
                    e.distance = dist;
                    OnGazeOn(e);
                }
                else if (dist >= gazeOutCutoff && isInGaze)
                {
                    isInGaze = false;
                    GazeEventArgs e;
                    e.distance = dist;
                    OnGazeOff(e);
                }
            }

        }

    }

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_ExternalCamera.cs
with MIT License
from dag10

void OnEnable()
	{
		// Move game view cameras to lower-right quadrant.
		cameras = FindObjectsOfType<Camera>() as Camera[];
		if (cameras != null)
		{
			var numCameras = cameras.Length;
			cameraRects = new Rect[numCameras];
			for (int i = 0; i < numCameras; i++)
			{
				var cam = cameras[i];
				cameraRects[i] = cam.rect;

				if (cam == this.cam)
					continue;

				if (cam.targetTexture != null)
					continue;

				if (cam.GetComponent<SteamVR_Camera>() != null)
					continue;

				cam.rect = new Rect(0.5f, 0.0f, 0.5f, 0.5f);
			}
		}

		if (config.sceneResolutionScale > 0.0f)
		{
			sceneResolutionScale = SteamVR_Camera.sceneResolutionScale;
			SteamVR_Camera.sceneResolutionScale = config.sceneResolutionScale;
		}
	}

19 Source : UnityMMUInstantiator.cs
with MIT License
from Daimler

public IMotionModelUnitDev InstantiateMMU(MMULoadingProperty mmuLoadingProperty)
        {

            Debug.Log("Calling Unity MMU instantiator " + mmuLoadingProperty.Path);

            MMUDescription mmuDescription = mmuLoadingProperty.Description;
            string filePath = mmuLoadingProperty.Path;

            //Check if the MMU supports the specified language
            if (mmuDescription.Language != "UnityC#" && mmuDescription.Language != "Unity")
                throw new NotSupportedException("MMU is not supported");

            //Skip if file path invalid
            if (filePath == null)
                throw new NullReferenceException("File path of MMU is null " + mmuDescription.Name);

            //Skip if the MMU has no dependencies
            if (mmuDescription.Dependencies.Count == 0)
                throw new Exception("No dependencies of MMU specified " + mmuDescription.Name);

            //Create a variable which hols the mmu
            IMotionModelUnitDev mmu = null;

            //Get the paths
            string folderPath = System.IO.Directory.GetParent(filePath).ToString();
            string replacedetBundlePath = folderPath + "\\" + mmuDescription.Dependencies[0].Name;


            //Perform on unity main thread
            MainThreadDispatcher.Instance.ExecuteBlocking(delegate
            {
                //To do in futre -> Create a new scene for each MMU
                //Scene scene = SceneManager.CreateScene("Scene" + mmuDescription.Name);
                //SceneManager.SetActiveScene(scene);

                //First load the resources
                replacedetBundle mmureplacedetBundle = null;
                try
                {
                    if (!mmuLoadingProperty.Data.ContainsKey(replacedetBundlePath))
                    {
                        mmureplacedetBundle = replacedetBundle.LoadFromFile(replacedetBundlePath);
                        if (mmureplacedetBundle == null)
                        {

                            MMICSharp.Adapter.Logger.Log(Log_level.L_ERROR, "Failed to load replacedetBundle! replacedetBundle is null!" + mmuDescription.Name);
                            return;
                        }

                        mmuLoadingProperty.Data.Add(replacedetBundlePath, mmureplacedetBundle);
                    }
                    else
                    {
                        mmureplacedetBundle = mmuLoadingProperty.Data[replacedetBundlePath] as replacedetBundle;
                    }
                }
                catch (Exception e)
                {
                    MMICSharp.Adapter.Logger.Log(Log_level.L_ERROR, "Cannot load replacedet bundle: " + mmuDescription.Name + " " + e.Message);
                    return;
                }

                GameObject prefab = null;
                try
                {
                    prefab = mmureplacedetBundle.Loadreplacedet<GameObject>(mmuDescription.Name);
                }
                catch (Exception e)
                {
                    MMICSharp.Adapter.Logger.Log(Log_level.L_ERROR, "Cannot load prefab: " + mmuDescription.Name + " " + e.Message);
                }

                GameObject mmuObj = null;

                try
                {
                    mmuObj = GameObject.Instantiate(prefab);
                }
                catch (Exception e)
                {
                    MMICSharp.Adapter.Logger.Log(Log_level.L_ERROR, "Cannot instantiate prefab: " + mmuDescription.Name + " " + e.Message);
                }

                try
                {
                    replacedembly replacedembly = replacedembly.LoadFile(filePath);

                    //Find the clreplaced type which implements the IMotionModelInterface
                    Type clreplacedType = replacedembly.GetTypes().ToList().Find(s => s.GetInterfaces().Contains(typeof(IMotionModelUnitDev)));
                    if (clreplacedType != null)
                    {
                        //Add the script to the game object
                        mmu = mmuObj.AddComponent(clreplacedType) as IMotionModelUnitDev;

                        ///Loading and replacedigning the configuration file
                        if (mmuObj.GetComponent<UnityMMUBase>() != null)
                        {
                            MMICSharp.Adapter.Logger.Log(Log_level.L_DEBUG, $"MMU {mmuDescription.Name} implements the UnityMMUBase");

                            //Get the UnityMMUBse interface
                            UnityMMUBase mmuBase = mmuObj.GetComponent<UnityMMUBase>();

                            //By default set the configuration file path and define it globally
                            string avatarConfigFilePath = AppDomain.CurrentDomain.BaseDirectory + "/" + "avatar.mos";

                            //Check if the MMU has a custom configuration file
                            if (this.GetLocalAvatarConfigurationFile(folderPath, out string localConfigFilePath))
                            {
                                //Setting the local avatar as reference for retargeting
                                MMICSharp.Adapter.Logger.Log(Log_level.L_DEBUG, $"Local avatar configuration was found: {mmuDescription.Name} ({avatarConfigFilePath}).");

                                //Set to the utilized path
                                avatarConfigFilePath = localConfigFilePath;
                            }

                           
                            //Further perform a check whether the file is available at all
                            if (System.IO.File.Exists(avatarConfigFilePath))
                            {
                                mmuBase.ConfigurationFilePath = avatarConfigFilePath;
                                MMICSharp.Adapter.Logger.Log(Log_level.L_DEBUG, $"Setting the configuration file path for loading the avatar of {mmuDescription.Name} to {avatarConfigFilePath}");
                            }

                            //Problem in here -> File is obviously not available
                            else
                            {
                                MMICSharp.Adapter.Logger.Log(Log_level.L_ERROR, $"Problem setting the configuration file path for loading the avatar of {mmuDescription.Name} to {avatarConfigFilePath}. File not available.");
                            }
                        }

                    }
                    else
                    {
                        MMICSharp.Adapter.Logger.Log(Log_level.L_ERROR, "Cannot instantiate MMU: " + mmuDescription.Name);
                    }
                }
                catch (Exception e)
                {
                    MMICSharp.Adapter.Logger.Log(Log_level.L_ERROR, "Problem at instantiating clreplaced of MMU: " + mmuDescription.Name + " " + e.Message + " " + e.StackTrace);
                }
                

                //Disable all renderers in the scene
                foreach (Renderer renderer in GameObject.FindObjectsOfType<Renderer>())
                    renderer.enabled = false;

            });

         


            return mmu;
        }

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

[MenuItem("GameObject/SRPG/Map Graph", priority = -1)]
        public static MapGraph CreateMapGraphGameObject()
        {
            MapGraph mapGraph = new GameObject("MapGraph", typeof(Grid)).AddComponent<MapGraph>();

            GameObject tilemapBg = new GameObject("TilemapBackground", typeof(Tilemap), typeof(TilemapRenderer));
            tilemapBg.transform.SetParent(mapGraph.transform, false);

            Tilemap tilemapTerrain = new GameObject("Terrain", typeof(Tilemap), typeof(TilemapRenderer)).GetComponent<Tilemap>();
            tilemapTerrain.transform.SetParent(mapGraph.transform, false);
            mapGraph.terrainTilemap = tilemapTerrain;

            GameObject mapCursorPoolGo = new GameObject("MapCursor");
            mapCursorPoolGo.transform.SetParent(mapGraph.transform, false);

            mapCursorPoolGo.SetActive(false);
            {
                ObjectPool[] pools = GameObject.FindObjectsOfType<ObjectPool>()
                    .Where(p => p.poolName == mapCursorPoolGo.name || (p.poolName == string.Empty && p.name == mapCursorPoolGo.name))
                    .ToArray();
                ObjectPool mapCursorPool = mapCursorPoolGo.AddComponent<ObjectPool>();
                mapCursorPool.poolName = mapCursorPool.name + (pools.Length == 0 ? string.Empty : pools.Length.ToString());
                mapCursorPool.dontDestroy = false;
                mapGraph.mapCursorPool = mapCursorPool;
            }
            mapCursorPoolGo.SetActive(true);

            GameObject mapObjectPoolGo = new GameObject("MapObject");
            mapObjectPoolGo.transform.SetParent(mapGraph.transform, false);
            mapObjectPoolGo.SetActive(false);
            {
                ObjectPool[] pools = GameObject.FindObjectsOfType<ObjectPool>()
                    .Where(p => p.poolName == mapObjectPoolGo.name || (p.poolName == string.Empty && p.name == mapObjectPoolGo.name))
                    .ToArray();
                ObjectPool mapObjectPool = mapObjectPoolGo.AddComponent<ObjectPool>();
                mapObjectPool.poolName = mapObjectPool.name + (pools.Length == 0 ? string.Empty : pools.Length.ToString());
                mapObjectPool.dontDestroy = false;
                mapGraph.mapObjectPool = mapObjectPool;
            }
            mapObjectPoolGo.SetActive(true);

            GameObject tilemapfg = new GameObject("TilemapForeground", typeof(Tilemap), typeof(TilemapRenderer));
            tilemapfg.transform.SetParent(mapGraph.transform, false);

            Selection.activeObject = mapGraph;
            return mapGraph;
        }

19 Source : ClientOnly.cs
with MIT License
from deadgg

private static void OnServerStarted()
    {
        var components = FindObjectsOfType<ClientOnly>();

        for (var i = components.Length - 1; i >= 0; i--)
        {
            var component = components[i];

            if (component != null)
            {
                components[i].DeleteConditional();
            }
        }
    }

19 Source : ServerOnly.cs
with MIT License
from deadgg

private static void OnClientStarted()
    {
        var components = FindObjectsOfType<ServerOnly>();

        for (var i = components.Length - 1; i >= 0; i--)
        {
            var component = components[i];

            if (component != null)
            {
                components[i].DeleteConditional();
            }
        }
    }

19 Source : EntityManager.cs
with MIT License
from deadgg

public T[] FindAll<T>() where T : BaseEnreplacedy
        {
            return FindObjectsOfType<T>();
        }

19 Source : EntityManager.cs
with MIT License
from deadgg

private void AddSceneEnreplacedies()
        {
            var enreplacedies = FindObjectsOfType<BaseEnreplacedy>();

            foreach (var enreplacedy in enreplacedies)
            {
                if (enreplacedy.EnreplacedyId == 0)
                {
                    if (Zapnet.Network.IsServer)
                    {
                        var prefab = enreplacedy.NetworkPrefab;

                        if (prefab != null)
                        {
                            var prefabName = prefab.uniqueName;

                            enreplacedy.PrefabName = prefabName;
                            enreplacedy.PrefabId = Zapnet.Prefab.GetId(prefabName);
                            enreplacedy.EnreplacedyId = GetFreeId();

                            Add(enreplacedy);
                        }
                    }
                    else
                    {
                        Destroy(enreplacedy.gameObject);
                    }
                }
            }
        }

19 Source : Demo.cs
with MIT License
from harshitjuneja

private void Start()
    {
        m_animators = FindObjectsOfType<Animator>();
    }

19 Source : SavePlayModeChangesChecker.cs
with MIT License
from inkle

static GameObject[] GetGameObjectsToPersist () {
			var persist = Object.FindObjectsOfType<SavePlayModeChanges>();
			return persist.Where(x => x.IsValid()).Select(x => x.gameObject).ToArray();
		}

19 Source : IMLEditorManager.cs
with MIT License
from Interactml

private static void FindIMLComponents()
    {
        // Get all iml components in scene
        var componentsFound = Object.FindObjectsOfType<IMLComponent>();

        // If we found any components, try to subscribe them to the list
        if (componentsFound != null)
        {
            foreach (var component in componentsFound)
            {
                SubscribeIMLComponent(component);
            }

        }
    }

19 Source : IMLOutputToMalbersInput.cs
with MIT License
from Interactml

void Start()
    {
        // Initialise lists
        m_BirdsInputScripts = FindObjectsOfType<MalbersInput>().ToList<MalbersInput>();
    }

19 Source : RayTracer.cs
with Apache License 2.0
from jcowles

public void NotifySceneChanged() {
    // Setup the scene.
    var objects = GameObject.FindObjectsOfType<RayTracedSphere>();

    bool reallocate = false;
    if (m_sphereData == null || m_sphereData.Length != objects.Length) {
      m_sphereData = new Sphere[objects.Length];
      reallocate = true;
    }

    for (int i = 0; i < objects.Length; i++) {
      var obj = objects[i];
      m_sphereData[i] = obj.GetSphere();
    }

    if (reallocate) {
      // Setup GPU memory for the scene.
      const int kFloatsPerSphere = 8;
      if (m_spheresBuffer != null) {
        m_spheresBuffer.Dispose();
        m_spheresBuffer = null;
      }

      if (m_sphereData.Length > 0) {
        m_spheresBuffer = new ComputeBuffer(m_sphereData.Length, sizeof(float) * kFloatsPerSphere);
        RayTraceKernels.SetBuffer(m_rayTraceKernel, "_Spheres", m_spheresBuffer);
      }
    }

    if (m_spheresBuffer != null) {
      m_spheresBuffer.SetData(m_sphereData);
    }

    m_sceneChanged = true;
  }

19 Source : Assistant.cs
with GNU General Public License v3.0
from Keelhauled

private void LoadChara(string path)
        {
            currentCharacter = path;

            var cfw = GameObject.FindObjectsOfType<CustomFileWindow>().FirstOrDefault(x => x.fwType == CustomFileWindow.FileWindowType.CharaLoad);
            var loadFace = true;
            var loadBody = true;
            var loadHair = true;
            var parameter = true;
            var loadCoord = true;

            if(cfw)
            {
                loadFace = cfw.tglChaLoadFace && cfw.tglChaLoadFace.isOn;
                loadBody = cfw.tglChaLoadBody && cfw.tglChaLoadBody.isOn;
                loadHair = cfw.tglChaLoadHair && cfw.tglChaLoadHair.isOn;
                parameter = cfw.tglChaLoadParam && cfw.tglChaLoadParam.isOn;
                loadCoord = cfw.tglChaLoadCoorde && cfw.tglChaLoadCoorde.isOn;
            }

            var chaCtrl = CustomBase.Instance.chaCtrl;
            var originalSex = chaCtrl.sex;

            chaCtrl.chaFile.LoadFileLimited(path, chaCtrl.sex, loadFace, loadBody, loadHair, parameter, loadCoord);
            if(chaCtrl.chaFile.GetLastErrorCode() != 0)
                throw new Exception("LoadFileLimited failed");

            if(chaCtrl.chaFile.parameter.sex != originalSex)
            {
                chaCtrl.chaFile.parameter.sex = originalSex;
                Log.Message("Warning: The character's sex has been changed to match the editor mode.");
            }

            chaCtrl.ChangeCoordinateType();
            chaCtrl.Reload(!loadCoord, !loadFace && !loadCoord, !loadHair, !loadBody);
            CustomBase.Instance.updateCustomUI = true;
        }

19 Source : HideUI.cs
with GNU General Public License v3.0
from Keelhauled

IEnumerator UpdateDelayed()
        {
            for(int i = 0; i < 3; i++) yield return null; // wait for other UI

            while(true)
            {
                if(Input.GetKeyDown(hotkey))
                {
                    var names = File.ReadAllLines(path);
                    if(names.Length > 0)
                    {
                        var gameobjects = FindObjectsOfType<GameObject>();

                        foreach(var canvasName in names)
                        {
                            CacheObject cacheobject;
                            if(!canvasCache.TryGetValue(canvasName, out cacheobject))
                            {
                                var split = canvasName.Split('|');
                                var match = gameobjects.Where(x => x.name == split[0]).ToList();

                                // Pick gameobject with RectTransform
                                GameObject gameobject = null;
                                for(int i = 0; i < match.Count; i++)
                                {
                                    if(match[i].GetComponent<RectTransform>())
                                    {
                                        gameobject = match[i];
                                        break;
                                    }
                                }

                                if(gameobject)
                                {
                                    try
                                    {
                                        cacheobject = new CacheObject();
                                        cacheobject.gameobject = gameobject;
                                        cacheobject.canvas = gameobject.GetComponent<Canvas>();
                                        cacheobject.canvasName = split[0];
                                        cacheobject.hideAction = (CacheObject.HideAction)Enum.Parse(typeof(CacheObject.HideAction), split[1], true);
                                        cacheobject.hideMethod = (CacheObject.HideMethod)Enum.Parse(typeof(CacheObject.HideMethod), split[2], true);
                                        Console.WriteLine(gameobject.name + " detected");

                                        if(cacheobject.hideMethod == CacheObject.HideMethod.Enabled && !cacheobject.canvas)
                                        {
                                            cacheobject.hideMethod = CacheObject.HideMethod.SetActive;
                                            Console.WriteLine(" Canvas not found, switching to setactive mode");
                                        }

                                        canvasCache.Add(canvasName, cacheobject);
                                    }
                                    catch(Exception ex)
                                    {
                                        Console.WriteLine(ex);
                                    }
                                }
                            }
                        }

                        if(canvasCache.Count > 0)
                        {
                            bool flag = GetMasterFlag(canvasCache.First().Value);
                            bool savedFlag = canvasCache.First().Value.savedState;

                            foreach(var cacheobject in canvasCache.Values.ToList())
                            {
                                switch(cacheobject.hideAction)
                                {
                                    case CacheObject.HideAction.Toggle:
                                    {
                                        ShowCanvas(cacheobject, !flag);
                                        break;
                                    }
                                    case CacheObject.HideAction.False:
                                    {
                                        ShowCanvas(cacheobject, false);
                                        break;
                                    }
                                    case CacheObject.HideAction.True:
                                    {
                                        ShowCanvas(cacheobject, true);
                                        break;
                                    }
                                    case CacheObject.HideAction.Save:
                                    {
                                        switch(cacheobject.hideMethod)
                                        {
                                            case CacheObject.HideMethod.SetActive:
                                            {
                                                if(cacheobject.gameobject.activeSelf)
                                                {
                                                    cacheobject.savedState = cacheobject.gameobject.activeSelf;
                                                    ShowCanvas(cacheobject, false);
                                                }
                                                else if(!cacheobject.gameobject.activeSelf && cacheobject.savedState)
                                                {
                                                    cacheobject.savedState = cacheobject.gameobject.activeSelf;
                                                    ShowCanvas(cacheobject, !flag);
                                                }
                                                else if(!cacheobject.gameobject.activeSelf && !cacheobject.savedState)
                                                {
                                                    cacheobject.savedState = cacheobject.gameobject.activeSelf;
                                                    ShowCanvas(cacheobject, false);
                                                }
                                                break;
                                            }

                                            case CacheObject.HideMethod.Enabled:
                                            {
                                                if(cacheobject.canvas.enabled)
                                                {
                                                    cacheobject.savedState = cacheobject.canvas.enabled;
                                                    ShowCanvas(cacheobject, false);
                                                }
                                                else if(!cacheobject.canvas.enabled && cacheobject.savedState)
                                                {
                                                    cacheobject.savedState = cacheobject.canvas.enabled;
                                                    ShowCanvas(cacheobject, true);
                                                }
                                                else if(!cacheobject.canvas.enabled && !cacheobject.savedState)
                                                {
                                                    cacheobject.savedState = cacheobject.canvas.enabled;
                                                    ShowCanvas(cacheobject, false);
                                                }
                                                break;
                                            }
                                        }

                                        break;
                                    }
                                }
                            }
                        }
                    }
                }

                yield return null;
            }
        }

19 Source : ItemComlink.cs
with GNU General Public License v3.0
from Kingo64

protected void Awake() {
            item = GetComponent<Item>();
            module = item.data.GetModule<ItemModuleComlink>();

            item.OnHeldActionEvent += OnHeldAction;
            item.OnGrabEvent += OnGrabEvent;
            item.OnUngrabEvent += OnUngrabEvent;
            item.OnSnapEvent += OnSnapEvent;

            idleSound = item.GetCustomReference("IdleSound").GetComponent<AudioSource>();
            pingSound = item.GetCustomReference("PingSound").GetComponent<AudioSource>();
            startSound = item.GetCustomReference("StartSound").GetComponent<AudioSource>();
            stopSound = item.GetCustomReference("StopSound").GetComponent<AudioSource>();
            useSound = item.GetCustomReference("UseSound").GetComponent<AudioSource>();

            hologram = item.GetCustomReference("Hologram").gameObject;
            hologramLight = item.GetCustomReference("HologramLight").GetComponent<MeshRenderer>();
            hologramLogo = item.GetCustomReference("HologramLogo").GetComponent<MeshRenderer>();
            light = item.GetCustomReference("Light").GetComponent<Light>();
            text = item.GetCustomReference("Text").GetComponent<Text>();
            materials = item.GetCustomReference("Materials").GetComponent<MeshRenderer>().materials;

            hologram.SetActive(false);
            spawnLocations = new List<SpawnLocation>(FindObjectsOfType<SpawnLocation>());

            item.TryGetSavedValue("faction", out string tempFaction);
            item.TryGetSavedValue("target", out string tempTarget);
            int.TryParse(tempFaction, out currentFaction);
            int.TryParse(tempTarget, out currentTarget);

            factionData = module.factions[currentFaction];
            reinforcementData = module.reinforcements[currentTarget];
            creatureTable = Catalog.GetData<CreatureTable>(reinforcementData.creatureTable, true);
            SetGraphic();
            SetColour();
        }

19 Source : ConverterMenu.cs
with MIT License
from mamoniem

static void OnCleanConvertedItem (GameObject selectedObject){

		UIWidget[] UIWidgetsOnChilderens = selectedObject.GetComponentsInChildren<UIWidget>();
		UISprite[] UISpritesOnChilderens = selectedObject.GetComponentsInChildren<UISprite>();
		UILabel[] UILablesOnChilderens = selectedObject.GetComponentsInChildren<UILabel>();
		UIButton[] UIButtonsOnChilderens = selectedObject.GetComponentsInChildren<UIButton>();
		UIToggle[] UITogglesOnChilderens = selectedObject.GetComponentsInChildren<UIToggle>();
		UIInput[] UIInputsOnChilderens = selectedObject.GetComponentsInChildren<UIInput>();
		UIScrollBar[] UIScrollBarsOnChilderens = selectedObject.GetComponentsInChildren<UIScrollBar>();
		UISlider[] UISlidersOnChilderens = selectedObject.GetComponentsInChildren<UISlider>();
#if PopupLists
		UIPopupList[] UIPopuplistsOnChilderens = selectedObject.GetComponentsInChildren<UIPopupList>();
#endif

		Collider[] CollidersOnChilderens = selectedObject.GetComponentsInChildren<Collider>();

		for (int a=0; a<UIWidgetsOnChilderens.Length; a++){
			if (UIWidgetsOnChilderens[a]){
				DestroyImmediate (UIWidgetsOnChilderens[a]);
			}
		}
		
		for (int b=0; b<UISpritesOnChilderens.Length; b++){
			if (UISpritesOnChilderens[b]){
				DestroyImmediate (UISpritesOnChilderens[b]);
			}
		}
		
		for (int c=0; c<UILablesOnChilderens.Length; c++){
			if (UILablesOnChilderens[c]){
				DestroyImmediate (UILablesOnChilderens[c]);
			}
		}
		
		for (int d=0; d<UIButtonsOnChilderens.Length; d++){
			if (UIButtonsOnChilderens[d]){
				DestroyImmediate (UIButtonsOnChilderens[d]);
			}
		}
		
		for (int e=0; e<UITogglesOnChilderens.Length; e++){
			if(UITogglesOnChilderens[e]){
				DestroyImmediate (UITogglesOnChilderens[e]);
			}
		}

		for (int f=0; f<UIInputsOnChilderens.Length; f++){
			if (UIInputsOnChilderens[f]){
				DestroyImmediate (UIInputsOnChilderens[f]);
			}
		}

		for (int g=0; g<UIScrollBarsOnChilderens.Length; g++){
			if (UIScrollBarsOnChilderens[g]){
				DestroyImmediate (UIScrollBarsOnChilderens[g]);
			}
		}

		for (int h=0; h<UISlidersOnChilderens.Length; h++){
			if (UISlidersOnChilderens[h]){
				if (UISlidersOnChilderens[h].GetComponent<UISliderColors>()){
					DestroyImmediate (UISlidersOnChilderens[h].gameObject.GetComponent<UISliderColors>());
				}
				DestroyImmediate (UISlidersOnChilderens[h]);
			}
		}
#if PopupLists
		for (int h=0; h<UIPopuplistsOnChilderens.Length; h++){
			if (UIPopuplistsOnChilderens[h]){
				DestroyImmediate (UIPopuplistsOnChilderens[h]);
			}
		}
#endif
		for (int z=0; z<CollidersOnChilderens.Length; z++){
			if (CollidersOnChilderens[z]){
				DestroyImmediate (CollidersOnChilderens[z]);
			}
		}


		GameObject[] allTrash;
		allTrash = GameObject.FindObjectsOfType<GameObject>();
		for (int Z=0; Z<allTrash.Length; Z++){
			if (allTrash[Z].gameObject.name.Contains("NGUI Snapshot") && allTrash[Z].gameObject.transform.GetComponentInParent<RectTransform>()){
				DestroyImmediate (allTrash[Z].gameObject);
			}
		}
		Debug.Log ("<Color=blue> Cleaned all the <Color=Red>NGUISnapshot</Color> Objects in the scene Hierarchy</Color>");


	}

19 Source : ConverterMenu.cs
with MIT License
from mamoniem

[MenuItem ("nGUI TO uGUI/Atlas Convert/Current Scene")]
	static void OnConvertAtlasesInScene () {
		UISprite[] FoundAtlasesList;
		FoundAtlasesList = GameObject.FindObjectsOfType<UISprite>();
		for (int c=0; c<FoundAtlasesList.Length; c++){
			UIAtlas tempNguiAtlas;
			tempNguiAtlas = FoundAtlasesList[c].atlas;
			if (File.Exists("replacedets/nGUI TO uUI/CONVERSION_DATA/"+tempNguiAtlas.name+".png")){
				Debug.Log ("The Atlas <color=yellow>" + tempNguiAtlas.name + " </color>was Already Converted, Check the<color=yellow> \"nGUI TO uUI/CONVERSION_DATA\" </color>Directory");
			}else{
				ConvertAtlas(tempNguiAtlas);
			}
		}
	}

19 Source : Typer.cs
with MIT License
from PacktPublishing

void Awake () 
	{
		//Get all enemies
		Enemies = Object.FindObjectsOfType<AIEnemy>();

		//Get audio source
		ThisAS = GetComponent<AudioSource>();
		ThisAS.clip = CombatSounds[0];

		TyperText = GetComponentInChildren<Text>();
	}

19 Source : FluencePlugin.cs
with The Unlicense
from PeturDarri

private void Awake()
	{
		Instance = this;
		_cameras = FindObjectsOfType<Camera>();
		for (int i = 0; i < _cameras.Length; i++)
		{
			FluenceCamera fluenceCamera = _cameras[i].gameObject.AddComponent<FluenceCamera>();
			fluenceCamera.CameraIndex = i;
		}

		try
		{
			SetupPlugin();
		}
		catch (DllNotFoundException e)
		{
			Debug.LogError("fluence_plugin.dll is missing! Read the README!");
			Debug.Break();
			throw;
		}
		SetEyeCount(_cameras.Length);
		_eyeFromStartMatrixRaw = new float[16];
		_clipFromEyeMatrixRaw = new float[16];
		_startFromLightfieldMatrixRaw = new float[16];
		_viewportRaw = new int[4];
		_flipMatrix = Matrix4x4.idenreplacedy;
		_flipMatrix[2, 2] = -1f;
		
		foreach (FluenceLightfield fluenceLightfield in Lightfields)
		{
			string text = Path.Combine(Application.streamingreplacedetsPath, fluenceLightfield.LightfieldPath);
			if (File.Exists(text))
			{
				fluenceLightfield.LightfieldIndex = LoadLightfield(text);
			}
			else
			{
				Debug.LogError("Could not find file: " + text + ". Have you imported .lf files into the Streamingreplacedets folder?");
				fluenceLightfield.LightfieldIndex = -1;
			}
		}
		Init();
		GL.IssuePluginEvent(GetRenderEventFunc(), 1179406079);
	}

19 Source : RotationSystem.cs
with GNU General Public License v3.0
from Psychloor

private static IEnumerator GrabMainCamera()
        {
            while (!Instance.cameraTransform)
            {
                yield return new WaitForSeconds(1f);
                foreach (Object component in Object.FindObjectsOfType(Il2CppType.Of<Transform>()))
                {
                    yield return null;
                    Transform transform;
                    if ((transform = component.TryCast<Transform>()) == null) continue;
                    if (!transform.name.Equals("Camera (eye)", StringComparison.OrdinalIgnoreCase)) continue;
                    Instance.cameraTransform = transform;
                    break;
                }
            }
        }

19 Source : SceneHierarchyBackend.cs
with MIT License
from seldomU

public IEnumerable<Relation<Object, string>> GetRelations( Object enreplacedy )
		{
			// the fake scene object gets special care
			if ( IsSceneObject( enreplacedy ) )
			{
				var allGOs = Object.FindObjectsOfType<GameObject>();
				var rootGOs = allGOs.Where( go => go.transform.parent == null );
				foreach ( var go in rootGOs )
					yield return new Relation<Object, string>( enreplacedy, go, string.Empty );

				yield break;
			}

			var asGameObject = enreplacedy as GameObject;
			if ( asGameObject == null )
				yield break;

			// include sub-gameObjects
			foreach ( Transform t in asGameObject.transform )
				yield return new Relation<Object, string>( enreplacedy, t.gameObject, string.Empty );

			// include components
			if ( includeComponents )
			{
				foreach ( var c in asGameObject.GetComponents<Component>() )
					yield return new Relation<Object, string>( enreplacedy, c, string.Empty );
			}
		}

19 Source : TagBackend.cs
with MIT License
from seldomU

public override Rect OnGUI()
		{
			GUILayout.BeginHorizontal( EditorStyles.toolbar );
			{
				// option: use all gameobjects of the active scene as targets
				if ( GUILayout.Button( "Show active scene", EditorStyles.toolbarButton ) )
					api.ResetTargets( Object.FindObjectsOfType<GameObject>().Cast<object>().ToArray() );

				// option: remove untagged objects
				if ( ContainsUntaggedTargets() &&
					GUILayout.Button( "Hide untagged", EditorStyles.toolbarButton ) )
					api.ResetTargets( api.GetTargets().Where( IsUntagged ).ToArray() );

				GUILayout.FlexibleSpace();

				searchstring = BackendUtil.DrawEnreplacedySelectSearchField( searchstring, api );
			}
			GUILayout.EndHorizontal();
			return base.OnGUI();
		}

19 Source : UIUtil.cs
with MIT License
from ST-Apps

private static void FindUIRoot()
        {
            uiRoot = null;

            foreach (var view in Object.FindObjectsOfType<UIView>())
                if (view.transform.parent == null && view.name == "UIView")
                {
                    uiRoot = view;
                    break;
                }
        }

19 Source : UIUtil.cs
with MIT License
from ST-Apps

public static T FindComponent<T>(string name, UIComponent parent = null, FindOptions options = FindOptions.None)
            where T : UIComponent
        {
            if (uiRoot == null)
            {
                FindUIRoot();
                if (uiRoot == null) return null;
            }

            foreach (var component in Object.FindObjectsOfType<T>())
            {
                bool nameMatches;
                if ((options & FindOptions.NameContains) != 0) nameMatches = component.name.Contains(name);
                else nameMatches = component.name == name;

                if (!nameMatches) continue;

                Transform parentTransform;
                if (parent != null) parentTransform = parent.transform;
                else parentTransform = uiRoot.transform;

                var t = component.transform.parent;
                while (t != null && t != parentTransform) t = t.parent;

                if (t == null) continue;

                return component;
            }


            return null;
        }

19 Source : GameController.cs
with MIT License
from Tobbse

void FixedUpdate()
        {
            // Not ideal I guess, but currently contains _bigSpinnerRigids and _smallSpinnerRigids contain only one rigid, so that should be fine.
            foreach (Rigidbody smallSpinner in _smallSpinnerRigids)
            {
                smallSpinner.angularVelocity = new Vector3(0.2f, 0, 0);
            }
            foreach (Rigidbody bigSpinner in _bigSpinnerRigids)
            {
                bigSpinner.angularVelocity = new Vector3(0.1f, 0, 0);
            }

            // Calculates the relative time that has preplaceded depending on the bpm values.
            float currentTime = Time.time;
            _timePreplaceded += currentTime - _lastTime;
            _relativeTimePreplaceded += (currentTime - _lastTime) * _bps;
            _lastTime = currentTime;

            // Triggers playing of audio file once, at the correct point in time.
            if (!_timeframeReached && _relativeTimePreplaceded >= 0)
            {
                _timeframeReached = true;
                _audioSource.Play();
                _audioSource.volume = 0.25f;
            }
            else if (_timeframeReached && !_audioSource.isPlaying)
            {
                // End of loop, only called once so the 'FindObjectsOfType' call is fine. Leftover blocks have to be missed.
                TimedBlock[] timedBlocks = Object.FindObjectsOfType<TimedBlock>();
                foreach (TimedBlock block in timedBlocks)
                {
                    block.MissBlock();
                }
                SceneManager.LoadScene("ScoreMenu");
            }

            // Checks if new events/blocks/obstacles are available and should be spawned, depending on the relative time preplaceded.
            // The travel time has to be taken into account here, because we want the blocks to spawn before they arrive at the player.
            _noteSpawner.checkBlocksSpawnable(_relativeTimePreplaceded + NoteSpawner.BLOCK_TRAVEL_TIME * _bps);
            _obstacleSpawner.checkObstaclesSpawnable(_relativeTimePreplaceded + ObstacleSpawner.OBSTACLE_TRAVEL_TIME * _bps);
            _effectController.checkEventsAvailable(_relativeTimePreplaceded);
        }

19 Source : OVREngineConfigurationUpdater.cs
with MIT License
from Tobbse

static void EnforceVRSupport()
	{
		if (PlayerSettings.virtualRealitySupported)
			return;
		
		var mgrs = GameObject.FindObjectsOfType<OVRManager>();
		for (int i = 0; i < mgrs.Length; ++i)
		{
			if (mgrs [i].isActiveAndEnabled)
			{
				Debug.Log ("Enabling Unity VR support");
				PlayerSettings.virtualRealitySupported = true;

				bool oculusFound = false;
#if UNITY_2017_2_OR_NEWER
				foreach (var device in UnityEngine.XR.XRSettings.supportedDevices)
#else
				foreach (var device in UnityEngine.VR.VRSettings.supportedDevices)
#endif
					oculusFound |= (device == "Oculus");

				if (!oculusFound)
					Debug.LogError("Please add Oculus to the list of supported devices to use the Utilities.");

				return;
			}
		}
	}

See More Examples