System.Collections.Generic.List.Add(GameObject)

Here are the examples of the csharp api System.Collections.Generic.List.Add(GameObject) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

992 Examples 7

19 View Source File : ShapeCreateTool.cs
License : Apache License 2.0
Project Creator : Algoryx

public override void OnSceneViewGUI( SceneView sceneView )
    {
      if ( Parent == null ) {
        PerformRemoveFromParent();
        return;
      }

      if ( HandleKeyEscape( true ) )
        return;

      // NOTE: Waiting for mouse click!
      if ( !Manager.HijackLeftMouseClick() )
        return;

      var hitResults = Utils.Raycast.IntersectChildren( HandleUtility.GUIPointToWorldRay( Event.current.mousePosition ),
                                                        Parent,
                                                        null,
                                                        true );
      // Find target. Ignoring shapes.
      GameObject selected = null;
      for ( int i = 0; selected == null && i < hitResults.Length; ++i ) {
        if ( hitResults[ i ].Target.GetComponent<Shape>() == null )
          selected = hitResults[ i ].Target;
      }

      // Single selection mode.
      ClearSelection();
      if ( selected != null ) {
        m_selection.Add( selected );
        // TODO HIGHLIGHT: Add multiple.
        //SetVisualizedSelection( selected );
      }
      else
        m_buttons.Reset();

      // TODO GUI: Why? Force inspector update instead?
      EditorUtility.SetDirty( Parent );
    }

19 View Source File : Contains.cs
License : Apache License 2.0
Project Creator : allenai

public List<GameObject> CurrentlyContainedGameObjects() {
        List<GameObject> objs = new List<GameObject>();

        BoxCollider b = this.GetComponent<BoxCollider>();

        // get center of this box in world space
        Vector3 worldCenter = b.transform.TransformPoint(b.center);

        // size of this receptacle box, but we need to scale by transform
        Vector3 worldHalfExtents = new Vector3(b.size.x * b.transform.lossyScale.x / 2, b.size.y * b.transform.lossyScale.y / 2, b.size.z * b.transform.lossyScale.z / 2);

        //////////////////////////////////////////////////
        // uncomment to debug "draw" where the OverlapBox goes
        // GameObject surrogateGeo = GameObject.CreatePrimitive(PrimitiveType.Cube);	
        // Destroy(surrogateGeo.GetComponent<Collider>());	
        // surrogateGeo.name = transform.parent.gameObject + "_dimensions";	
        // surrogateGeo.transform.position = worldCenter;	
        // surrogateGeo.transform.rotation = b.transform.rotation;	
        // surrogateGeo.transform.localScale = worldHalfExtents * 2;	
        // surrogateGeo.transform.parent = b.transform;	
        ////////////////////////////////////////////////////

        // ok now create an overlap box using these values and return all contained objects
        foreach (Collider col in Physics.OverlapBox(worldCenter, worldHalfExtents, b.transform.rotation)) {
            // ignore triggers
            if (col.GetComponentInParent<SimObjPhysics>() && !col.isTrigger) {
                // grab reference to game object this collider is part of
                SimObjPhysics sop = col.GetComponentInParent<SimObjPhysics>();

                // don't add any colliders from our parent object, so things like a 
                // shelf or drawer nested inside another shelving unit or dresser sim object
                // don't contain the object they are nested inside
                if (!hasAncestor(this.transform.gameObject, sop.transform.gameObject)) {
                    // don't add repeat objects in case there were multiple
                    // colliders from the same object
                    if (!objs.Contains(sop.transform.gameObject)) {
                        objs.Add(sop.transform.gameObject);
                    }
                }
            }
        }

        return objs;
    }

19 View Source File : VoxelTile.cs
License : MIT License
Project Creator : alen-smajic

IEnumerator BuildRoutine()
		{
			var distanceOrderedVoxels = _voxels.OrderBy(x => (_camera.transform.position - x.Position).magnitude).ToList();

			for (int i = 0; i < distanceOrderedVoxels.Count; i += _voxelBatchCount)
			{
				for (int j = 0; j < _voxelBatchCount; j++)
				{
					var index = i + j;
					if (index < distanceOrderedVoxels.Count)
					{
						var voxel = distanceOrderedVoxels[index];
						_instantiatedVoxels.Add(Instantiate(voxel.Prefab, voxel.Position, Quaternion.idenreplacedy, transform) as GameObject);
					}
				}
				yield return null;
			}
		}

19 View Source File : AGXFileImporter.cs
License : Apache License 2.0
Project Creator : Algoryx

public static GameObject[] Import( Object[] objects )
    {
      var prefabs = new List<GameObject>();
      foreach ( var obj in objects ) {
        var prefab = Import( obj );
        if ( prefab != null )
          prefabs.Add( prefab );
      }
      return prefabs.ToArray();
    }

19 View Source File : NPCspawner.cs
License : GNU General Public License v3.0
Project Creator : AlexandreDoucet

[ContextMenu("GenerateList")]
    public void GenerateList()
    {

        while (npcList.Count > maxNpcOnTrack)
        {
            if(Application.isEditor)
            DestroyImmediate(npcList[npcList.Count - 1]);
            else
            Destroy(npcList[npcList.Count - 1]);

            npcList.RemoveAt(npcList.Count - 1);
        }

        List<GameObject> holder = new List<GameObject>();
        for (int i = 0; i < npcList.Count; i++)
        {
            if (npcList[i] == null)
            {
                holder.Add(npcList[i]);
            }
        }
        foreach (GameObject item in holder)
        {npcList.Remove(item);}

        {
            int i = npcList.Count;
            for (; i < maxNpcOnTrack; i++)
            { npcList.Add(GenerateNewNPC("NPC_" + npcList.Count)); }
        }

    }

19 View Source File : TriggerData.cs
License : MIT License
Project Creator : ajayyy

void OnTriggerEnter(Collider other) {
        collidingObjects.Add(other.gameObject);
    }

19 View Source File : InstantiatePrefabTest.cs
License : Apache License 2.0
Project Creator : allenai

public SimObjPhysics SpawnObject(string objectType, bool randomize, int variation, Vector3 position, Vector3 rotation, bool spawningInHand, bool ignoreChecks) {
        GameObject topObject = GameObject.Find("Objects");

        List<GameObject> candidates = new List<GameObject>();

        foreach (GameObject go in prefabs) {
            // does a prefab of objectType exist in the current array of prefabs to spawn?
            if (go.GetComponent<SimObjPhysics>().Type == (SimObjType)Enum.Parse(typeof(SimObjType), objectType)) {
                candidates.Add(go);
            }
        }

        // ok time to spawn a sim object!
        SimObjPhysics simObj = null;

        // Figure out which variation to use, if no variation use first candidate found
        if (randomize) {
            variation = UnityEngine.Random.Range(1, candidates.Count);
        }
        if (variation != 0) {
            variation -= 1;
        }

        Quaternion quat = Quaternion.Euler(rotation);

        if (ignoreChecks || CheckSpawnArea(candidates[variation].GetComponent<SimObjPhysics>(), position, quat, spawningInHand)) {
            GameObject prefab = Instantiate(candidates[variation], position, quat) as GameObject;
            if (!ignoreChecks) {
                if (UtilityFunctions.isObjectColliding(
                    prefab,
                    new List<GameObject>(from agent in GameObject.FindObjectsOfType<BaseAgentComponent>() select agent.gameObject))
                ) {
                    Debug.Log("On spawning object the area was not clear despite CheckSpawnArea saying it was.");
                    prefab.SetActive(false);
                    return null;
                }
            }
            prefab.transform.SetParent(topObject.transform);
            simObj = prefab.GetComponent<SimObjPhysics>();
            spawnCount++;
        } else {
            return null;
        }

        // ok make sure we did actually spawn something now, and give it an Id number
        if (simObj) {
            simObj.objectID = objectType + "|" + spawnCount.ToString();
            return simObj;
        }

        return null;
    }

19 View Source File : PathManager.cs
License : MIT License
Project Creator : Adsito

public static void SpawnPath(PathData pathData)
    {
        Vector3 averageLocation = Vector3.zero;
        for (int j = 0; j < pathData.nodes.Length; j++)
            averageLocation += pathData.nodes[j];

        averageLocation /= pathData.nodes.Length;
        GameObject newObject = GameObject.Instantiate(DefaultPath, averageLocation + PathParent.position, Quaternion.idenreplacedy, PathParent);
        newObject.name = pathData.name;

        var pathNodes = new List<GameObject>();
        for (int j = 0; j < pathData.nodes.Length; j++)
        {
            GameObject newNode = GameObject.Instantiate(DefaultNode, newObject.transform);
            newNode.transform.position = pathData.nodes[j] + PathParent.position;
            pathNodes.Add(newNode);
        }
        newObject.GetComponent<PathDataHolder>().pathData = pathData;
    }

19 View Source File : LoadCustomAssets.cs
License : MIT License
Project Creator : amazingalek

private void ShootDuck()
		{
			var duckBody = Instantiate(_duckBody);
			duckBody.gameObject.SetActive(true);

			duckBody.SetPosition(_playerTransform.position + _playerTransform.forward * 2f);
			duckBody.SetRotation(_playerTransform.rotation);
			duckBody.SetVelocity(_playerBody.GetVelocity() + _playerTransform.forward * 10f);
			_ducks.Add(duckBody.gameObject);

			_shootSound.Play();

			_saveFile.NumberOfDucks++;
			ModHelper.Console.WriteLine($"Ducks shot: {_saveFile.NumberOfDucks}");
			ModHelper.Storage.Save(_saveFile, "savefile.json");
		}

19 View Source File : DebugShowPlanes.cs
License : The Unlicense
Project Creator : aeroson

public override void Start()
        {
            for (int i = 0; i < 6; i++)
            {
                var go = new GameObject();
                gos.Add(go);
                var r = go.AddComponent<MeshRenderer>();
                r.mesh = Factory.GetMesh("internal/cube.obj");
                go.transform.scale = new Vector3(10, 10, 1);
            }
        }

19 View Source File : Find.cs
License : Apache License 2.0
Project Creator : Algoryx

public static GameObject[] ChildrenList( GameObject gameObject )
    {
      if ( gameObject == null )
        return null;

      GameObject root = Find.RootGameObject( gameObject );
      RigidBody[] bodies = root.GetComponentsInChildren<RigidBody>();
      Collide.Shape[] shapes = root.GetComponentsInChildren<Collide.Shape>();

      List<GameObject> gameObjects = new List<GameObject>();
      foreach ( var rb in bodies )
        gameObjects.Add( rb.gameObject );
      foreach ( var shape in shapes )
        gameObjects.Add( shape.gameObject );

      gameObjects.Add( null );

      int indexOfSelected = gameObjects.IndexOf( gameObject );
      if ( indexOfSelected > 0 && gameObjects.Count > 1 ) {
        GameObject tmp = gameObjects[ 0 ];
        gameObjects[ 0 ] = gameObject;
        gameObjects[ indexOfSelected ] = tmp;
      }

      return gameObjects.ToArray();
    }

19 View Source File : ConveyorBelt.cs
License : Apache License 2.0
Project Creator : Algoryx

public bool Add( GameObject roller )
    {
      if ( roller == null || m_rollers.Contains( roller ) )
        return false;

      var rb = roller.GetComponentInParent<RigidBody>();
      if ( rb == null )
        return false;

      // If any previously added TrackWheel component belongs to another
      // track/belt we cannot (right now) add this roller to this belt.
      var alreadyPresentTrackWheels = roller.GetComponents<TrackWheel>();
      if ( alreadyPresentTrackWheels.Length > 0 ) {
        // Don't think disabled tracks will appear here.
        var tracks = FindObjectsOfType<Track>();
        if ( tracks.Any( track => alreadyPresentTrackWheels.Any( wheel => track.Contains( wheel ) ) ) ) {
          Debug.LogWarning( $"Roller {roller.name} already has {roller.GetComponents<TrackWheel>().Length} TrackWheel components " +
                             "belonging to other belt/track instances." );
          return false;
        }
      }

      using ( BeginResourceRequests() ) {
        var rotationAxisOffset = 0.5f * ( Width - TrackWidth );
        for ( int i = 0; i < NumberOfTracks; ++i ) {
          var trackWheel = i < alreadyPresentTrackWheels.Length ?
                             alreadyPresentTrackWheels[ i ] :
                             AddComponent<TrackWheel>( roller );
          trackWheel.Configure( roller,
                                rotationAxisOffset,
                                (aName, aModel) =>
                                {
                                  return ( aModel == TrackWheelModel.Sprocket && aName.StartsWith( "drivtrumma" ) ) ||
                                         ( aModel == TrackWheelModel.Idler && aName.StartsWith( "vandtrumma" ) );
                                } );
          rotationAxisOffset -= TrackWidth;
          AboutToChange( Tracks[ i ] );
          Tracks[ i ].Add( trackWheel );
        }

        // Destroying leftover TrackWheel components.
        for ( int i = NumberOfTracks; i < alreadyPresentTrackWheels.Length; ++i )
          DestroyObjectImmediate( alreadyPresentTrackWheels[ i ] );

        m_rollers.Add( roller );
      }

      return true;
    }

19 View Source File : RollerCoaster.cs
License : MIT License
Project Creator : ajayyy

public void RemoveTrackPiece(GameObject trackPiece) {
        unusedTrackPieces.Add(trackPiece);
        trackPieces.Remove(trackPiece);

        trackPiece.SetActive(false);
    }

19 View Source File : AssetsMenu.cs
License : Apache License 2.0
Project Creator : Algoryx

[MenuItem( "replacedets/AGXUnity/Import/Selected URDF [prefab]...", priority = 550 )]
    public static GameObject[] SelectedUrdfFilesAsPrefab()
    {
      var urdfFilePaths = IO.URDF.Reader.GetSelectedUrdfFiles( true );
      var instances = IO.URDF.Reader.Instantiate( urdfFilePaths, null, false );
      if ( instances.Length == 0 )
        return instances;

      var prefabs = new List<GameObject>();
      foreach ( var instance in instances ) {
        var directory = IO.URDF.Prefab.OpenFolderPanel( $"Prefab and replacedets directory for: {instance.name}" );
        if ( string.IsNullOrEmpty( directory ) ) {
          Debug.Log( $"Ignoring URDF prefab {instance.name}." );
          continue;
        }
        var model = AGXUnity.IO.URDF.Utils.GetElement<AGXUnity.IO.URDF.Model>( instance );
        var prefab = IO.URDF.Prefab.Create( model,
                                            instance,
                                            directory );
        if ( prefab != null )
          prefabs.Add( prefab );

        Object.DestroyImmediate( instance );
      }

      return prefabs.ToArray();
    }

19 View Source File : DebugUIBuilder.cs
License : MIT License
Project Creator : absurd-joy

public void Awake()
  {
    Debug.replacedert(instance == null);
    instance = this;
    menuOffset = transform.position; // TODO: this is unpredictable/busted
    gameObject.SetActive(false);
    rig = FindObjectOfType<OVRCameraRig>();
    for (int i = 0; i < toEnable.Count; ++i)
    {
      toEnable[i].SetActive(false);
    }

    insertPositions = new Vector2[targetContentPanels.Length];
    for (int i = 0; i < insertPositions.Length; ++i)
    {
      insertPositions[i].x = marginH;
      insertPositions[i].y = -marginV;
    }
    insertedElements = new List<RectTransform>[targetContentPanels.Length];
    for (int i = 0; i < insertedElements.Length; ++i)
    {
      insertedElements[i] = new List<RectTransform>();
    }

    if (uiHelpersToInstantiate)
    {
      GameObject.Instantiate(uiHelpersToInstantiate);
    }

    lp = FindObjectOfType<LaserPointer>();
    if (!lp)
    {
      Debug.LogError("Debug UI requires use of a LaserPointer and will not function without it. Add one to your scene, or replacedign the UIHelpers prefab to the DebugUIBuilder in the inspector.");
      return;
    }
    lp.laserBeamBehavior = laserBeamBehavior;

    if (!toEnable.Contains(lp.gameObject))
    {
      toEnable.Add(lp.gameObject);
    }
    GetComponent<OVRRaycaster>().pointer = lp.gameObject;
    lp.gameObject.SetActive(false);
#if UNITY_EDITOR
    string scene = SceneManager.GetActiveScene().name;
    OVRPlugin.SendEvent("debug_ui_builder",
      ((scene == "DebugUI") ||
       (scene == "DistanceGrab") ||
       (scene == "OVROverlay") ||
       (scene == "Locomotion")).ToString(),
      "sample_framework");
#endif
  }

19 View Source File : DroneObjectLauncher.cs
License : Apache License 2.0
Project Creator : allenai

public GameObject GetGameObject(string objectType, bool randomize, int variation) {
        List<GameObject> candidates = new List<GameObject>();

        SimObjType target = (SimObjType)Enum.Parse(typeof(SimObjType), objectType);
        // Debug.Log(target);
        foreach (GameObject go in prefabsToLaunch) {
            // Debug.Log(go.GetComponent<SimObjPhysics>().Type);
            // does a prefab of objectType exist in the current array of prefabs to spawn?
            if (go.GetComponent<SimObjPhysics>().Type == target) {
                candidates.Add(go);
            }
        }

        // Figure out which variation to use, if no variation use first candidate found
        if (randomize) {
            variation = UnityEngine.Random.Range(1, candidates.Count);
        }
        if (variation != 0) {
            variation -= 1;
        }

        return candidates[variation];
    }

19 View Source File : GroupManager.cs
License : MIT License
Project Creator : AleksandrHovhannisyan

void SpawnBoid(float x, float z)
    {
        Vector3 spawnPoint = new Vector3(x, boidRadius, z);
        GameObject newBoid = Instantiate(boidPrefab, spawnPoint, Quaternion.idenreplacedy);
        boids.Add(newBoid);
    }

19 View Source File : PhysicsSceneManager.cs
License : Apache License 2.0
Project Creator : allenai

public bool RandomSpawnRequiredSceneObjects(
        int seed,
        bool spawnOnlyOutside,
        int maxPlacementAttempts,
        bool staticPlacement,
        HashSet<SimObjPhysics> excludedSimObjects,
        ObjectTypeCount[] numDuplicatesOfType,
        List<SimObjType> excludedReceptacleTypes
    ) {
#if UNITY_EDITOR
        var Masterwatch = System.Diagnostics.Stopwatch.StartNew();
#endif

        if (RequiredObjects.Count == 0) {
#if UNITY_EDITOR
            Debug.Log("No objects in Required Objects array, please add them in editor");
#endif

            return false;
        }

        // initialize Unity's random with seed
        UnityEngine.Random.InitState(seed);

        List<SimObjType> TypesOfObjectsPrefabIsAllowedToSpawnIn = new List<SimObjType>();

        int HowManyCouldntSpawn = RequiredObjects.Count;

        // if we already spawned objects, lets just move them around
        if (SpawnedObjects.Count > 0) {
            HowManyCouldntSpawn = SpawnedObjects.Count;

            Dictionary<SimObjType, List<SimObjPhysics>> typeToObjectList = new Dictionary<SimObjType, List<SimObjPhysics>>();

            Dictionary<SimObjType, int> requestedNumDuplicatesOfType = new Dictionary<SimObjType, int>();
            // List<SimObjType> listOfExcludedReceptacles = new List<SimObjType>();
            HashSet<GameObject> originalObjects = new HashSet<GameObject>(SpawnedObjects);

            if (numDuplicatesOfType == null) {
                numDuplicatesOfType = new ObjectTypeCount[0];
            }

            foreach (ObjectTypeCount repeatCount in numDuplicatesOfType) {
                SimObjType objType = (SimObjType)System.Enum.Parse(typeof(SimObjType), repeatCount.objectType);
                requestedNumDuplicatesOfType[objType] = repeatCount.count;
            }

            // Now lets go through all pickupable sim objects that are in the current scene
            foreach (GameObject go in SpawnedObjects) {
                SimObjPhysics sop = null;
                sop = go.GetComponent<SimObjPhysics>();

                // Add object types in the current scene to the typeToObjectList if not already on it
                if (!typeToObjectList.ContainsKey(sop.ObjType)) {
                    typeToObjectList[sop.ObjType] = new List<SimObjPhysics>();
                }

                // Add this sim object to the list if the sim object's type matches the key in typeToObjectList
                if (!requestedNumDuplicatesOfType.ContainsKey(sop.ObjType) ||
                    (typeToObjectList[sop.ObjType].Count < requestedNumDuplicatesOfType[sop.ObjType])
                ) {
                    typeToObjectList[sop.ObjType].Add(sop);
                }
            }

            // Keep track of the sim objects we are making duplicates of
            List<GameObject> gameObjsToPlaceInReceptacles = new List<GameObject>();

            // Keep track of the sim objects that have not been duplicated
            List<GameObject> unduplicatedSimObjects = new List<GameObject>();

            // Ok now lets go through each object type in the dictionary
            foreach (SimObjType sopType in typeToObjectList.Keys) {
                // we found a matching SimObjType and the requested count of duplicates is bigger than how many of that
                // object are currently in the scene
                if (requestedNumDuplicatesOfType.ContainsKey(sopType) &&
                    requestedNumDuplicatesOfType[sopType] > typeToObjectList[sopType].Count
                ) {
                    foreach (SimObjPhysics sop in typeToObjectList[sopType]) {
                        gameObjsToPlaceInReceptacles.Add(sop.gameObject);
                    }

                    int numExtra = requestedNumDuplicatesOfType[sopType] - typeToObjectList[sopType].Count;

                    // let's instantiate the duplicates now
                    for (int j = 0; j < numExtra; j++) {
                        // Add a copy of the item to try and match the requested number of duplicates
                        SimObjPhysics sop = typeToObjectList[sopType][UnityEngine.Random.Range(0, typeToObjectList[sopType].Count - 1)];
                        SimObjPhysics copy = Instantiate(sop);
                        copy.name += "_random_copy_" + j;
                        copy.ObjectID = sop.ObjectID + "_copy_" + j;
                        copy.objectID = copy.ObjectID;
                        gameObjsToPlaceInReceptacles.Add(copy.gameObject);
                    }
                } else {
                    // this object is not one that needs duplicates, so just add it to the unduplicatedSimObjects list
                    foreach (SimObjPhysics sop in typeToObjectList[sopType]) {
                        unduplicatedSimObjects.Add(sop.gameObject);
                    }
                }
            }

            // NOTE: for backwards compatibility with InitialRandomSpawn, this does not use BaseFPSAgentController.systemRandom.
            // InitialRandomSpawn is going to be deprecated soon.
            System.Random rng = new System.Random(seed);
            gameObjsToPlaceInReceptacles.AddRange(unduplicatedSimObjects);
            gameObjsToPlaceInReceptacles.Shuffle_(rng);

            Dictionary<SimObjType, List<SimObjPhysics>> objTypeToReceptacles = new Dictionary<SimObjType, List<SimObjPhysics>>();
            foreach (SimObjPhysics receptacleSop in GatherAllReceptaclesInScene()) {

                SimObjType receptType = receptacleSop.ObjType;
                if (!excludedReceptacleTypes.Contains(receptacleSop.Type) &&
                        ((!spawnOnlyOutside) || ReceptacleRestrictions.SpawnOnlyOutsideReceptacles.Contains(receptacleSop.ObjType))
                ) {
                    if (!objTypeToReceptacles.ContainsKey(receptacleSop.ObjType)) {
                        objTypeToReceptacles[receptacleSop.ObjType] = new List<SimObjPhysics>();
                    }
                    objTypeToReceptacles[receptacleSop.ObjType].Add(receptacleSop);
                }
            }

            InstantiatePrefabTest spawner = gameObject.GetComponent<InstantiatePrefabTest>();
            foreach (GameObject gameObjToPlaceInReceptacle in gameObjsToPlaceInReceptacles) {
                SimObjPhysics sopToPlaceInReceptacle = gameObjToPlaceInReceptacle.GetComponent<SimObjPhysics>();

                if (staticPlacement) {
                    sopToPlaceInReceptacle.GetComponent<Rigidbody>().isKinematic = true;
                }

                // if(sopToPlaceInReceptacle.IsBreakable) {
                //     sopToPlaceInReceptacle.GetComponent<Break>().Unbreakable = true;
                // }

                if (excludedSimObjects.Contains(sopToPlaceInReceptacle)) {
                    HowManyCouldntSpawn--;
                    continue;
                }

                bool spawned = false;
                foreach (SimObjPhysics receptacleSop in IterShuffleSimObjPhysicsDictList(objTypeToReceptacles, rng)) {
                    List<ReceptacleSpawnPoint> targetReceptacleSpawnPoints;

                    if(receptacleSop.ContainedGameObjects().Count > 0 && receptacleSop.IsPickupable) {
                        //this pickupable object already has something in it, skip over it since we currently can't account for detecting bounds of a receptacle + any contained objects
                        continue;
                    }

                    // check if the target Receptacle is an ObjectSpecificReceptacle
                    // if so, if this game object is compatible with the ObjectSpecific restrictions, place it!
                    // this is specifically for things like spawning a mug inside a coffee maker
                    if (receptacleSop.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.ObjectSpecificReceptacle)) {
                        ObjectSpecificReceptacle osr = receptacleSop.GetComponent<ObjectSpecificReceptacle>();

                        if (osr.HreplacedpecificType(sopToPlaceInReceptacle.ObjType)) {
                            // in the random spawn function, we need this additional check because there isn't a chance for
                            // the physics update loop to fully update osr.isFull() correctly, which can cause multiple objects
                            // to be placed on the same spot (ie: 2 pots on the same burner)
                            if (osr.attachPoint.transform.childCount > 0) {
                                break;
                            }

                            // perform additional checks if this is a Stove Burner! 
                            if (receptacleSop.GetComponent<SimObjPhysics>().Type == SimObjType.StoveBurner) {
                                if (
                                    StoveTopCheckSpawnArea(
                                        sopToPlaceInReceptacle,
                                        osr.attachPoint.transform.position,
                                        osr.attachPoint.transform.rotation,
                                        false) == true
                                ) {
                                    // print("moving object now");
                                    gameObjToPlaceInReceptacle.transform.position = osr.attachPoint.position;
                                    gameObjToPlaceInReceptacle.transform.SetParent(osr.attachPoint.transform);
                                    gameObjToPlaceInReceptacle.transform.localRotation = Quaternion.idenreplacedy;

                                    gameObjToPlaceInReceptacle.GetComponent<Rigidbody>().collisionDetectionMode = CollisionDetectionMode.Discrete;
                                    gameObjToPlaceInReceptacle.GetComponent<Rigidbody>().isKinematic = true;

                                    HowManyCouldntSpawn--;
                                    spawned = true;

                                    break;
                                }
                            } else { // for everything else (coffee maker, toilet paper holder, etc) just place it if there is nothing attached
                                gameObjToPlaceInReceptacle.transform.position = osr.attachPoint.position;
                                gameObjToPlaceInReceptacle.transform.SetParent(osr.attachPoint.transform);
                                gameObjToPlaceInReceptacle.transform.localRotation = Quaternion.idenreplacedy;

                                Rigidbody rb = gameObjToPlaceInReceptacle.GetComponent<Rigidbody>();
                                rb.collisionDetectionMode = CollisionDetectionMode.Discrete;
                                rb.isKinematic = true;

                                HowManyCouldntSpawn--;
                                spawned = true;
                                break;
                            }
                        }
                    }

                    targetReceptacleSpawnPoints = receptacleSop.ReturnMySpawnPoints();

                    // first shuffle the list so it's random
                    targetReceptacleSpawnPoints.Shuffle_(rng);
                    if (spawner.PlaceObjectReceptacle(
                        targetReceptacleSpawnPoints,
                        sopToPlaceInReceptacle,
                        staticPlacement,
                        maxPlacementAttempts,
                        90,
                        true
                    )) {
                        HowManyCouldntSpawn--;
                        spawned = true;
                        break;
                    }
                }

                if (!spawned) {
#if UNITY_EDITOR
                    Debug.Log(gameObjToPlaceInReceptacle.name + " could not be spawned.");
#endif
                    // go.GetComponent<SimpleSimObj>().IsDisabled = true;
                    if (!originalObjects.Contains(gameObjToPlaceInReceptacle)) {
                        gameObjToPlaceInReceptacle.SetActive(false);
                        Destroy(gameObjToPlaceInReceptacle);
                    }
                }

            }
        } else {
            /// XXX: add exception in at some point
            throw new NotImplementedException();
        }

#if UNITY_EDITOR
        if (HowManyCouldntSpawn > 0) {
            Debug.Log(HowManyCouldntSpawn + " object(s) could not be spawned into the scene!");
        }

        Masterwatch.Stop();
        var elapsed = Masterwatch.ElapsedMilliseconds;
        print("total time: " + elapsed);
#endif

        SetupScene();
        return true;
    }

19 View Source File : GridAcademy.cs
License : Apache License 2.0
Project Creator : A7ocin

public override void AcademyReset()
    {
        foreach (GameObject actor in actorObjs)
        {
            DestroyImmediate(actor);
        }
        SetEnvironment();

        actorObjs = new List<GameObject>();

        HashSet<int> numbers = new HashSet<int>();
        while (numbers.Count < players.Length)
        {
            numbers.Add(Random.Range(0, (int)resetParameters["gridSize"] * (int)resetParameters["gridSize"]));
        }
        int[] numbersA = Enumerable.ToArray(numbers);

        for (int i = 0; i < players.Length; i++)
        {
            int x = (numbersA[i]) / (int)resetParameters["gridSize"];
            int y = (numbersA[i]) % (int)resetParameters["gridSize"];
            GameObject actorObj = (GameObject)GameObject.Instantiate(Resources.Load(players[i]));
            actorObj.transform.position = new Vector3(x, -0.25f, y);
            actorObj.name = players[i];
            actorObjs.Add(actorObj);
            if (players[i] == "agent")
            {
                trueAgent.transform.position = actorObj.transform.position;
                trueAgent.transform.rotation = actorObj.transform.rotation;
                visualAgent = actorObj;
            }
        }

    }

19 View Source File : UtilityFunctions.cs
License : Apache License 2.0
Project Creator : allenai

public static Collider firstColliderObjectCollidingWith(
        GameObject go,
        List<GameObject> ignoreGameObjects = null,
        float expandBy = 0.0f,
        bool useBoundingBoxInChecks = false
     ) {
        if (ignoreGameObjects == null) {
            ignoreGameObjects = new List<GameObject>();
        }
        ignoreGameObjects.Add(go);
        HashSet<Collider> ignoreColliders = new HashSet<Collider>();
        foreach (GameObject toIgnoreGo in ignoreGameObjects) {
            foreach (Collider c in toIgnoreGo.GetComponentsInChildren<Collider>()) {
                ignoreColliders.Add(c);
            }
        }

        int layerMask = 1 << 8 | 1 << 10;
        foreach (CapsuleCollider cc in go.GetComponentsInChildren<CapsuleCollider>()) {
            if (cc.isTrigger) {
                continue;
            }
            foreach (Collider c in PhysicsExtensions.OverlapCapsule(cc, layerMask, QueryTriggerInteraction.Ignore, expandBy)) {
                if (!ignoreColliders.Contains(c)) {
                    return c;
                }
            }
        }
        foreach (BoxCollider bc in go.GetComponentsInChildren<BoxCollider>()) {
            if (bc.isTrigger || ("BoundingBox" == bc.gameObject.name && (!useBoundingBoxInChecks))) {
                continue;
            }
            foreach (Collider c in PhysicsExtensions.OverlapBox(bc, layerMask, QueryTriggerInteraction.Ignore, expandBy)) {
                if (!ignoreColliders.Contains(c)) {
                    return c;
                }
            }
        }
        foreach (SphereCollider sc in go.GetComponentsInChildren<SphereCollider>()) {
            if (sc.isTrigger) {
                continue;
            }
            foreach (Collider c in PhysicsExtensions.OverlapSphere(sc, layerMask, QueryTriggerInteraction.Ignore, expandBy)) {
                if (!ignoreColliders.Contains(c)) {
                    return c;
                }
            }
        }
        return null;
    }

19 View Source File : ReplaceFeatureModifier.cs
License : MIT License
Project Creator : alen-smajic

private void SpawnPrefab(VectorEnreplacedy ve, UnityTile tile, Vector2d latLong)
		{
			GameObject go;

			var featureId = ve.Feature.Data.Id;
			if (_objects.ContainsKey(featureId))
			{
				go = _objects[featureId];
				go.SetActive(true);
				go.transform.SetParent(ve.GameObject.transform, false);

			}
			else
			{
				go = Instantiate(_options.prefab);
				_prefabList.Add(go);
				_objects.Add(featureId, go);
				_objectPosition.Add(featureId, latLong);
				go.transform.SetParent(ve.GameObject.transform, false);
			}

			PositionScaleRectTransform(ve, tile, go, latLong);

			if (_options.AllPrefabsInstatiated != null)
			{
				_options.AllPrefabsInstatiated(_prefabList);
			}
		}

19 View Source File : SpawnInsideModifier.cs
License : MIT License
Project Creator : alen-smajic

private GameObject GetObject(int index, GameObject go)
		{
			GameObject ob;
			if (_pool.Count > 0)
			{
				ob = _pool.Dequeue();
				ob.SetActive(true);
				ob.transform.SetParent(go.transform);
			}
			else
			{
				ob = ((GameObject)Instantiate(_prefabs[index], go.transform, false));
			}
			if (_objects.ContainsKey(go))
			{
				_objects[go].Add(ob);
			}
			else
			{
				_objects.Add(go, new List<GameObject>() { ob });
			}
			return ob;
		}

19 View Source File : DNAPanel.cs
License : Apache License 2.0
Project Creator : A7ocin

public void Initialize (DynamicCharacterAvatar Avatar) 
		{

		foreach(GameObject go in CreatedObjects) UMAUtils.DestroySceneObject(go);
		CreatedObjects.Clear();

			UMADnaBase[] DNA = Avatar.GetAllDNA();

			List<DNAHolder> ValidDNA = new List<DNAHolder>();

			foreach (UMADnaBase d in DNA)
			{
				string[] names = d.Names;
				float[] values = d.Values;

				for (int i=0;i<names.Length;i++)
				{
					string name = names[i];
					if (IsThisCategory(name.ToLower()))
					{
						ValidDNA.Add(new DNAHolder(name,values[i],i,d));
					}
				}

			}

			ValidDNA.Sort( );
			
			foreach(DNAHolder dna in ValidDNA)
			{
				GameObject go = GameObject.Instantiate(DnaEditor);
				go.transform.SetParent(ContentArea.transform);
				go.transform.localScale = new Vector3(1f, 1f, 1f);//Set the scale back to 1
				DNAEditor de = go.GetComponentInChildren<DNAEditor>();
			de.Initialize(dna.name.BreakupCamelCase(),dna.index,dna.dnaBase,Avatar,dna.value);
				go.SetActive(true);
				CreatedObjects.Add(go);
			}
		}

19 View Source File : StlFileImporter.cs
License : Apache License 2.0
Project Creator : Algoryx

public static GameObject[] Instantiate( string stlFile,
                                            float normalSmoothAngleThreshold,
                                            Action<Object> onCreate )
    {
      var createdParents = new List<GameObject>();
      var meshes = Read( stlFile, normalSmoothAngleThreshold );
      if ( meshes.Length == 0 ) {
        Debug.LogWarning( $"{stlFile} contained 0 meshes." );
        return createdParents.ToArray();
      }

      var filename = new FileInfo( stlFile).Name;
      filename = filename.Substring( 0, filename.LastIndexOf( '.' ) );
      var parent = meshes.Length > 1 ?
                      new GameObject( Factory.CreateName( filename ) ) :
                      null;
      if ( parent != null ) {
        createdParents.Add( parent );
        onCreate?.Invoke( parent );
      }

      foreach ( var mesh in meshes ) {
        var go                  = new GameObject( Factory.CreateName( filename ) );
        var filter              = go.AddComponent<MeshFilter>();
        var renderer            = go.AddComponent<MeshRenderer>();
        filter.sharedMesh       = mesh;
        renderer.sharedMaterial = Rendering.ShapeVisual.DefaultMaterial;
        if ( parent != null )
          go.transform.parent = parent.transform;
        else
          createdParents.Add( go );

        onCreate?.Invoke( go );
        onCreate?.Invoke( filter );
        onCreate?.Invoke( renderer );
      }

      return createdParents.ToArray();
    }

19 View Source File : CalendarController.cs
License : MIT License
Project Creator : ahmetozlu

void Start()
    {
        _calendarInstance = this;
        Vector3 startPos = _item.transform.localPosition;
        _dateItems.Clear();
        _dateItems.Add(_item);

        for (int i = 1; i < _totalDateNum; i++)
        {
            GameObject item = GameObject.Instantiate(_item) as GameObject;
            item.name = "Item" + (i + 1).ToString();
            item.transform.SetParent(_item.transform.parent);
            item.transform.localScale = Vector3.one;
            item.transform.localRotation = Quaternion.idenreplacedy;
            item.transform.localPosition = new Vector3((i % 7) * 31 + startPos.x, startPos.y - (i / 7) * 25, startPos.z);

            _dateItems.Add(item);
        }

        _dateTime = DateTime.Now;

        CreateCalendar();

        _calendarPanel.SetActive(false);
    }

19 View Source File : Model.cs
License : Apache License 2.0
Project Creator : Algoryx

public static Func<string, ResourceType, Object> CreateDefaultResourceLoader( string dataDirectory = "",
                                                                                  Func<string, ResourceType, Object> resourceLoad = null )
    {
      var isPlayerResource = resourceLoad == null;
      if ( !string.IsNullOrEmpty( dataDirectory ) ) {
        dataDirectory.Replace( '\\', '/' );
        if ( !dataDirectory.EndsWith( "/" ) )
          dataDirectory += '/';
      }

      var loadedInstances = new List<GameObject>();
      Func<string, ResourceType, Object> resourceLoader = ( resourceFilename, type ) =>
      {
        if ( type == ResourceType.FinalizedLoad ) {
          loadedInstances.ForEach( instance => Object.DestroyImmediate( instance ) );
          loadedInstances = null;
          return null;
        }

        if ( resourceFilename.StartsWith( "package:/" ) )
          resourceFilename = dataDirectory + resourceFilename.Substring( "package://".Length );
        else if ( !string.IsNullOrEmpty( dataDirectory ) )
          resourceFilename = dataDirectory + resourceFilename;

        // Makes resourceFilename relative to the application root directory,
        // expands any ".." in the path and replaces any \ with /.
        resourceFilename = resourceFilename.PrettyPath();

        var hasExtension = Path.HasExtension( resourceFilename );
        var isStlFile    = hasExtension && Path.GetExtension( resourceFilename ).ToLowerInvariant() == ".stl";
        var isCollada    = hasExtension && !isStlFile && Path.GetExtension( resourceFilename ).ToLowerInvariant() == ".dae";

        // STL file we instantiate it and delete them at FinalizeLoad.
        if ( isStlFile ) {
          var stlInstances = StlFileImporter.Instantiate( resourceFilename );
          loadedInstances.AddRange( stlInstances );
          return stlInstances.FirstOrDefault();
        }
        // Remove file extension when using Resources.Load.
        else if ( isPlayerResource && hasExtension )
          resourceFilename = resourceFilename.Substring( 0, resourceFilename.LastIndexOf( '.' ) );

        // Search for .obj file instead of Collada if we're not loading from Resources.
        if ( !isPlayerResource &&
             !File.Exists( resourceFilename ) &&
             isCollada )
          resourceFilename = resourceFilename.Substring( 0, resourceFilename.Length - 3 ) + "obj";

        var resource = resourceLoad != null ?
                         resourceLoad( resourceFilename, type ) :
                         Resources.Load<Object>( resourceFilename );

        if ( !isPlayerResource && isCollada && resource != null ) {
          var colladaInfo = Utils.ParseColladaInfo( resourceFilename );
          var resourceGo = resource as GameObject;
          // Model implementation replacedumes Z-up, anything other than that
          // has to be transformed.
          if ( resourceGo != null && !colladaInfo.IsDefault ) {
            var colladaInstance = Object.Instantiate<GameObject>( resourceGo );
            if ( colladaInfo.UpAxis == Utils.ColladaInfo.Axis.Y )
              colladaInstance.transform.rotation = Quaternion.Euler( -90, 0, 0 ) * colladaInstance.transform.rotation;
            else if ( colladaInfo.UpAxis == Utils.ColladaInfo.Axis.X )
              colladaInstance.transform.rotation = Quaternion.Euler( -90, 0, 90 ) * colladaInstance.transform.rotation;
            loadedInstances.Add( colladaInstance );
            resource = colladaInstance;
          }
        }

        return resource;
      };
      return resourceLoader;
    }

19 View Source File : DebugRenderManager.cs
License : Apache License 2.0
Project Creator : Algoryx

public static void OnEditorDestroy()
    {
      if ( !HasInstance )
        return;

      List<GameObject> gameObjectsToDestroy = new List<GameObject>();
      foreach ( var node in Instance.Children ) {
        OnSelectionProxy selectionProxy = node.GetComponent<OnSelectionProxy>();
        if ( selectionProxy != null )
          gameObjectsToDestroy.Add( selectionProxy.gameObject );
      }

      while ( gameObjectsToDestroy.Count > 0 ) {
        DestroyImmediate( gameObjectsToDestroy[ gameObjectsToDestroy.Count - 1 ] );
        gameObjectsToDestroy.RemoveAt( gameObjectsToDestroy.Count - 1 );
      }
    }

19 View Source File : RollerCoaster.cs
License : MIT License
Project Creator : ajayyy

public GameObject AddTrackPiece (Vector3 totalAngle, Vector3 modifiedPosition, Vector3 eulerAngles, Vector3 startAngle, Vector3 offset, float percentageOfTrack, int secondCurveStart) {
        GameObject newTrackPiece;

        if(unusedTrackPieces.Count > 0) {
            newTrackPiece = unusedTrackPieces[0];
            unusedTrackPieces.RemoveAt(0);

            newTrackPiece.SetActive(true);
        } else {
            newTrackPiece = Instantiate(trackPrefab, transform);

            TrackPiece trackPieceClreplaced = newTrackPiece.GetComponent<TrackPiece>();

            trackPieceClreplaced.Start();
            trackPieceClreplaced.rollerCoaster = this;
        }

        //reset position and angle before adjusting the track
        newTrackPiece.transform.position = Vector3.zero;
        newTrackPiece.transform.localEulerAngles = Vector3.zero;

        TrackPiece newTrackPieceClreplaced = newTrackPiece.GetComponent<TrackPiece>();

        newTrackPieceClreplaced.totalAngle = totalAngle;
        trackPieces.Add(newTrackPiece);

        //adjust the track
        newTrackPieceClreplaced.AdjustTrack(totalAngle, startAngle, percentageOfTrack, secondCurveStart);

        //set track rotation (after adjustment to make sure the adjustment process goes well)
        newTrackPiece.transform.eulerAngles = eulerAngles;
        //subtract offset
        newTrackPiece.transform.position = modifiedPosition - offset;

        return newTrackPiece;
    }

19 View Source File : Find.cs
License : Apache License 2.0
Project Creator : Algoryx

public static GameObject[] ChildrenList( GameObject gameObject )
    {
      if ( gameObject == null )
        return null;

      GameObject root = Find.RootGameObject( gameObject );
      RigidBody[] bodies = root.GetComponentsInChildren<RigidBody>();
      Collide.Shape[] shapes = root.GetComponentsInChildren<Collide.Shape>();

      List<GameObject> gameObjects = new List<GameObject>();
      foreach ( var rb in bodies )
        gameObjects.Add( rb.gameObject );
      foreach ( var shape in shapes )
        gameObjects.Add( shape.gameObject );

      gameObjects.Add( null );

      int indexOfSelected = gameObjects.IndexOf( gameObject );
      if ( indexOfSelected > 0 && gameObjects.Count > 1 ) {
        GameObject tmp = gameObjects[ 0 ];
        gameObjects[ 0 ] = gameObject;
        gameObjects[ indexOfSelected ] = tmp;
      }

      return gameObjects.ToArray();
    }

19 View Source File : BaseEventSystem.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public virtual void Register(GameObject listener)
        {
            // Because components on an object can change during its lifetime, we can't enumerate all handlers on an object 
            // at this point in time and register them via the new API.
            // This forces us to store an object and use ExecuteEvents traversal at time of handling events.
            if (eventExecutionDepth == 0)
            {
                if (!EventListeners.Contains(listener))
                {
                    // Due to how events are sent to game objects, if any of registered handlers sits on a 
                    // registered object it will receive any event preplaceded to this object.
                    // We need to mark such handlers, so they don't receive their events twice.
                    // It can be checked in HandleEvent with less code, but this becomes a 
                    // performance bottleneck with many handlers in the system

                    bool report = false;
                    foreach (var typeEntry in EventHandlersByType)
                    {
                        for (int index = 0; index < typeEntry.Value.Count; index++)
                        {
                            var handlerEntry = typeEntry.Value[index];

                            var comp = handlerEntry.handler as Component;

                            if (comp != null && comp.gameObject == listener)
                            {
                                handlerEntry.parentObjectIsInObjectCollection = true;
                                typeEntry.Value[index] = handlerEntry;
                                report = true;
                            }
                        }
                    }

                    if (report)
                    {
                        WarnAboutConflictingApis(listener.name);
                    }

                    EventListeners.Add(listener);
                }
            }
            else
            {
                postponedObjectActions.Add(Tuple.Create(Action.Add, listener));
            }
        }

19 View Source File : RuntimeObjects.cs
License : Apache License 2.0
Project Creator : Algoryx

private void Update()
    {
      gameObject.transform.position = Vector3.zero;
      gameObject.transform.rotation = Quaternion.idenreplacedy;
      // Change parent before scale is set - otherwise scale will be preserved.
      // E.g., move "this" to a parent with scale x, scale will be set,
      // parent = null will remove the parent but the scale will be preserved.
      // Fix - set scale after set parent.
      gameObject.transform.parent = null;
      gameObject.transform.localScale = Vector3.one;

      List<GameObject> rootsToRemove = new List<GameObject>();
      foreach ( Transform rootTransform in transform ) {
        rootTransform.position   = Vector3.zero;
        rootTransform.rotation   = Quaternion.idenreplacedy;
        rootTransform.localScale = Vector3.one;

        if ( rootTransform.childCount == 0 )
          continue;
        var selectionProxy = rootTransform.GetChild( 0 ).GetComponent<Utils.OnSelectionProxy>();
        if ( selectionProxy == null || selectionProxy.Component == null )
          rootsToRemove.Add( rootTransform.gameObject );
      }

      foreach ( var kvp in m_potentiallyDeletedParents ) {
        if ( kvp.Key != null )
          continue;

        var rootTransform = transform.Find( kvp.Value );
        if ( rootTransform == null )
          continue;

        if ( !rootsToRemove.Contains( rootTransform.gameObject ) )
          rootsToRemove.Add( rootTransform.gameObject );
      }
      m_potentiallyDeletedParents.Clear();

      while ( rootsToRemove.Count > 0 ) {
        DestroyImmediate( rootsToRemove.Last() );
        rootsToRemove.RemoveAt( rootsToRemove.Count - 1 );
      }

      if ( transform.childCount == 0 )
        DestroyImmediate( gameObject );
    }

19 View Source File : CoasterSpawning.cs
License : MIT License
Project Creator : ajayyy

void Update () {

        //print(rightController.GetComponent<TriggerData>().colliding);

        GameController gameController = GameController.instance;

        RaycastHit groundHit;

        bool groundBoxCastCollided = Physics.BoxCast(rightController.transform.position, (options[currentCoaster].GetComponent<BoxCollider>()).size * options[currentCoaster].transform.localScale.x / 2, Vector3.down, out groundHit, Quaternion.Euler(new Vector3(180, 0, 0)));

        if (groundBoxCastCollided) {
            currentThumbnail.transform.position = new Vector3(rightController.transform.position.x, groundHit.point.y, rightController.transform.position.z);
        }
        currentThumbnail.transform.eulerAngles = new Vector3(0, rightController.transform.eulerAngles.y, 0);

        if (currentMode == 0) {

            if (Input.GetAxis("RightTrigger") == 1 && !lastspawned) {

                if (groundBoxCastCollided) {

                    Vector3 spawnPosition = currentThumbnail.transform.position;

                    float spawnRotation = currentThumbnail.transform.eulerAngles.y;

                    if (groundHit.collider.gameObject.tag == "Track") {

                        Vector3 spawnPositionForward = groundHit.collider.gameObject.transform.position + (groundHit.collider.gameObject.transform.forward * ((BoxCollider)groundHit.collider).size.z) * groundHit.collider.gameObject.transform.localScale.x;
                        Vector3 spawnPositionBackward = groundHit.collider.gameObject.transform.position + ((-groundHit.collider.gameObject.transform.forward) * ((BoxCollider)groundHit.collider).size.z) * groundHit.collider.gameObject.transform.localScale.x;

                        float distForward = Vector3.Distance(currentThumbnail.transform.position, spawnPositionForward);
                        float distBackward = Vector3.Distance(currentThumbnail.transform.position, spawnPositionBackward);

                        if(distForward < distBackward) {
                            spawnPosition = spawnPositionForward;
                        } else {
                            spawnPosition = spawnPositionBackward;
                        }

                        spawnRotation = groundHit.collider.gameObject.transform.eulerAngles.y;
                    }

                    lastspawned = true;

                    GameObject newCoaster = Instantiate(options[currentCoaster]);

                    newCoaster.transform.parent = newCoaster.transform.root;

                    newCoaster.transform.position = spawnPosition;
                    newCoaster.transform.eulerAngles = new Vector3(0, spawnRotation, 0);
                }

            } else if (Input.GetAxis("RightTrigger") != 1) {
                lastspawned = false;
            }

            if (Input.GetButtonDown("RightTrackpadClick") && gameController.rightController.GetAxis().y > 0.5) {
                //change mode
                currentMode = 1;
                modeText.GetComponent<TextMesh>().text = "Move Mode";
                modeText.GetComponent<Animator>().SetTrigger("fade");

                currentThumbnail.SetActive(false);

            } else if (Input.GetButtonDown("RightTrackpadClick") && gameController.rightController.GetAxis().y < -0.5) {
                //change mode
                currentMode = 1;
                modeText.GetComponent<TextMesh>().text = "Move Mode";
                modeText.GetComponent<Animator>().SetTrigger("fade");

                currentThumbnail.SetActive(false);

            } else if (Input.GetButtonDown("RightTrackpadClick") && gameController.rightController.GetAxis().x > 0) {
                currentCoaster++;

                if (currentCoaster >= options.Length) {
                    currentCoaster = 0;
                }

                Destroy(currentThumbnail);
                currentThumbnail = Instantiate(thumbnails[currentCoaster]);
                //currentThumbnail.transform.parent = thumbnailPlacement.transform;
                currentThumbnail.transform.localPosition = Vector3.zero;
                currentThumbnail.transform.localEulerAngles = Vector3.zero;
            } else if (Input.GetButtonDown("RightTrackpadClick") && gameController.rightController.GetAxis().x < 0) {
                currentCoaster--;

                if (currentCoaster < 0) {
                    currentCoaster = options.Length - 1;
                }
                Destroy(currentThumbnail);
                currentThumbnail = Instantiate(thumbnails[currentCoaster]);
                //currentThumbnail.transform.parent = thumbnailPlacement.transform;
                currentThumbnail.transform.localPosition = Vector3.zero;
                currentThumbnail.transform.localEulerAngles = Vector3.zero;
            }

        } else if(currentMode == 1) {

            TriggerData triggerData = rightController.GetComponent<TriggerData>();

            if (triggerData.collidingObjects.Count > 0 && Input.GetAxis("RightTrigger") >= 0.96 && !attachedObjects.Contains(triggerData.collidingObjects[0])) {
                triggerData.collidingObjects[0].transform.parent = thumbnailPlacement.transform;
                triggerData.collidingObjects[0].GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeAll;

                attachedObjects.Add(triggerData.collidingObjects[0]);
            }

            if (attachedObjects.Count > 0 && Input.GetAxis("RightTrigger") == 0) {
                attachedObjects[0].transform.parent = transform.root;

                print(rightDevice.velocity);

                attachedObjects[0].GetComponent<Rigidbody>().constraints = RigidbodyConstraints.None;
                attachedObjects[0].GetComponent<Rigidbody>().AddForce(rightDevice.velocity * 100);

                attachedObjects.RemoveAt(0);
            }

            if (Input.GetButtonDown("RightTrackpadClick") && gameController.rightController.GetAxis().y > 0.5) {

                //change mode
                currentMode = 0;

                modeText.GetComponent<TextMesh>().text = "Place Mode";
                modeText.GetComponent<Animator>().SetTrigger("fade");

                currentThumbnail.SetActive(true);

            } else if (Input.GetButtonDown("RightTrackpadClick") && gameController.rightController.GetAxis().y < -0.5) {

                //change mode
                currentMode = 0;

                modeText.GetComponent<TextMesh>().text = "Place Mode";
                modeText.GetComponent<Animator>().SetTrigger("fade");

                currentThumbnail.SetActive(true);

            }
        }


    }

19 View Source File : DisableCollisionsTool.cs
License : Apache License 2.0
Project Creator : Algoryx

private void HandleSelectedObject( GameObject selected )
    {
      if ( selected == null )
        return;

      if ( !m_selected.Contains( selected ) )
        m_selected.Add( selected );

      EditorUtility.SetDirty( m_mainObject );
    }

19 View Source File : UnityPointCloudExample.cs
License : MIT License
Project Creator : 734843327

public void Start()
    {
        UnityARSessionNativeInterface.ARFrameUpdatedEvent += ARFrameUpdated;
        if (PointCloudPrefab != null)
        {
            pointCloudObjects = new List<GameObject> ();
            for (int i =0; i < numPointsToShow; i++)
            {
                pointCloudObjects.Add (Instantiate (PointCloudPrefab));
            }
        }
    }

19 View Source File : ConvertableEditor.cs
License : Apache License 2.0
Project Creator : allenai

public override void OnInspectorGUI() {
        Convertable c = (Convertable)target;

        GUI.color = Color.grey;

        if (c.CurrentState < 0) {
            GUI.color = Color.red;
        }

        Animator a = c.GetComponent<Animator>();
        if (a == null) {
            a = c.gameObject.AddComponent<Animator>();
            a.runtimeAnimatorController = Resources.Load("StateAnimController") as RuntimeAnimatorController;
        }

        EditorGUILayout.BeginVertical(EditorStyles.helpBox);
        GUI.color = Color.white;
        EditorGUILayout.LabelField("States:", EditorStyles.miniLabel);

        c.DefaultState = EditorGUILayout.IntSlider("Default State", c.DefaultState + 1, 1, 4) - 1;
        c.EditorState = EditorGUILayout.IntSlider("Editor State", c.EditorState + 1, 1, 4) - 1;
        EditorGUILayout.LabelField("Current state: " + (c.CurrentState + 1).ToString());

        if (c.States == null || c.States.Length < 2) {
            c.States = new SimObjState[2];
            c.States[0] = new SimObjState();
            c.States[1] = new SimObjState();
            c.States[0].Type = c.GetComponent<SimObj>().Type;
        }

        // name all state objects for their state
        foreach (SimObjState state in c.States) {
            if (state.Obj != null) {
                // state.Obj.name = state.Type.ToString ();
            }
        }

        List<GameObject> availableItems = new List<GameObject>();
        Transform baseTransform = c.transform.Find("Base");
        if (baseTransform == null) {
            GUI.color = Color.red;
            EditorGUILayout.LabelField("MUST HAVE BASE OBJECT!");
        } else {
            foreach (Transform child in baseTransform) {
                availableItems.Add(child.gameObject);
            }

            List<string> choicesList = new List<string>();
            foreach (GameObject availableItem in availableItems) {
                choicesList.Add(availableItem.name);
            }
            string[] choices = choicesList.ToArray();

            int stateIndex = 0;
            foreach (SimObjState state in c.States) {
                GUI.color = Color.white;
                if (stateIndex == c.CurrentState) {
                    GUI.color = Color.Lerp(Color.white, Color.green, 0.5f);
                }
                EditorGUILayout.BeginVertical(EditorStyles.helpBox);
                EditorGUILayout.LabelField("State " + (stateIndex + 1).ToString());
                state.Type = (SimObjType)EditorGUILayout.EnumPopup("Type", state.Type);
                int stateObjIndex = 0;
                if (state.Obj != null) {
                    for (int i = 0; i < choices.Length; i++) {
                        if (state.Obj.name.Equals(choices[i])) {
                            stateObjIndex = i;
                            break;
                        }
                    }
                }
                stateObjIndex = EditorGUILayout.Popup("Object", stateObjIndex, choices);
                if (availableItems.Count > 0) {
                    state.Obj = availableItems[stateObjIndex];
                }
                EditorGUILayout.EndVertical();
                stateIndex++;
            }
        }
        EditorGUILayout.EndVertical();


        GUI.color = Color.grey;
        EditorGUILayout.BeginVertical(EditorStyles.helpBox);
        GUI.color = Color.white;
        EditorGUILayout.LabelField("Utilities:", EditorStyles.miniLabel);
        if (baseTransform.childCount == 0 && GUILayout.Button("Create sub-type objects from base")) {
            GameObject newBaseObj = new GameObject("Base");
            newBaseObj.transform.parent = baseTransform.parent;
            newBaseObj.transform.position = baseTransform.position;
            newBaseObj.transform.rotation = baseTransform.rotation;
            newBaseObj.transform.localScale = baseTransform.localScale;
            baseTransform.parent = newBaseObj.transform;
            baseTransform.name = c.States[0].Type.ToString();
            c.States[0].Obj = baseTransform.gameObject;
            GameObject newStateObj = new GameObject("State");
            newStateObj.transform.parent = baseTransform.parent;
            newStateObj.transform.position = baseTransform.position;
            newStateObj.transform.rotation = baseTransform.rotation;
            newStateObj.transform.localScale = baseTransform.localScale;
            c.States[1].Obj = newStateObj;
        }
        EditorGUILayout.EndVertical();

        EditorUtility.SetDirty(c.gameObject);
        EditorUtility.SetDirty(c);
    }

19 View Source File : ArrowHand.cs
License : MIT License
Project Creator : ajayyy

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 View Source File : InstantiatePrefabTest.cs
License : Apache License 2.0
Project Creator : allenai

public Bounds BoundsOfObject(string objectType, int variation) {
        // GameObject topObject = GameObject.Find("Objects");
        List<GameObject> candidates = new List<GameObject>();
        foreach (GameObject go in prefabs) {
            if (go.GetComponent<SimObjPhysics>().Type == (SimObjType)Enum.Parse(typeof(SimObjType), objectType)) {
                candidates.Add(go);
            }
        }

        Bounds objBounds = UtilityFunctions.CreateEmptyBounds();
        foreach (Renderer r in candidates[variation - 1].GetComponentsInChildren<Renderer>()) {
            if (r.enabled) {
                objBounds.Encapsulate(r.bounds);
            }
        }
        return objBounds;
    }

19 View Source File : OVROverlaySample.cs
License : MIT License
Project Creator : absurd-joy

void SimulateLevelLoad()
        {
            int numToPrint = 0;
            for (int p = 0; p < numLoopsTrigger; p++)
            {
                numToPrint++;
            }
            Debug.Log("Finished " + numToPrint + " Loops");
            Vector3 playerPos = mainCamera.transform.position;
            playerPos.y = 0.5f;
            // Generate a bunch of blocks, "blocking" the mainthread ;)
            for (int j = 0; j < numLevels; j++)
            {
                for (var i = 0; i < numObjectsPerLevel; i++)
                {
                    var angle = i * Mathf.PI * 2 / numObjectsPerLevel;
                    float stagger = (i % 2 == 0) ? 1.5f : 1.0f;
                    var pos = new Vector3(Mathf.Cos(angle), 0, Mathf.Sin(angle)) * cubeSpawnRadius * stagger;
                    pos.y = j * heightBetweenItems;
                    var newInst = Instantiate(prefabForLevelLoadSim, pos + playerPos, Quaternion.idenreplacedy);
                    var newObjTransform = newInst.transform;
                    newObjTransform.LookAt(playerPos);
                    Vector3 newAngle = newObjTransform.rotation.eulerAngles;
                    newAngle.x = 0.0f;
                    newObjTransform.rotation = Quaternion.Euler(newAngle);
                    spawnedCubes.Add(newInst);
                }
            }
        }

19 View Source File : ExpRoomEditor.cs
License : Apache License 2.0
Project Creator : allenai

public static List<(SimObjPhysics, string)> AddAllPrefabsAsOnlyChildrenOfObject(
        GameObject parent,
        bool onlyPickupable,
        bool onlyReceptacles,
        string tag = ""
    ) {
        List <(SimObjPhysics, string)> sopAndPrefabTuples = new List <(SimObjPhysics, string)>();
        string[] allPrefabs = GetAllPrefabs();
        int numAdded = 0;
        foreach (string prefab in allPrefabs) {
            GameObject go = null;
            try {
                Debug.Log($"Checking {prefab}");
                go = (GameObject) replacedetDatabase.LoadMainreplacedetAtPath(prefab);
                SimObjPhysics sop = go.GetComponent<SimObjPhysics>();

                // if (sop != null && sop.Type.ToString() == "Box" && sop.GetComponent<CanOpen_Object>()) {
                if (sop != null) {
                    bool pickupable = sop.PrimaryProperty == SimObjPrimaryProperty.CanPickup;
                    bool isReceptacle = Array.IndexOf(
                        sop.SecondaryProperties,
                        SimObjSecondaryProperty.Receptacle
                    ) > -1 && sop.ReceptacleTriggerBoxes != null;
                    if (
                        (pickupable || !onlyPickupable)
                        && (isReceptacle || !onlyReceptacles)
                    ) {
                        sopAndPrefabTuples.Add((go.GetComponent<SimObjPhysics>(), prefab));
                        numAdded += 1;
                    }
                }
            } catch {
                try {
                    if (go) {
                        DestroyImmediate(go);
                    }
                } catch {}
                Debug.LogWarning($"Prefab {prefab} failed to load.");
            }
        }

        sopAndPrefabTuples = sopAndPrefabTuples.OrderBy(
            sopAndPath => (
                sopAndPath.Item1.Type.ToString(),
                int.Parse("0" + new string(
                    sopAndPath.Item1.name
                    .Split('/')
                    .Last()
                    .Where(c => char.IsDigit(c))
                    .ToArray()))
            )
        ).ToList();
        Debug.Log(
            $"Found {allPrefabs.Length} total prefabs of which {sopAndPrefabTuples.Count} were SimObjPhysics satisfying"
            + $"onlyPickupable=={onlyPickupable} and onlyReceptacles=={onlyReceptacles}."
        );

        UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene());

        // Note that you cannot (unfortunately) combine the two below loops into
        // a single loop as doing something like
        //   foreach (Transform child in parent.transform) {
        //       DestroyImmediate(child.gameObject);
        //   }
        // Will actually miss a large number of children because the way that looping through
        // parent.transform works (deleting while iterating results in missing elements).
        List<GameObject> toDestroy = new List<GameObject>();
        foreach (Transform child in parent.transform) {
            toDestroy.Add(child.gameObject);
        }
        foreach (GameObject child in toDestroy) {
            Debug.Log($"Attempting to destroy {child.gameObject}");
            DestroyImmediate(child);
        }

        if (tag != "") {
            tag = $"_{tag}";
        }
        for (int i = 0; i < sopAndPrefabTuples.Count; i++) {
            SimObjPhysics sop = sopAndPrefabTuples[i].Item1;
            string path = sopAndPrefabTuples[i].Item2;
            string hash = CreateSHA256Hash(path).Substring(0, 8);

            GameObject go = (GameObject) PrefabUtility.InstantiatePrefab(sop.gameObject);

            SimObjPhysics newSop = go.GetComponent<SimObjPhysics>();

            if (onlyReceptacles && sop.Type.ToString() == "Box") {
                OpenBoxFlapsMore(newSop);
            }

            FixBoundingBox(newSop);

            go.name = $"{sop.Type.ToString()}{tag}_{hash}";
            go.SetActive(false);
            go.transform.position = new Vector3(-5f, i * 0.05f, -5f);
            go.transform.parent = parent.transform;

            sopAndPrefabTuples[i] = (newSop, path);
        }

        return sopAndPrefabTuples;
    }

19 View Source File : SpawnOnMap.cs
License : MIT License
Project Creator : alen-smajic

void Start()
		{
			_locations = new Vector2d[_locationStrings.Length];
			_spawnedObjects = new List<GameObject>();
			for (int i = 0; i < _locationStrings.Length; i++)
			{
				var locationString = _locationStrings[i];
				_locations[i] = Conversions.StringToLatLon(locationString);
				var instance = Instantiate(_markerPrefab);
				instance.transform.localPosition = _map.GeoToWorldPosition(_locations[i], true);
				instance.transform.localScale = new Vector3(_spawnScale, _spawnScale, _spawnScale);
				_spawnedObjects.Add(instance);
			}
		}

19 View Source File : UtilityFunctions.cs
License : Apache License 2.0
Project Creator : allenai

public static Collider[] collidersObjectCollidingWith(
        GameObject go,
        List<GameObject> ignoreGameObjects = null,
        float expandBy = 0.0f,
        bool useBoundingBoxInChecks = false
        ) {
        if (ignoreGameObjects == null) {
            ignoreGameObjects = new List<GameObject>();
        }
        ignoreGameObjects.Add(go);
        HashSet<Collider> ignoreColliders = new HashSet<Collider>();
        foreach (GameObject toIgnoreGo in ignoreGameObjects) {
            foreach (Collider c in toIgnoreGo.GetComponentsInChildren<Collider>()) {
                ignoreColliders.Add(c);
            }
        }

        HashSet<Collider> collidersSet = new HashSet<Collider>();
        int layerMask = 1 << 8 | 1 << 10;
        foreach (CapsuleCollider cc in go.GetComponentsInChildren<CapsuleCollider>()) {
            foreach (Collider c in PhysicsExtensions.OverlapCapsule(cc, layerMask, QueryTriggerInteraction.Ignore, expandBy)) {
                if (!ignoreColliders.Contains(c)) {
                    collidersSet.Add(c);
                }
            }
        }
        foreach (BoxCollider bc in go.GetComponentsInChildren<BoxCollider>()) {
            if ("BoundingBox" == bc.gameObject.name && (!useBoundingBoxInChecks)) {
                continue;
            }
            foreach (Collider c in PhysicsExtensions.OverlapBox(bc, layerMask, QueryTriggerInteraction.Ignore, expandBy)) {
                if (!ignoreColliders.Contains(c)) {
                    collidersSet.Add(c);
                }
            }
        }
        foreach (SphereCollider sc in go.GetComponentsInChildren<SphereCollider>()) {
            foreach (Collider c in PhysicsExtensions.OverlapSphere(sc, layerMask, QueryTriggerInteraction.Ignore, expandBy)) {
                if (!ignoreColliders.Contains(c)) {
                    collidersSet.Add(c);
                }
            }
        }
        return collidersSet.ToArray();
    }

19 View Source File : G_RttManager.cs
License : MIT License
Project Creator : 1ZouLTReX1

private void Init()
        {
            m_graphyManager = transform.root.GetComponentInChildren<GraphyManager>();

            m_rectTransform = GetComponent<RectTransform>();

            m_rttGraph = GetComponent<G_RttGraph>();
            m_rttMonitor = GetComponent<G_RttMonitor>();
            m_rttText = GetComponent<G_RttText>();

            foreach (Transform child in transform)
            {
                if (child.parent == transform)
                {
                    m_childrenGameObjects.Add(child.gameObject);
                }
            }
        }

19 View Source File : ContinuousMovement.cs
License : Apache License 2.0
Project Creator : allenai

public static IEnumerator rotateAroundPoint(
            PhysicsRemoteFPSAgentController controller,
            CollisionListener collisionListener,
            Transform updateTransform,
            Vector3 rotatePoint,
            Quaternion targetRotation,
            float fixedDeltaTime,
            float degreesPerSecond,
            bool returnToStartPropIfFailed = false
        ) {
            bool teleport = (degreesPerSecond == float.PositiveInfinity) && fixedDeltaTime == 0f;

            // To figure out how to translate/rotate the undateTransform
            // we just create two proxy game object that represent the
            // transforms of objects sitting at the updateTransform
            // position (fulcrum) and the rotatePoint (wristProxy). The
            // wristProxy transform is a child of the fulcrum transform.
            // As we rotate the fulcrum transform we thus figure out how the
            // updateTransform should be updated by looking at how the
            // wristProxy transform has changed.

            GameObject fulcrum = new GameObject();
            fulcrum.transform.position = rotatePoint;
            fulcrum.transform.rotation = updateTransform.rotation;
            targetRotation = fulcrum.transform.rotation * targetRotation;

            GameObject wristProxy = new GameObject();
            wristProxy.transform.parent = fulcrum.transform;
            wristProxy.transform.position = updateTransform.position;
            wristProxy.transform.rotation = updateTransform.rotation;

            List<GameObject> tmpObjects = new List<GameObject>();
            tmpObjects.Add(fulcrum);
            tmpObjects.Add(wristProxy);

            Func<Quaternion, Quaternion, Quaternion> directionFunc = (target, current) => target;
            Func<Quaternion, Quaternion, float> distanceFunc = (target, current) => Quaternion.Angle(current, target);

            Func<Transform, Quaternion> getRotFunc = (t) => t.rotation;
            Action<Transform, Quaternion> setRotFunc = (t, newRotation) => {
                t.rotation = newRotation;
                updateTransform.position = wristProxy.transform.position;
                updateTransform.rotation = newRotation;
            };
            Func<Transform, Quaternion, Quaternion> nextRotFunc = (t, target) => {
                return Quaternion.RotateTowards(t.rotation, target, fixedDeltaTime * degreesPerSecond);
            };

            if (teleport) {
                nextRotFunc = (t, direction) => targetRotation;
            }

            return finallyDestroyGameObjects(
                gameObjectsToDestroy: tmpObjects,
                steps: updateTransformPropertyFixedUpdate(
                    controller: controller,
                    collisionListener: collisionListener,
                    moveTransform: fulcrum.transform,
                    target: targetRotation,
                    getProp: getRotFunc,
                    setProp: setRotFunc,
                    nextProp: nextRotFunc,
                    getDirection: directionFunc,
                    distanceMetric: distanceFunc,
                    fixedDeltaTime: fixedDeltaTime,
                    returnToStartPropIfFailed: returnToStartPropIfFailed,
                    epsilon: 1e-3
                )
            );

        }

19 View Source File : PrefabModifier.cs
License : MIT License
Project Creator : alen-smajic

public override void Run(VectorEnreplacedy ve, UnityTile tile)
		{
			if (_options.prefab == null)
			{
				return;
			}

			GameObject go = null;

			if (_objects.ContainsKey(ve.GameObject))
			{
				go = _objects[ve.GameObject];
			}
			else
			{
				go = Instantiate(_options.prefab);
				_prefabList.Add(go);
				_objects.Add(ve.GameObject, go);
				go.transform.SetParent(ve.GameObject.transform, false);
			}

			PositionScaleRectTransform(ve, tile, go);

			if (_options.AllPrefabsInstatiated != null)
			{
				_options.AllPrefabsInstatiated(_prefabList);
			}
		}

19 View Source File : PathDataHolder.cs
License : MIT License
Project Creator : Adsito

public void IncreaseNodesRes()
    {
        GameObject pathNodeObj = Resources.Load<GameObject>("Paths/PathNode");
        int amount = (int)(resolutionFactor * transform.childCount);
        if (amount == 0)
            return;
        int step = transform.childCount / amount;
        
        List<GameObject> newNodes = new List<GameObject>();

        for (int i = 0; i < transform.childCount; i += step)
        {
            if (i + 1 >= transform.childCount)
                continue;

            Transform current = transform.GetChild(i);
            Transform next = transform.GetChild(i+1);

            Vector3 pos = (current.position + next.position) / 2;
            GameObject newNode = Instantiate(pathNodeObj, pos, Quaternion.idenreplacedy);
            newNodes.Add(newNode);
        }
        int count = 0;
        for (int i = 0; i < newNodes.Count; i ++)
        {
            newNodes[i].transform.parent = transform;
            newNodes[i].transform.SetSiblingIndex((i*step)+count+1);
            count++;
        }
    }

19 View Source File : G_FpsManager.cs
License : MIT License
Project Creator : 1ZouLTReX1

private void Init()
        {
            m_graphyManager = transform.root.GetComponentInChildren<GraphyManager>();
            
            m_rectTransform = GetComponent<RectTransform>();

            m_fpsGraph      = GetComponent<G_FpsGraph>();
            m_fpsMonitor    = GetComponent<G_FpsMonitor>();
            m_fpsText       = GetComponent<G_FpsText>();

            foreach (Transform child in transform)
            {
                if (child.parent == transform)
                {
                    m_childrenGameObjects.Add(child.gameObject);
                }
            }
        }

19 View Source File : ProximityDetector.cs
License : MIT License
Project Creator : 39M

void Awake() {
      proximityWatcherCoroutine = proximityWatcher();
      if (TagName != "") {
        GameObject[] taggedObjects = GameObject.FindGameObjectsWithTag(TagName);
        List<GameObject> targets = new List<GameObject>(taggedObjects.Length + TargetObjects.Length);
        for (int t = 0; t < TargetObjects.Length; t++) {
          targets.Add(TargetObjects[t]);
        }
        for (int t = 0; t < taggedObjects.Length; t++) {
          targets.Add(taggedObjects[t]);
        }
        TargetObjects = targets.ToArray();
      }
    }

19 View Source File : RandomWeaponGeneratorWindow.cs
License : MIT License
Project Creator : Abdelfattah-Radwan

private void LoadreplacedetReferences()
		{
			templates?.Clear();
			weaponBases?.Clear();
			stocks?.Clear();
			grips?.Clear();
			magazines?.Clear();
			scopes?.Clear();
			barrels?.Clear();

			string filePath = Path.Combine("Temp", replacedET_REFERENCES_INSTANCE_IDS_FILE_NAME);

			if (File.Exists(filePath))
			{
				List<int>[] lists = new List<int>[0];

				using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
				{
					lists = new BinaryFormatter().Deserialize(fileStream) as List<int>[];
				}

				lists[0].ForEach(id => templates?.Add(replacedetDatabase.LoadreplacedetAtPath<WeaponPropertiesTemplate>(replacedetDatabase.GetreplacedetPath(id))));
				lists[1].ForEach(id => weaponBases?.Add(replacedetDatabase.LoadreplacedetAtPath<WeaponBase>(replacedetDatabase.GetreplacedetPath(id))));
				lists[2].ForEach(id => stocks?.Add(replacedetDatabase.LoadreplacedetAtPath<GameObject>(replacedetDatabase.GetreplacedetPath(id))));
				lists[3].ForEach(id => grips?.Add(replacedetDatabase.LoadreplacedetAtPath<GameObject>(replacedetDatabase.GetreplacedetPath(id))));
				lists[4].ForEach(id => magazines?.Add(replacedetDatabase.LoadreplacedetAtPath<GameObject>(replacedetDatabase.GetreplacedetPath(id))));
				lists[5].ForEach(id => scopes?.Add(replacedetDatabase.LoadreplacedetAtPath<GameObject>(replacedetDatabase.GetreplacedetPath(id))));
				lists[6].ForEach(id => barrels?.Add(replacedetDatabase.LoadreplacedetAtPath<GameObject>(replacedetDatabase.GetreplacedetPath(id))));
			}
		}

19 View Source File : RollerCoaster.cs
License : MIT License
Project Creator : ajayyy

void Start () {
        //just for now, since we must start with one
        transform.Find("TrackPiece0").gameObject.GetComponent<TrackPiece>().rollerCoaster = this;
        trackPieces.Add(transform.Find("TrackPiece0").gameObject);

        //TODO: set tracksize dynamically based on calling the TrackPiece clreplaced

        //set track bone size based on scale
        trackBoneSize = defaultTrackBoneSize * GameController.instance.scale;
        trackWidth = defaultTrackWidth * GameController.instance.scale;

        currentTrack = trackPieces[0];
    }

19 View Source File : DebugRenderManager.cs
License : Apache License 2.0
Project Creator : Algoryx

protected void Update()
    {
      UpdateIsActiveForSynchronize();

      // When the application is playing we rely on callbacks
      // from the objects when they've synchronized their
      // transforms.
      if ( Application.isPlaying )
        return;

      // Shapes with inactive game objects will be updated below when we're
      // traversing all children.
      FindObjectsOfType<Collide.Shape>().ToList().ForEach(
        shape => SynchronizeShape( shape )
      );

      FindObjectsOfType<Constraint>().ToList().ForEach(
        constraint => constraint.AttachmentPair.Synchronize()
      );

      List<GameObject> gameObjectsToDestroy = new List<GameObject>();
      foreach ( var node in Children ) {
        OnSelectionProxy proxy = node.GetComponent<OnSelectionProxy>();

        if ( proxy == null )
          continue;

        if ( proxy.Target == null )
          gameObjectsToDestroy.Add( node );
        // FindObjectsOfType will not include the Shape if its game object is inactive.
        // We're handling that shape here instead.
        else if ( !proxy.Target.activeInHierarchy && proxy.Component is Collide.Shape )
          SynchronizeShape( proxy.Component as Collide.Shape );
      }

      while ( gameObjectsToDestroy.Count > 0 ) {
        DestroyImmediate( gameObjectsToDestroy.Last() );
        gameObjectsToDestroy.RemoveAt( gameObjectsToDestroy.Count - 1 );
      }
    }

See More Examples