FindObjectsOfType() public static method

public static FindObjectsOfType ( Type type ) : Object[]
type Type
return Object[]
コード例 #1
0
 /// <summary>
 /// Build planar graph of car spawners and points of fuel triggers
 /// </summary>
 private void BuildGraph()
 {
     _graph.AddRange(Object.FindObjectsOfType <RefuelingMark>().Select(refueling => Scale(refueling.transform.position.ToHex())));
     for (var i = 0; i < _graph.Count; i++)
     {
         for (var j = i + 1; j < _graph.Count; j++)
         {
             var currentEdge = new HexEdge(_graph[i], _graph[j]);
             var isAdd       = true;
             var removeEdges = new List <HexEdge>();
             var magnitude   = Hex.Distance(currentEdge.A, currentEdge.B);
             foreach (var edge in Edges.Where(edge => Intersection(currentEdge, edge)))
             {
                 if (magnitude < Hex.Distance(edge.A, edge.B))
                 {
                     removeEdges.Add(edge);
                 }
                 else
                 {
                     isAdd = false;
                     break;
                 }
             }
             if (isAdd && !Edges.Contains(currentEdge))
             {
                 Edges.Add(currentEdge);
                 foreach (var edge in removeEdges)
                 {
                     Edges.Remove(edge);
                 }
             }
         }
     }
 }
コード例 #2
0
    public static void GenerateNames()
    {
        Names.Clear();

        var uniqueNames = Object.FindObjectsOfType <UniqueName>();

        foreach (var uniqueName in uniqueNames)
        {
            var trimmedName = uniqueName.name.TrimEnd();
            if (!Names.Contains(trimmedName))
            {
                Names.Add(trimmedName);
                continue;
            }

            string baseName = trimmedName;
            if (Regex.IsMatch(baseName, @".+ \(\d+\)$"))
            {
                baseName = baseName.Substring(0, baseName.LastIndexOf("(", StringComparison.Ordinal)).TrimEnd();
            }

            string newName = baseName;
            int    index   = 1;
            while (Names.Contains(newName))
            {
                newName = baseName + " (" + index + ")";
                index++;
            }

            Debug.LogWarning("Object name changed from " + uniqueName.name + " to " + newName, uniqueName);
            uniqueName.name = newName;
            Names.Add(newName);
        }
    }
コード例 #3
0
    public void Initialize()
    {
        List <ViewableEntityInitializer> initializableEntities = Object.FindObjectsOfType <ViewableEntityInitializer>().ToList();

        foreach (ViewableEntityInitializer initializableEntity in initializableEntities)
        {
            List <BaseComponentMonoBehaviour> monoComponents = initializableEntity.GetComponents <BaseComponentMonoBehaviour>().ToList();

            IContext currentContext = _contexts.game;

            Entity entity = (Entity)currentContext.GetType().InvokeMember("CreateEntity", BindingFlags.InvokeMethod, null, currentContext, null);

            string componentLookupClassName = currentContext.contextInfo.name + "ComponentsLookup";
            Type[] componentTypes           = (Type[])Type.GetType(componentLookupClassName).GetField("componentTypes", BindingFlags.Public | BindingFlags.Static).GetValue(null);

            IComponent viewComponent = new ViewComponent {
                gameObject = initializableEntity.gameObject
            };
            int viewComponentIndex = Array.IndexOf(componentTypes, viewComponent.GetType());
            entity.AddComponent(viewComponentIndex, viewComponent);

            foreach (BaseComponentMonoBehaviour monoComponent in monoComponents)
            {
                var component      = monoComponent.Component;
                int componentIndex = Array.IndexOf(componentTypes, component.GetType());

                //@todo Implement univeral 'special case' initializers
                if (component.GetType() == typeof(NavAgentComponent))
                {
                    ((NavAgentComponent)component).value = initializableEntity.GetComponent <NavAgentBehaviour>();
                }

                entity.AddComponent(componentIndex, component);

                Object.Destroy(monoComponent);
            }

            initializableEntity.gameObject.Link(entity, currentContext);
            Object.Destroy(initializableEntity);
        }
    }
コード例 #4
0
        public static void Combine(GameObject staticBatchRoot, bool combineOnlyStatic)
        {
            GameObject[]      array = (GameObject[])Object.FindObjectsOfType(typeof(GameObject));
            List <GameObject> list  = new List <GameObject>();

            GameObject[] array2 = array;
            for (int i = 0; i < array2.Length; i++)
            {
                GameObject gameObject = array2[i];
                if (!(staticBatchRoot != null) || gameObject.transform.IsChildOf(staticBatchRoot.transform))
                {
                    if (!combineOnlyStatic || gameObject.isStaticBatchable)
                    {
                        list.Add(gameObject);
                    }
                }
            }
            array = list.ToArray();
            if (!Application.HasProLicense() && !Application.HasAdvancedLicense() && staticBatchRoot != null && array.Length > 0)
            {
                Debug.LogError("Your Unity license is not sufficient for Static Batching.");
            }
            InternalStaticBatchingUtility.Combine(array, staticBatchRoot);
        }
コード例 #5
0
    /// <summary>
    /// Build road
    /// </summary>
    public void BuildRoad()
    {
        BuildGraph();
        InitPathFinding();
        var edges = Edges.SelectMany(edge => Dijkstras.shortest_path(edge.A, edge.B,
                                                                     hex => _road.Contains(hex) ? 1 : (Rectifier(edge.A, edge.B, hex) ? 3 : 6)));

        _road.AddRange(_graph);
        foreach (var hex in edges.Where(hex => !_road.Contains(hex)))
        {
            _road.Add(hex);
        }

        foreach (var roadHex in _road)
        {
            CreateRoadObj(roadHex, _road.Concat(Object.FindObjectsOfType <RoadAddMark>().
                                                Select(mark => Scale(mark.transform.position.ToHex()))));
        }

        foreach (var mark in Object.FindObjectsOfType <RefuelingMark>())
        {
            Map.Instance.HexUnitMap[mark.transform.position.ToHex()].AddTrigger(mark);
        }
    }
コード例 #6
0
    /// <summary>
    /// Finds DataSetTrackableBehaviours for this dataset and associates them with the Trackables in the DataSet.
    /// VirtualButtonBehaviours created in the scene are associated with the VirtualButtons in the DataSet or created there.
    ///
    /// If there is a Trackable in the DataSet where no TrackableBehaviour exists yet, this Behaviour is created, together with its VirtualButtons.
    /// </summary>
    public void AssociateTrackableBehavioursForDataSet(DataSet dataSet)
    {
        // Step: Add all TrackableBehaviours that belong to this data set and
        // are already instantiated in the scene to the dictionary.
        DataSetTrackableBehaviour[] trackableBehaviours = (DataSetTrackableBehaviour[])
                                                          Object.FindObjectsOfType(typeof(DataSetTrackableBehaviour));

        // Initialize all Image Targets
        foreach (DataSetTrackableBehaviour trackableBehaviour in trackableBehaviours)
        {
            IEditorDataSetTrackableBehaviour editorTrackableBehaviour = trackableBehaviour;
            if (editorTrackableBehaviour.TrackableName == null)
            {
                Debug.LogError("Found Trackable without name.");
                continue;
            }

            // check if the TrackableBehaviour references this DataSet
            if (editorTrackableBehaviour.DataSetPath.Equals(dataSet.Path))
            {
                bool matchFound = false;

                // find the trackable to be associated with this TrackableBehaviour:
                foreach (Trackable trackable in dataSet.GetTrackables())
                {
                    if (trackable.Name.Equals(editorTrackableBehaviour.TrackableName))
                    {
                        if (trackableBehaviour is ImageTargetBehaviour &&
                            trackable is ImageTarget)
                        {
                            IEditorImageTargetBehaviour editorImageTargetBehaviour = (ImageTargetBehaviour)trackableBehaviour;

                            matchFound = true;

                            editorImageTargetBehaviour.InitializeImageTarget((ImageTarget)trackable);
                            mTrackableBehaviours[trackable.ID] = trackableBehaviour;
                            Debug.Log("Found Trackable named " + trackableBehaviour.Trackable.Name +
                                      " with id " + trackableBehaviour.Trackable.ID);
                        }
                        else if (trackableBehaviour is MultiTargetBehaviour &&
                                 trackable is MultiTarget)
                        {
                            matchFound = true;

                            IEditorMultiTargetBehaviour editorMultiTargetBehaviour = (MultiTargetBehaviour)trackableBehaviour;
                            editorMultiTargetBehaviour.InitializeMultiTarget((MultiTarget)trackable);
                            mTrackableBehaviours[trackable.ID] = trackableBehaviour;
                            Debug.Log("Found Trackable named " + trackableBehaviour.Trackable.Name +
                                      " with id " + trackableBehaviour.Trackable.ID);
                        }
                    }
                }

                if (!matchFound)
                {
                    Debug.LogError("Could not associate DataSetTrackableBehaviour '" + editorTrackableBehaviour.TrackableName +
                                   "' - no matching Trackable found in DataSet!");
                }
            }
        }


        // Step 2: Add all VirtualButtonBehaviours that belong to this data set
        // and are already instantiated in the scene to the dictionary.
        VirtualButtonBehaviour[] vbBehaviours = (VirtualButtonBehaviour[])
                                                Object.FindObjectsOfType(typeof(VirtualButtonBehaviour));
        AssociateVirtualButtonBehaviours(vbBehaviours, dataSet);

        // Step 3: Create TrackableBehaviours that are not existing in the scene.
        CreateMissingDataSetTrackableBehaviours(dataSet);
    }
コード例 #7
0
            public IEnumerator BallsMoveAtConstantVelocity()
            {
                // Wait for soccer player to load, kick ball, and then ball to be spawned
                yield return(new WaitUntil(() => Object.FindObjectOfType <SoccerPlayer>() != null));

                SoccerPlayer soccerPlayer = Object.FindObjectOfType <SoccerPlayer>();

                yield return(new WaitUntil(() => soccerPlayer.PlayerHasKickedBall()));

                yield return(new WaitUntil(() => Object.FindObjectOfType <BallProjectile>() != null));

                BallProjectile[] balls = Object.FindObjectsOfType <BallProjectile>();
                BallProjectile   ball1 = balls[0];
                BallProjectile   ball2 = balls[1];
                BallProjectile   ball3 = balls[2];

                float endingTime  = Time.time + Math.Max(Math.Max(ball1.ActualTimeToContact, ball2.ActualTimeToContact), ball3.ActualTimeToContact);
                float currentTime = Time.time;

                // For every frame before the ball arrives, its position should be
                // unchanged.
                List <double> ball1Scales = new List <double>();
                List <double> ball2Scales = new List <double>();
                List <double> ball3Scales = new List <double>();

                while (endingTime - currentTime > 0)
                {
                    ball1Scales.Add(ball1.transform.localScale.x);
                    ball2Scales.Add(ball2.transform.localScale.x);
                    ball3Scales.Add(ball3.transform.localScale.x);
                    yield return(new WaitForSeconds(0.05f));

                    currentTime = Time.time;
                }

                // Utility method for calculating standard deviation
                // Credit: https://stackoverflow.com/a/6252351
                double StandardDeviation(IEnumerable <double> values)
                {
                    double avg = values.Average();

                    return(Math.Sqrt(values.Average(v => Math.Pow(v - avg, 2))));
                }

                // Find the absolute difference between two any
                // ball scales.
                IEnumerable <double> ball1ScaleDifferences = Enumerable.Zip(ball1Scales,
                                                                            ball1Scales.Skip(1),
                                                                            (x1, x2) => Math.Abs(x2 - x1));
                IEnumerable <double> ball2ScaleDifferences = Enumerable.Zip(ball2Scales,
                                                                            ball2Scales.Skip(1),
                                                                            (x1, x2) => Math.Abs(x2 - x1));
                IEnumerable <double> ball3ScaleDifferences = Enumerable.Zip(ball3Scales,
                                                                            ball3Scales.Skip(1),
                                                                            (x1, x2) => Math.Abs(x2 - x1));

                // If the data is linear, then
                // (ballScale(i+1) - ballScale(i)) = (ballScale(j+1) - ballScale(j))
                // for any frame i and j. Thus, we can take the standard deviation
                // of the ball scale differences. If it is close to 0, then
                // the ball scale differences are all almost the same, thus indicating
                // a linear relationship.
                double ball1StandardDeviation = StandardDeviation(ball1ScaleDifferences);
                double ball2StandardDeviation = StandardDeviation(ball2ScaleDifferences);
                double ball3StandardDeviation = StandardDeviation(ball3ScaleDifferences);

                // Check if the standard deviation is equal to 0 with a possible error
                // of ± 0.1.
                Assert.AreEqual(0, ball1StandardDeviation, 0.1);
                Assert.AreEqual(0, ball2StandardDeviation, 0.1);
                Assert.AreEqual(0, ball3StandardDeviation, 0.1);
            }
コード例 #8
0
ファイル: ButtonUtils.cs プロジェクト: malahx/QuickMods
 public static Button FindButtons(string name)
 {
     return((Button)Object.FindObjectsOfType(typeof(Button))
            .FirstOrDefault(c => c.name == name));
 }
コード例 #9
0
 public static T[] FindObjectsOfType <T>() where T : Object
 {
     return(Resources.ConvertObjects <T>(Object.FindObjectsOfType(typeof(T))));
 }
コード例 #10
0
    public static void SaveGame(string fileName)
    {
        Debug.Log("hi");
        var result             = new JsonData();
        var allSaveableObjects = Object
                                 .FindObjectsOfType <MonoBehaviour>()
                                 .OfType <ISaveable>();

        if (allSaveableObjects.Count() > 0)
        {
            var savedObjects = new JsonData();
            foreach (var saveableObject in allSaveableObjects)
            {
                var data = saveableObject.SavedData;
                // Using LitJSON, checks if data is a JSON dictionary.
                if (data.IsObject)
                {
                    // https://litjson.net/api/LitJson/JsonData/
                    data[SAVEID_KEY] = saveableObject.SaveID;
                    savedObjects.Add(data);
                }
                else
                {
                    // Casts to MonoBehaviour;
                    var behaviour = saveableObject as MonoBehaviour;
                    if (!(behaviour is null))
                    {
                        Debug.LogWarningFormat(
                            behaviour,
                            "{0}'s save data is not a dictionary. The " +
                            "object was not saved.",
                            behaviour.name
                            );
                    }
                }
            }

            result[OBJECTS_KEY] = savedObjects;
        }
        else
        {
            Debug.LogWarningFormat("The scene did not include any saveable objects.");
        }

        // Gets Scene Data
        var openScenes = new JsonData();
        var sceneCount = SceneManager.sceneCount; // Currently loaded scenes.

        for (var i = 0; i < sceneCount; i++)
        {
            var scene = SceneManager.GetSceneAt(i);
            openScenes.Add(scene.name);
        }

        result[SCENES_KEY]       = openScenes;
        result[ACTIVE_SCENE_KEY] = SceneManager.GetActiveScene().name;

        //Finds where to put the file
        var outputPath = Path.Combine(Application.persistentDataPath, fileName);
        var writer     = new JsonWriter();

        writer.PrettyPrint = true;
        result.ToJson(writer);
        File.WriteAllText(outputPath, writer.ToString());
        Debug.LogFormat("Wrote saved game to {0}", outputPath);
        // Run GC now.
        result = null;
        System.GC.Collect();
    }
コード例 #11
0
ファイル: SceneBuilder.cs プロジェクト: yiqideren/Babylon.js
        public void ConvertFromUnity()
        {
            ExporterWindow.ReportProgress(0, "Starting Babylon.js exportation process...");

            gameObjects = Object.FindObjectsOfType(typeof(GameObject)) as GameObject[];

            if (gameObjects.Length == 0)
            {
                ExporterWindow.ShowMessage("No gameobject! - Please add at least a gameobject to export");
                return;
            }

            var itemsCount = gameObjects.Length;

            var index = 0;

            foreach (var gameObject in gameObjects)
            {
                var progress = ((float)index / itemsCount);
                index++;
                // Static meshes
                var meshFilter = gameObject.GetComponent <MeshFilter>();
                if (meshFilter != null)
                {
                    ConvertUnityMeshToBabylon(meshFilter.sharedMesh, meshFilter.transform, gameObject, progress);
                    continue;
                }

                // Skinned meshes
                var skinnedMesh = gameObject.GetComponent <SkinnedMeshRenderer>();
                if (skinnedMesh != null)
                {
                    ConvertUnityMeshToBabylon(skinnedMesh.sharedMesh, skinnedMesh.transform, gameObject, progress);
                    continue;
                }

                // Light
                var light = gameObject.GetComponent <Light>();
                if (light != null)
                {
                    ConvertUnityLightToBabylon(light, progress);
                    continue;
                }

                // Camera
                var camera = gameObject.GetComponent <Camera>();
                if (camera != null)
                {
                    ConvertUnityCameraToBabylon(camera, progress);
                    ConvertUnitySkyboxToBabylon(camera, progress);
                    continue;
                }

                // Empty
                ConvertUnityEmptyObjectToBabylon(gameObject);
            }

            // Materials
            foreach (var mat in materialsDictionary)
            {
                babylonScene.MaterialsList.Add(mat.Value);
            }

            foreach (var multiMat in multiMatDictionary)
            {
                babylonScene.MultiMaterialsList.Add(multiMat.Value);
            }

            // Collisions
            if (exportationOptions.ExportCollisions)
            {
                babylonScene.gravity = exportationOptions.Gravity.ToFloat();
            }
        }
コード例 #12
0
    /// <summary>
    /// Finds DataSetTrackableBehaviours for this dataset and associates them with the Trackables in the DataSet.
    /// VirtualButtonBehaviours created in the scene are associated with the VirtualButtons in the DataSet or created there.
    ///
    /// If there is a Trackable in the DataSet where no TrackableBehaviour exists yet, this Behaviour is created, together with its VirtualButtons.
    /// </summary>
    public void AssociateTrackableBehavioursForDataSet(DataSet dataSet)
    {
        // Step: Add all TrackableBehaviours that belong to this data set and
        // are already instantiated in the scene to the dictionary.
        DataSetTrackableBehaviour[] trackableBehaviours = (DataSetTrackableBehaviour[])
                                                          Object.FindObjectsOfType(typeof(DataSetTrackableBehaviour));

        // Initialize all Image Targets
        foreach (DataSetTrackableBehaviour trackableBehaviour in trackableBehaviours)
        {
            // trackable has been destroyed and shouldn't be associated
            if (mBehavioursMarkedForDeletion.Contains(trackableBehaviour))
            {
                continue;
            }

            IEditorDataSetTrackableBehaviour editorTrackableBehaviour = trackableBehaviour;
            if (editorTrackableBehaviour.TrackableName == null)
            {
                Debug.LogError("Found Trackable without name.");
                continue;
            }

            // check if the TrackableBehaviour references this DataSet
            if (editorTrackableBehaviour.DataSetPath.Equals(dataSet.Path))
            {
                bool matchFound = false;

                // find the trackable to be associated with this TrackableBehaviour:
                foreach (Trackable trackable in dataSet.GetTrackables())
                {
                    if (trackable.Name.Equals(editorTrackableBehaviour.TrackableName))
                    {
                        if (mTrackableBehaviours.ContainsKey(trackable.ID))
                        {
                            // don't replace existing behaviour if it has been created manually
                            if (!mAutomaticallyCreatedBehaviours.Contains(trackable.ID) && !mBehavioursMarkedForDeletion.Contains(mTrackableBehaviours[trackable.ID]))
                            {
                                matchFound = true;
                                continue;
                            }

                            // destroy automatically created behaviour - will be replaced by new one
                            Object.Destroy(mTrackableBehaviours[trackable.ID].gameObject);
                            mTrackableBehaviours.Remove(trackable.ID);
                            mAutomaticallyCreatedBehaviours.Remove(trackable.ID);
                        }

                        if (trackableBehaviour is ImageTargetBehaviour &&
                            trackable is ImageTarget)
                        {
                            IEditorImageTargetBehaviour editorImageTargetBehaviour = (ImageTargetBehaviour)trackableBehaviour;

                            matchFound = true;

                            editorImageTargetBehaviour.InitializeImageTarget((ImageTarget)trackable);
                            mTrackableBehaviours[trackable.ID] = trackableBehaviour;
                            Debug.Log("Found Trackable named " + trackableBehaviour.Trackable.Name +
                                      " with id " + trackableBehaviour.Trackable.ID);
                        }
                        else if (trackableBehaviour is MultiTargetBehaviour &&
                                 trackable is MultiTarget)
                        {
                            matchFound = true;

                            IEditorMultiTargetBehaviour editorMultiTargetBehaviour = (MultiTargetBehaviour)trackableBehaviour;
                            editorMultiTargetBehaviour.InitializeMultiTarget((MultiTarget)trackable);
                            mTrackableBehaviours[trackable.ID] = trackableBehaviour;
                            Debug.Log("Found Trackable named " + trackableBehaviour.Trackable.Name +
                                      " with id " + trackableBehaviour.Trackable.ID);
                        }
                        else if (trackableBehaviour is CylinderTargetBehaviour &&
                                 trackable is CylinderTarget)
                        {
                            matchFound = true;

                            IEditorCylinderTargetBehaviour editorCylinderTargetBehaviour = (CylinderTargetBehaviour)trackableBehaviour;
                            editorCylinderTargetBehaviour.InitializeCylinderTarget((CylinderTarget)trackable);
                            mTrackableBehaviours[trackable.ID] = trackableBehaviour;
                            Debug.Log("Found Trackable named " + trackableBehaviour.Trackable.Name +
                                      " with id " + trackableBehaviour.Trackable.ID);
                        }
                    }
                }

                if (!matchFound)
                {
                    Debug.LogError("Could not associate DataSetTrackableBehaviour '" + editorTrackableBehaviour.TrackableName +
                                   "' - no matching Trackable found in DataSet!");
                }
            }
        }

        // Step 2: Add all VirtualButtonBehaviours that belong to this data set
        // and are already instantiated in the scene to the dictionary.
        VirtualButtonBehaviour[] vbBehaviours = (VirtualButtonBehaviour[])
                                                Object.FindObjectsOfType(typeof(VirtualButtonBehaviour));
        AssociateVirtualButtonBehaviours(vbBehaviours, dataSet);

        // Step 3: Create TrackableBehaviours that are not existing in the scene.
        CreateMissingDataSetTrackableBehaviours(dataSet);
    }
コード例 #13
0
        IEnumerator CollectGameObjects()
        {
            cameraMain = Camera.main;
            yield return(new WaitForSeconds(0.15f));

            Debug.Out("cameraMain");

            dnaEvidences = Object.FindObjectsOfType <DNAEvidence>().ToList <DNAEvidence>() ?? null;
            yield return(new WaitForSeconds(0.15f));

            Debug.Out("dnaEvidences");

            doors = Object.FindObjectsOfType <Door>().ToList <Door>() ?? null;
            yield return(new WaitForSeconds(0.15f));

            Debug.Out("doors");

            fuseBox = Object.FindObjectOfType <FuseBox>() ?? null;
            yield return(new WaitForSeconds(0.15f));

            Debug.Out("fuseBox");

            gameController = Object.FindObjectOfType <GameController>() ?? null;
            yield return(new WaitForSeconds(0.15f));

            Debug.Out("gameController");

            ghostAI = Object.FindObjectOfType <GhostAI>() ?? null;
            yield return(new WaitForSeconds(0.15f));

            Debug.Out("ghostAI");

            ghostAIs = Object.FindObjectsOfType <GhostAI>().ToList <GhostAI>() ?? null;
            yield return(new WaitForSeconds(0.15f));

            Debug.Out("ghostAIs");

            ghostActivity = Object.FindObjectOfType <GhostActivity>() ?? null;
            yield return(new WaitForSeconds(0.15f));

            Debug.Out("ghostActivity");

            ghostInfo = Object.FindObjectOfType <GhostInfo>() ?? null;
            yield return(new WaitForSeconds(0.15f));

            Debug.Out("ghostInfo");

            levelController = Object.FindObjectOfType <LevelController>() ?? null;
            yield return(new WaitForSeconds(0.15f));

            Debug.Out("levelController");

            lightSwitch = Object.FindObjectOfType <LightSwitch>() ?? null;
            yield return(new WaitForSeconds(0.15f));

            Debug.Out("lightSwitch");

            lightSwitches = Object.FindObjectsOfType <LightSwitch>().ToList <LightSwitch>() ?? null;
            yield return(new WaitForSeconds(0.15f));

            Debug.Out("lightSwitches");

            soundController = Object.FindObjectOfType <SoundController>() ?? null;
            yield return(new WaitForSeconds(0.15f));

            Debug.Out("soundController");

            ouijaBoards = Object.FindObjectsOfType <OuijaBoard>().ToList <OuijaBoard>() ?? null;
            yield return(new WaitForSeconds(0.15f));

            Debug.Out("ouijaBoards");

            windows = Object.FindObjectsOfType <Window>().ToList <Window>() ?? null;
            yield return(new WaitForSeconds(0.15f));

            Debug.Out("ouijaBoards");

            if (Object.FindObjectOfType <Player>() != null)
            {
                player = Object.FindObjectOfType <Player>() ?? null;
                yield return(new WaitForSeconds(0.15f));

                Debug.Out("player");

                players = Object.FindObjectsOfType <Player>().ToList <Player>() ?? null;
                yield return(new WaitForSeconds(0.15f));

                Debug.Out("players");

                playerStatsManager = Object.FindObjectOfType <PlayerStatsManager>() ?? null;
                yield return(new WaitForSeconds(0.15f));

                Debug.Out("playerStatsManager");

                myPlayer = GetLocalPlayer() ?? player;
                Debug.Out("myPlayer");
                yield return(new WaitForSeconds(0.15f));

                playerAnim = myPlayer.field_Public_Animator_0 ?? null;
                yield return(new WaitForSeconds(0.15f));

                Debug.Out("playerAnim");

                if (playerAnim != null)
                {
                    boneTransform = playerAnim.GetBoneTransform(HumanBodyBones.Head) ?? null;
                    yield return(new WaitForSeconds(0.15f));

                    Debug.Out("boneTransform");
                }
            }

            if (levelController != null)
            {
                photonView = ghostAI.field_Public_PhotonView_0 ?? null;
                yield return(new WaitForSeconds(0.15f));

                Debug.Out("photonView");

                emf = Object.FindObjectsOfType <EMF>().ToList <EMF>() ?? null;
                yield return(new WaitForSeconds(0.15f));

                Debug.Out("emf");

                //emfData = Object.FindObjectOfType<EMFData>() ?? null;
                //yield return new WaitForSeconds(0.15f);
                //Debug.Out("emfData");
            }

            serverManager = Object.FindObjectOfType <ServerManager>() ?? null;
            yield return(new WaitForSeconds(0.15f));

            Debug.Out("serverManager");

            Debug.Out("-----------------------------");
            yield return(null);
        }
コード例 #14
0
ファイル: Coroutine.cs プロジェクト: Kretera/Kretera
        public static IEnumerator AltruistRevive(DeadBody target, Altruist role)
        {
            var parentId = target.ParentId;
            var position = target.TruePosition;

            var revived = new List <PlayerControl>();


            Utils.MurderPlayer(role.Player, role.Player);

            if (CustomGameOptions.AltruistTargetBody)
            {
                if (target != null)
                {
                    Object.Destroy(target.gameObject);
                }
            }

            var startTime = DateTime.UtcNow;

            while (true)
            {
                var now     = DateTime.UtcNow;
                var seconds = (now - startTime).TotalSeconds;
                if (seconds < CustomGameOptions.ReviveDuration)
                {
                    yield return(null);
                }
                else
                {
                    break;
                }

                if (MeetingHud.Instance)
                {
                    yield break;
                }
            }

            var altruistBody = Object.FindObjectsOfType <DeadBody>().FirstOrDefault(b => b.ParentId == role.Player.PlayerId);

            if (altruistBody != null)
            {
                Object.Destroy(altruistBody.gameObject);
            }

            var player = Utils.PlayerById(parentId);


            player.Revive();
            MedicMod.Murder.KilledPlayers.Remove(
                MedicMod.Murder.KilledPlayers.FirstOrDefault(x => x.PlayerId == player.PlayerId));
            revived.Add(player);
            player.NetTransform.SnapTo(position);

            if (target != null)
            {
                Object.Destroy(target.gameObject);
            }

            if (player.isLover())
            {
                var lover = Roles.Role.GetRole <Lover>(player).OtherLover.Player;

                lover.Revive();
                MedicMod.Murder.KilledPlayers.Remove(
                    MedicMod.Murder.KilledPlayers.FirstOrDefault(x => x.PlayerId == lover.PlayerId));
                revived.Add(lover);

                var loverBody = Object.FindObjectsOfType <DeadBody>().FirstOrDefault(b => b.ParentId == lover.PlayerId);

                if (loverBody != null)
                {
                    lover.NetTransform.SnapTo(loverBody.TruePosition);
                    Object.Destroy(loverBody.gameObject);
                }
            }

            if (revived.Any(x => x.AmOwner))
            {
                try
                {
                    Minigame.Instance.Close();
                    Minigame.Instance.Close();
                }
                catch
                {
                }
            }


            if (PlayerControl.LocalPlayer.Data.IsImpostor)
            {
                var gameObj = new GameObject();
                Arrow = gameObj.AddComponent <ArrowBehaviour>();
                gameObj.transform.parent = PlayerControl.LocalPlayer.gameObject.transform;
                var renderer = gameObj.AddComponent <SpriteRenderer>();
                renderer.sprite = Sprite;
                Arrow.image     = renderer;
                gameObj.layer   = 5;
                Target          = player;
                yield return(Utils.FlashCoroutine(role.Color, 1f, 0.5f));
            }
        }
コード例 #15
0
        /// <summary>
        /// Loads ALL the style declarations available in the scene<br/>
        /// Note: this doesn't filter any declaration based on media query rules<br/>
        /// This should be done once per scene (loaded level)<br/>
        /// The outside logic should set the Settings.Instance.StyleCacheDirty parameter
        /// </summary>
        public void Load()
        {
            bool resetCache = Gui.StyleCacheDirty;

            Gui.StyleCacheDirty = false; // reset flag

            /**
             * If another level loaded, we need to reset the collection,
             * even if the supplied resetCache parameter is false
             * */
            if (Application.loadedLevel != _loadedLevel)
            {
                _loadedLevel = Application.loadedLevel;
                resetCache   = true;
            }

            if (resetCache)
            {
                Reset();
            }

            if (_loaded)
            {
                return;
            }

#if DEBUG
            if (DebugMode)
            {
                Debug.Log(string.Format(@"### Deserializing stylesheets ###"));
            }
#endif

            _modules.Clear();

            Object[] stylesheets = Object.FindObjectsOfType(typeof(eDrivenStyleSheet));

            foreach (Object o in stylesheets)
            {
                eDrivenStyleSheet eds = (eDrivenStyleSheet)o;

                if (!eds.enabled)
                {
                    continue;
                }

                foreach (Serialization.StyleDeclaration declaration in eds.StyleSheet.Declarations)
                {
                    _allDeclarations.Add(declaration);

                    if (string.IsNullOrEmpty(declaration.Module))
                    {
                        throw new Exception("Module ID cannot be empty");
                    }

                    if (!_modules.ContainsKey(declaration.Module))
                    {
                        _modules[declaration.Module] = new List <Serialization.StyleDeclaration>();
                    }
                    _modules[declaration.Module].Add(declaration);
                }
            }

            _loaded = true;
        }
コード例 #16
0
    // Token: 0x060000B6 RID: 182 RVA: 0x00009660 File Offset: 0x00007860
    private void LoadDressingModel(string modelDir, int select)
    {
        string modelPath   = this.modelCategory + "/" + modelDir + "/model";
        Object modelPrefab = Resources.Load(modelPath, typeof(GameObject));
        bool   flag        = modelPrefab == null;

        if (!flag)
        {
            bool flag2 = this.selModel != null;
            if (flag2)
            {
                Object.Destroy(this.selModel);
            }
            for (int i = 0; i < this.modelHat.Length; i++)
            {
                bool flag3 = i == select;
                if (flag3)
                {
                    this.selHat = this.modelHat[select];
                }
                else
                {
                    this.modelHat[i].SetActive(false);
                }
            }
            this.UserBodyBlender.ChangeBackGround(this.selected);
            this.selModel      = (GameObject)Object.Instantiate(modelPrefab, Vector3.zero, Quaternion.Euler(0f, 180f, 0f));
            this.selModel.name = "Model" + modelDir;
            ModelData data  = this.selModel.GetComponent <ModelData>();
            bool      flag4 = data == null;
            if (flag4)
            {
                throw new UnityException("没有找到模型数据");
            }
            this.CurInfo = GlobalSettings.GetRoleInfo(data.Name);
            bool flag5 = this.CurInfo == null;
            if (flag5)
            {
                throw new UnityException("没有找到角色数据,查找的角色是:" + data.Name);
            }
            this.editorModel.SetInfo(this.CurInfo);
            this.selHat.GetComponent <ModelHatController>().verticalOffset = this.CurInfo.HatHeight;
            bool flag6 = FacetrackingManager.Instance != null;
            if (flag6)
            {
                //FacetrackingManager.Instance.Shifting = this.CurInfo.Shifting;
                //FacetrackingManager.Instance.modelMeshScale = this.CurInfo.HeadScale;
            }
            AvatarController ac    = this.selModel.GetComponent <AvatarController>();
            bool             flag7 = ac == null;
            if (flag7)
            {
                ac                    = this.selModel.AddComponent <AvatarController>();
                ac.playerIndex        = this.playerIndex;
                ac.mirroredMovement   = true;
                ac.verticalMovement   = true;
                ac.applyMuscleLimits  = this.applyMuscleLimits;
                ac.verticalOffset     = this.verticalOffset;
                ac.forwardOffset      = this.forwardOffset;
                ac.smoothFactor       = 0f;
                ac.verticalOffset     = this.CurInfo.Vertacal;
                ac.forwardOffset      = this.CurInfo.Farward;
                ac.fingerOrientations = true;
                ac.applyMuscleLimits  = true;
            }
            ac.posRelativeToCamera = this.modelRelativeToCamera;
            ac.posRelOverlayColor  = (this.foregroundCamera != null);
            KinectManager km    = KinectManager.Instance;
            bool          flag8 = km && km.IsInitialized();
            if (flag8)
            {
                long userId = km.GetUserIdByIndex(this.playerIndex);
                bool flag9  = userId != 0L;
                if (flag9)
                {
                    ac.SuccessfulCalibration(userId, false);
                }
                MonoBehaviour[] monoScripts = Object.FindObjectsOfType(typeof(MonoBehaviour)) as MonoBehaviour[];
                km.avatarControllers.Clear();
                foreach (MonoBehaviour monoScript in monoScripts)
                {
                    bool flag10 = monoScript is AvatarController && monoScript.enabled;
                    if (flag10)
                    {
                        AvatarController avatar = (AvatarController)monoScript;
                        km.avatarControllers.Add(avatar);
                    }
                }
            }
            AvatarScaler scaler = this.selModel.GetComponent <AvatarScaler>();
            bool         flag11 = scaler == null;
            if (flag11)
            {
                scaler                   = this.selModel.AddComponent <AvatarScaler>();
                scaler.playerIndex       = this.playerIndex;
                scaler.mirroredAvatar    = true;
                scaler.continuousScaling = this.continuousScaling;
                scaler.bodyScaleFactor   = this.bodyScaleFactor;
                scaler.bodyWidthFactor   = this.bodyWidthFactor;
                scaler.armScaleFactor    = this.armScaleFactor;
                scaler.legScaleFactor    = this.legScaleFactor;
                scaler.bodyScaleFactor   = this.CurInfo.BodyScale;
                scaler.legScaleFactor    = this.CurInfo.LegScale;
                scaler.armScaleFactor    = this.CurInfo.ArmScale;
            }
            scaler.foregroundCamera = this.foregroundCamera;
        }
    }
コード例 #17
0
 // Search for objects instead of using chainloader API to find dynamically loaded plugins
 public static BaseUnityPlugin[] FindPlugins() => Object.FindObjectsOfType <BaseUnityPlugin>();
コード例 #18
0
ファイル: RecursiveDrawer.cs プロジェクト: kimsama/VFW-1
        protected virtual void SelectionButton()
        {
            var tabs = new List <Tab>();

            Action <Func <Type[]>, Action <Type>, string> newTypeTab = (getValues, create, title) =>
                                                                       tabs.Add(new Tab <Type>(
                                                                                    @getValues: getValues,
                                                                                    @getCurrent: () => { var x = memberValue; return(x == null ? null : x.GetType()); },
                                                                                    @setTarget: newType => { if (newType == null)
                                                                                                             {
                                                                                                                 memberValue = memberType.GetDefaultValueEmptyIfString();
                                                                                                             }
                                                                                                             else
                                                                                                             {
                                                                                                                 create(newType);
                                                                                                             } },
                                                                                    @getValueName: type => type.Name,
                                                                                    @title: title
                                                                                    ));

            if (memberType.IsInterface)
            {
                Action <Func <UnityObject[]>, string> newUnityTab = (getValues, title) =>
                                                                    tabs.Add(new Tab <UnityObject>(
                                                                                 @getValues: getValues,
                                                                                 @getCurrent: member.As <UnityObject>,
                                                                                 @setTarget: member.Set,
                                                                                 @getValueName: obj => obj.name + " (" + obj.GetType().Name + ")",
                                                                                 @title: title
                                                                                 ));

                newUnityTab(() => UnityObject.FindObjectsOfType <UnityObject>()
                            .OfType(memberType)
                            .ToArray(), "Scene");

                newUnityTab(() => PrefabHelper.GetComponentPrefabs(memberType)
                            .ToArray(), "Prefabs");

                newTypeTab(() => GetAllUserTypesOf(memberType)
                           .Where(t => t.IsA <MonoBehaviour>())
                           .Where(t => !t.IsAbstract)
                           .ToArray(), TryCreateInstanceInGO, "MonoBehaviours");
            }

            newTypeTab(() => GetAllUserTypesOf(memberType)
                       .Disinclude(memberType.IsAbstract ? memberType : null)
                       .Where(t => !t.IsA <UnityObject>() && !t.IsAbstract)
                       .ToArray(), TryCreateInstance, "System types");

            var click = Event.current.button;

            if (gui.SelectionButton("Left click: select type. Right click: try instantiate"))
            {
                if (click == 0)
                {
                    SelectionWindow.Show("Select a `" + memberTypeName + "` object", tabs.ToArray());
                }
                else if (click == 1)
                {
                    try
                    {
                        memberValue = memberType.ActivatorInstance();
                    }
                    catch (Exception e)
                    {
                        Debug.Log("Error. Couldn't create instance: " + e.Message);
                    }
                }
            }
        }
コード例 #19
0
        protected override void Initialize()
        {
            _nullString = string.Format("null ({0})", memberTypeName);

            if (memberValue != null)
            {
                _polymorphicType = memberValue.GetType();
                _isToStringImpl  = _polymorphicType.IsMethodImplemented("ToString", Type.EmptyTypes);
            }
            else
            {
                _isToStringImpl = memberType.IsMethodImplemented("ToString", Type.EmptyTypes);
            }

            _getDraggedObject = objs =>
            {
                for (int i = 0; i < objs.Length; i++)
                {
                    var drag = objs[i];
                    if (drag == null)
                    {
                        continue;
                    }

                    var go = drag as GameObject;
                    if (go != null)
                    {
                        var c = go.GetComponent(memberType);
                        if (c != null)
                        {
                            return(c);
                        }
                    }

                    if (drag.GetType().IsA(memberType))
                    {
                        return(drag);
                    }
                }
                return(null);
            };

            _isDropAccepted = objs => _getDraggedObject(objs) != null;

            _newTypeTab = (getValues, create, title) =>
                          new Tab <Type>(
                @getValues: getValues,
                @getCurrent: () => { var x = memberValue; return(x == null ? null : x.GetType()); },
                @setTarget: newType => { if (newType == null)
                                         {
                                             memberValue = memberType.GetDefaultValueEmptyIfString();
                                         }
                                         else
                                         {
                                             create(newType);
                                         } },
                @getValueName: type => type.GetNiceName(),
                @title: title
                );

            _newUnityTab = (getValues, title) =>
                           new Tab <UnityObject>(
                @getValues: getValues,
                @getCurrent: member.As <UnityObject>,
                @setTarget: member.Set,
                @getValueName: obj => obj.name + " (" + obj.GetType().GetNiceName() + ")",
                @title: title
                );

            int idx = 0;

            if (memberType.IsInterface)
            {
                _tabs = new Tab[4];

                _tabs[idx++] = _newUnityTab(() => UnityObject.FindObjectsOfType <UnityObject>()
                                            .OfType(memberType)
                                            .ToArray(), "Scene");

                _tabs[idx++] = _newUnityTab(() => PrefabHelper.GetComponentPrefabs(memberType)
                                            .ToArray(), "Prefab");

                _tabs[idx++] = _newTypeTab(() => ReflectionHelper.GetAllUserTypesOf(memberType)
                                           .Where(t => t.IsA <MonoBehaviour>() && !t.IsAbstract)
                                           .ToArray(), TryCreateInstanceInGO, "New Behaviour");
            }
            else
            {
                _tabs = new Tab[1];
            }

            var systemTypes = ReflectionHelper.GetAllUserTypesOf(memberType)
                              .Where(t => !t.IsA <UnityObject>() && !t.IsAbstract)
                              .ToArray();

            if (memberType.IsGenericType && !systemTypes.Contains(memberType))
            {
                ArrayUtility.Add(ref systemTypes, memberType);
            }

            _tabs[idx] = _newTypeTab(() => systemTypes, TryCreateInstance, "System Type");
        }
コード例 #20
0
        protected virtual void OnGUISceneCheck(VRC_SceneDescriptor scene)
        {
            CheckUploadChanges(scene);
#if !VRC_SDK_VRCSDK3
            bool isSdk3Scene = false;
#elif UDON
            bool isSdk3Scene = scene as VRC.SDK3.Components.VRCSceneDescriptor != null;
#endif

            List <VRC_EventHandler> sdkBaseEventHandlers =
                new List <VRC_EventHandler>(Object.FindObjectsOfType <VRC_EventHandler>());
#if VRC_SDK_VRCSDK2
            if (isSdk3Scene == false)
            {
                for (int i = sdkBaseEventHandlers.Count - 1; i >= 0; --i)
                {
                    if (sdkBaseEventHandlers[i] as VRCSDK2.VRC_EventHandler)
                    {
                        sdkBaseEventHandlers.RemoveAt(i);
                    }
                }
            }
#endif
            if (sdkBaseEventHandlers.Count > 0)
            {
                _builder.OnGUIError(scene,
                                    "You have Event Handlers in your scene that are not allowed in this build configuration.",
                                    delegate
                {
                    List <Object> gos = sdkBaseEventHandlers.ConvertAll(item => (Object)item.gameObject);
                    Selection.objects = gos.ToArray();
                },
                                    delegate
                {
                    foreach (VRC_EventHandler eh in sdkBaseEventHandlers)
                    {
#if VRC_SDK_VRCSDK2
                        GameObject go = eh.gameObject;
                        if (isSdk3Scene == false)
                        {
                            if (VRC_SceneDescriptor.Instance as VRCSDK2.VRC_SceneDescriptor != null)
                            {
                                go.AddComponent <VRCSDK2.VRC_EventHandler>();
                            }
                        }
#endif
                        Object.DestroyImmediate(eh);
                    }
                });
            }

            Vector3 g = Physics.gravity;
            if (Math.Abs(g.x) > float.Epsilon || Math.Abs(g.z) > float.Epsilon)
            {
                _builder.OnGUIWarning(scene,
                                      "Gravity vector is not straight down. Though we support different gravity, player orientation is always 'upwards' so things don't always behave as you intend.",
                                      delegate { SettingsService.OpenProjectSettings("Project/Physics"); }, null);
            }
            if (g.y > 0)
            {
                _builder.OnGUIWarning(scene,
                                      "Gravity vector is not straight down, inverted or zero gravity will make walking extremely difficult.",
                                      delegate { SettingsService.OpenProjectSettings("Project/Physics"); }, null);
            }
            if (Math.Abs(g.y) < float.Epsilon)
            {
                _builder.OnGUIWarning(scene,
                                      "Zero gravity will make walking extremely difficult, though we support different gravity, player orientation is always 'upwards' so this may not have the effect you're looking for.",
                                      delegate { SettingsService.OpenProjectSettings("Project/Physics"); }, null);
            }

            if (CheckFogSettings())
            {
                _builder.OnGUIWarning(
                    scene,
                    "Fog shader stripping is set to Custom, this may lead to incorrect or unnecessary shader variants being included in the build. You should use Automatic unless you change the fog mode at runtime.",
                    delegate { SettingsService.OpenProjectSettings("Project/Graphics"); },
                    delegate
                {
                    EnvConfig.SetFogSettings(
                        new EnvConfig.FogSettings(EnvConfig.FogSettings.FogStrippingMode.Automatic));
                });
            }

            if (scene.autoSpatializeAudioSources)
            {
                _builder.OnGUIWarning(scene,
                                      "Your scene previously used the 'Auto Spatialize Audio Sources' feature. This has been deprecated, press 'Fix' to disable. Also, please add VRC_SpatialAudioSource to all your audio sources. Make sure Spatial Blend is set to 3D for the sources you want to spatialize.",
                                      null,
                                      delegate { scene.autoSpatializeAudioSources = false; }
                                      );
            }

            AudioSource[] audioSources = Object.FindObjectsOfType <AudioSource>();
            foreach (AudioSource a in audioSources)
            {
                if (a.GetComponent <ONSPAudioSource>() != null)
                {
                    _builder.OnGUIWarning(scene,
                                          "Found audio source(s) using ONSP, this is deprecated. Press 'fix' to convert to VRC_SpatialAudioSource.",
                                          delegate { Selection.activeObject = a.gameObject; },
                                          delegate
                    {
                        Selection.activeObject = a.gameObject;
                        AutoAddSpatialAudioComponents.ConvertONSPAudioSource(a);
                    }
                                          );
                    break;
                }
                else if (a.GetComponent <VRC_SpatialAudioSource>() == null)
                {
                    string msg =
                        "Found 3D audio source with no VRC Spatial Audio component, this is deprecated. Press 'fix' to add a VRC_SpatialAudioSource.";
                    if (IsAudioSource2D(a))
                    {
                        msg =
                            "Found 2D audio source with no VRC Spatial Audio component, this is deprecated. Press 'fix' to add a (disabled) VRC_SpatialAudioSource.";
                    }

                    _builder.OnGUIWarning(scene, msg,
                                          delegate { Selection.activeObject = a.gameObject; },
                                          delegate
                    {
                        Selection.activeObject = a.gameObject;
                        AutoAddSpatialAudioComponents.AddVRCSpatialToBareAudioSource(a);
                    }
                                          );
                    break;
                }
            }

            if (VRCSdkControlPanel.HasSubstances())
            {
                _builder.OnGUIWarning(scene,
                                      "One or more scene objects have Substance materials. This is not supported and may break in game. Please bake your Substances to regular materials.",
                                      () => { Selection.objects = VRCSdkControlPanel.GetSubstanceObjects(); },
                                      null);
            }

#if VRC_SDK_VRCSDK2
            foreach (VRC_DataStorage ds in Object.FindObjectsOfType <VRC_DataStorage>())
            {
                VRCSDK2.VRC_ObjectSync os = ds.GetComponent <VRCSDK2.VRC_ObjectSync>();
                if (os != null && os.SynchronizePhysics)
                {
                    _builder.OnGUIWarning(scene, ds.name + " has a VRC_DataStorage and VRC_ObjectSync, with SynchronizePhysics enabled.",
                                          delegate { Selection.activeObject = os.gameObject; }, null);
                }
            }
#else
            foreach (VRC.SDK3.Components.VRCObjectSync os in Object.FindObjectsOfType <VRC.SDK3.Components.VRCObjectSync>())
            {
                if (os.GetComponents <VRC.Udon.UdonBehaviour>().Any((ub) => ub.Reliable))
                {
                    _builder.OnGUIError(scene, "Object Sync cannot share an object with a manually synchronized Udon Behaviour",
                                        delegate { Selection.activeObject = os.gameObject; }, null);
                }
                if (os.GetComponent <VRC.SDK3.Components.VRCObjectPool>() != null)
                {
                    _builder.OnGUIError(scene, "Object Sync cannot share an object with an object pool",
                                        delegate { Selection.activeObject = os.gameObject; }, null);
                }
            }
#endif

            string vrcFilePath = UnityWebRequest.UnEscapeURL(EditorPrefs.GetString("lastVRCPath"));
            if (!string.IsNullOrEmpty(vrcFilePath) &&
                ValidationHelpers.CheckIfAssetBundleFileTooLarge(ContentType.World, vrcFilePath, out int fileSize))
            {
                _builder.OnGUIWarning(scene,
                                      ValidationHelpers.GetAssetBundleOverSizeLimitMessageSDKWarning(ContentType.World, fileSize), null,
                                      null);
            }

            foreach (GameObject go in Object.FindObjectsOfType <GameObject>())
            {
                if (go.transform.parent == null)
                {
                    // check root game objects
#if UNITY_ANDROID
                    IEnumerable <Shader> illegalShaders = VRC.SDKBase.Validation.WorldValidation.FindIllegalShaders(go);
                    foreach (Shader s in illegalShaders)
                    {
                        _builder.OnGUIWarning(scene, "World uses unsupported shader '" + s.name + "'. This could cause low performance or future compatibility issues.", null, null);
                    }
#endif
                }
                else
                {
                    // Check sibling game objects
                    for (int idx = 0; idx < go.transform.parent.childCount; ++idx)
                    {
                        Transform t = go.transform.parent.GetChild(idx);
                        if (t == go.transform)
                        {
                            continue;
                        }

#if VRC_SDK_VRCSDK2
                        bool allowedType = (t.GetComponent <VRCSDK2.VRC_ObjectSync>() ||
                                            t.GetComponent <VRCSDK2.VRC_SyncAnimation>() ||
                                            t.GetComponent <VRCSDK2.VRC_SyncVideoPlayer>() ||
                                            t.GetComponent <VRCSDK2.VRC_SyncVideoStream>());
                        if (t.name != go.transform.name || allowedType)
                        {
                            continue;
                        }
#else
                        if (t.name != go.transform.name)
                        {
                            continue;
                        }
#endif

                        string    path = t.name;
                        Transform p    = t.parent;
                        while (p != null)
                        {
                            path = p.name + "/" + path;
                            p    = p.parent;
                        }

                        _builder.OnGUIWarning(scene,
                                              "Sibling objects share the same path, which may break network events: " + path,
                                              delegate
                        {
                            List <Object> gos = new List <Object>();
                            for (int c = 0; c < go.transform.parent.childCount; ++c)
                            {
                                if (go.transform.parent.GetChild(c).name == go.name)
                                {
                                    gos.Add(go.transform.parent.GetChild(c).gameObject);
                                }
                            }
                            Selection.objects = gos.ToArray();
                        },
                                              delegate
                        {
                            List <Object> gos = new List <Object>();
                            for (int c = 0; c < go.transform.parent.childCount; ++c)
                            {
                                if (go.transform.parent.GetChild(c).name == go.name)
                                {
                                    gos.Add(go.transform.parent.GetChild(c).gameObject);
                                }
                            }
                            Selection.objects = gos.ToArray();
                            for (int i = 0; i < gos.Count; ++i)
                            {
                                gos[i].name = gos[i].name + "-" + i.ToString("00");
                            }
                        });
                        break;
                    }
                }
            }

            // detect dynamic materials and prefabs with identical names (since these could break triggers)
            VRC_Trigger[]     triggers  = Tools.FindSceneObjectsOfTypeAll <VRC_Trigger>();
            List <GameObject> prefabs   = new List <GameObject>();
            List <Material>   materials = new List <Material>();

#if VRC_SDK_VRCSDK2
            AssetExporter.FindDynamicContent(ref prefabs, ref materials);
#elif VRC_SDK_VRCSDK3
            AssetExporter.FindDynamicContent(ref prefabs, ref materials);
#endif

            foreach (VRC_Trigger t in triggers)
            {
                foreach (VRC_Trigger.TriggerEvent triggerEvent in t.Triggers)
                {
                    foreach (VRC_EventHandler.VrcEvent e in triggerEvent.Events.Where(evt =>
                                                                                      evt.EventType == VRC_EventHandler.VrcEventType.SpawnObject))
                    {
                        GameObject go =
                            AssetDatabase.LoadAssetAtPath(e.ParameterString, typeof(GameObject)) as GameObject;
                        if (go == null)
                        {
                            continue;
                        }
                        foreach (GameObject existing in prefabs)
                        {
                            if (go == existing || go.name != existing.name)
                            {
                                continue;
                            }
                            _builder.OnGUIWarning(scene,
                                                  "Trigger prefab '" + AssetDatabase.GetAssetPath(go).Replace(".prefab", "") +
                                                  "' has same name as a prefab in another folder. This may break the trigger.",
                                                  delegate { Selection.objects = new Object[] { go }; },
                                                  delegate
                            {
                                AssetDatabase.RenameAsset(AssetDatabase.GetAssetPath(go),
                                                          go.name + "-" + go.GetInstanceID());
                                AssetDatabase.Refresh();
                                e.ParameterString = AssetDatabase.GetAssetPath(go);
                            });
                        }
                    }

                    foreach (VRC_EventHandler.VrcEvent e in triggerEvent.Events.Where(evt =>
                                                                                      evt.EventType == VRC_EventHandler.VrcEventType.SetMaterial))
                    {
                        Material mat = AssetDatabase.LoadAssetAtPath <Material>(e.ParameterString);
                        if (mat == null || mat.name.Contains("(Instance)"))
                        {
                            continue;
                        }
                        foreach (Material existing in materials)
                        {
                            if (mat == existing || mat.name != existing.name)
                            {
                                continue;
                            }
                            _builder.OnGUIWarning(scene,
                                                  "Trigger material '" + AssetDatabase.GetAssetPath(mat).Replace(".mat", "") +
                                                  "' has same name as a material in another folder. This may break the trigger.",
                                                  delegate { Selection.objects = new Object[] { mat }; },
                                                  delegate
                            {
                                AssetDatabase.RenameAsset(AssetDatabase.GetAssetPath(mat),
                                                          mat.name + "-" + mat.GetInstanceID());
                                AssetDatabase.Refresh();
                                e.ParameterString = AssetDatabase.GetAssetPath(mat);
                            });
                        }
                    }
                }
            }
        }
コード例 #21
0
    public static bool LoadGame(string fileName)
    {
        var dataPath = Path.Combine(Application.persistentDataPath, fileName);

        if (!File.Exists(dataPath))
        {
            Debug.LogErrorFormat("No file exists at {0}", dataPath);
            return(false);
        }

        var text = File.ReadAllText(dataPath);
        var data = JsonMapper.ToObject(text);

        if (data == null || data.IsObject == false)
        {
            Debug.LogErrorFormat("Data at {0} is not a JSON Object", dataPath);
            return(false);
        }

        var scenes     = data[SCENES_KEY];
        var sceneCount = scenes.Count;

        if (sceneCount == 0)
        {
            Debug.LogWarningFormat("Data at {0} doesn't specify any scenes to load.", dataPath);
            return(false);
        }

        for (var i = 0; i < sceneCount; i++)
        {
            var scene = (string)scenes[i];
            if (i == 0) // The First scene is the active scene.
            {
                SceneManager.LoadScene(scene, LoadSceneMode.Single);
            }
            else
            {
                SceneManager.LoadScene(scene, LoadSceneMode.Additive);
            }
        }

        if (data.ContainsKey(ACTIVE_SCENE_KEY))
        {
            var activeSceneName = (string)data[ACTIVE_SCENE_KEY];
            var activeScene     = SceneManager.GetSceneByName(activeSceneName);
            if (activeScene.IsValid() == false)
            {
                Debug.LogErrorFormat(
                    "Data at {0} specifies an active scene that " +
                    "doesn't exist. Stopping loading here.",
                    dataPath
                    );
                return(false);
            }

            SceneManager.SetActiveScene(activeScene);
        }
        else
        {
            Debug.LogWarningFormat(
                "Data at {0} does not specify an active scene. " +
                "(But the first scene in the list will be treated as active)",
                dataPath
                );
        }

        if (data.ContainsKey(OBJECTS_KEY))
        {
            var objects = data[OBJECTS_KEY];
            // We need to wait until the scene loads, or else objects will revert to their
            // original states- ignoring the changes we make here.
            LoadObjectsAfterSceneLoad = (scene, LoadSceneMode) =>
            {
                var allLoadableObjects = Object
                                         .FindObjectsOfType <MonoBehaviour>()
                                         .OfType <ISaveable>()
                                         .ToDictionary(o => o.SaveID, o => o);
                var objectsCount = objects.Count;
                for (var i = 0; i < objectsCount; i++)
                {
                    var objectData = objects[i];
                    var saveID     = (string)objectData[SAVEID_KEY];
                    if (allLoadableObjects.ContainsKey(saveID))
                    {
                        var loadableObject = allLoadableObjects[saveID];
                        loadableObject.LoadFromData(objectData); // TODO How does objectData look like- in order to parse it?
                    }
                }

                // Unsubscribes from SceneLoaded notifications.
                SceneManager.sceneLoaded -= LoadObjectsAfterSceneLoad;
                LoadObjectsAfterSceneLoad = null;
                System.GC.Collect();
            };

            // Registers the object-loading code to run after scene loads.
            SceneManager.sceneLoaded += LoadObjectsAfterSceneLoad;
        }

        return(true);
    }
コード例 #22
0
        /// <summary>
        /// Returns TRUE if its actually previewing animations
        /// </summary>
        public static bool PreviewGUI(DOTweenAnimation src)
        {
            if (EditorApplication.isPlaying)
            {
                return(false);
            }

            Styles.Init();

            bool isPreviewing     = _AnimationToTween.Count > 0;
            bool isPreviewingThis = isPreviewing && _AnimationToTween.ContainsKey(src);

            // Preview in editor
            GUI.backgroundColor = isPreviewing
                ? new DeSkinColor(new Color(0.49f, 0.8f, 0.86f), new Color(0.15f, 0.26f, 0.35f))
                : new DeSkinColor(Color.white, new Color(0.13f, 0.13f, 0.13f));
            GUILayout.BeginVertical(Styles.previewBox);
            DeGUI.ResetGUIColors();
            GUILayout.BeginHorizontal();
            GUILayout.Label("Preview Mode - Experimental", Styles.previewLabel);
            _previewOnlyIfSetToAutoPlay = DeGUILayout.ToggleButton(
                _previewOnlyIfSetToAutoPlay,
                new GUIContent("AutoPlay only", "If toggled only previews animations that have AutoPlay turned ON"),
                Styles.btOption
                );
            GUILayout.EndHorizontal();
            GUILayout.Space(1);
            // Preview - Play
            GUILayout.BeginHorizontal();
            EditorGUI.BeginDisabledGroup(
                isPreviewingThis || src.animationType == DOTweenAnimationType.None ||
                !src.isActive || _previewOnlyIfSetToAutoPlay && !src.autoPlay
                );
            if (GUILayout.Button("► Play", Styles.btPreview))
            {
                if (!isPreviewing)
                {
                    StartupGlobalPreview();
                }
                AddAnimationToGlobalPreview(src);
            }
            EditorGUI.EndDisabledGroup();
            EditorGUI.BeginDisabledGroup(isPreviewing);
            if (GUILayout.Button("► Play All <i>on GameObject</i>", Styles.btPreview))
            {
                if (!isPreviewing)
                {
                    StartupGlobalPreview();
                }
                DOTweenAnimation[] anims = src.gameObject.GetComponents <DOTweenAnimation>();
                foreach (DOTweenAnimation anim in anims)
                {
                    AddAnimationToGlobalPreview(anim);
                }
            }
            if (GUILayout.Button("► Play All <i>in Scene</i>", Styles.btPreview))
            {
                if (!isPreviewing)
                {
                    StartupGlobalPreview();
                }
                DOTweenAnimation[] anims = Object.FindObjectsOfType <DOTweenAnimation>();
                foreach (DOTweenAnimation anim in anims)
                {
                    AddAnimationToGlobalPreview(anim);
                }
            }
            EditorGUI.EndDisabledGroup();
            GUILayout.EndHorizontal();
            // Preview - Stop
            GUILayout.BeginHorizontal();
            EditorGUI.BeginDisabledGroup(!isPreviewingThis);
            if (GUILayout.Button("■ Stop", Styles.btPreview))
            {
                if (_AnimationToTween.ContainsKey(src))
                {
                    StopPreview(_AnimationToTween[src].tween);
                }
            }
            EditorGUI.EndDisabledGroup();
            EditorGUI.BeginDisabledGroup(!isPreviewing);
            if (GUILayout.Button("■ Stop All <i>on GameObject</i>", Styles.btPreview))
            {
                StopPreview(src.gameObject);
            }
            if (GUILayout.Button("■ Stop All <i>in Scene</i>", Styles.btPreview))
            {
                StopAllPreviews();
            }
            EditorGUI.EndDisabledGroup();
            GUILayout.EndHorizontal();
            if (isPreviewing)
            {
                int playingTweens   = 0;
                int completedTweens = 0;
                int pausedTweens    = 0;
                foreach (KeyValuePair <DOTweenAnimation, TweenInfo> kvp in _AnimationToTween)
                {
                    Tween t = kvp.Value.tween;
                    if (t.IsPlaying())
                    {
                        playingTweens++;
                    }
                    else if (t.IsComplete())
                    {
                        completedTweens++;
                    }
                    else
                    {
                        pausedTweens++;
                    }
                }
                GUILayout.Label("Playing Tweens: " + playingTweens, Styles.previewStatusLabel);
                GUILayout.Label("Completed Tweens: " + completedTweens, Styles.previewStatusLabel);
                //                GUILayout.Label("Paused Tweens: " + playingTweens);
            }
            GUILayout.EndVertical();

            return(isPreviewing);
        }
コード例 #23
0
ファイル: Preprocess.cs プロジェクト: MakiMakiSa/TestRepo
        private List <MeshObject> GetMeshList()
        {
            List <GameObject> objects = null;

            if (core.parameters.Targets != null)
            {
                objects = new List <GameObject>(core.parameters.Targets);
            }
            else
            {
                if (core.parameters.DontUseTag)
                {
                    var objs = Object.FindObjectsOfType(typeof(Explodable));
                    objects = new List <GameObject>(objs.Length);

                    foreach (var o in objs)
                    {
                        var ex = (Explodable)o;

                        if (ex)
                        {
                            objects.Add(ex.gameObject);
                        }
                    }
                }
                else
                {
                    objects = new List <GameObject>(GameObject.FindGameObjectsWithTag(ExploderObject.Tag));
                }
            }

            if (core.parameters.ExplodeSelf)
            {
                objects.Add(core.parameters.ExploderGameObject);
            }

            var list = new List <MeshObject>(objects.Count);

            int counter = 0;

            var ctr        = Vector3.zero;
            var ctrCounter = 0;

            foreach (var o in objects)
            {
                // in case of destroyed objects
                if (!o)
                {
                    continue;
                }

                // don't destroy the destroyer :)
                if (!core.parameters.ExplodeSelf && o == core.parameters.ExploderGameObject)
                {
                    continue;
                }

                // stop scanning for object is case of settings.ExplodeSelf
                if (o != core.parameters.ExploderGameObject && core.parameters.ExplodeSelf && core.parameters.DisableRadiusScan)
                {
                    continue;
                }

                if (core.parameters.Targets != null || IsInRadius(o))
                {
                    var meshData    = GetMeshData(o);
                    var meshDataLen = meshData.Count;

                    for (var i = 0; i < meshDataLen; i++)
                    {
                        var centroid = meshData[i].centroid;

                        // overwrite settings.Position in case of settings.Target
                        if (core.parameters.Targets != null)
                        {
                            core.parameters.Position = centroid;
                            ctr += centroid;
                            ctrCounter++;
                        }

                        var distance = (centroid - core.parameters.Position).magnitude;

                        //                    UnityEngine.Debug.Log("Distance: " + distance + " " + meshData[i].gameObject.name);

                        list.Add(new MeshObject
                        {
                            id        = counter++,
                            mesh      = new ExploderMesh(meshData[i].sharedMesh),
                            material  = meshData[i].sharedMaterial,
                            transform = new ExploderTransform(meshData[i].gameObject.transform),

                            parent     = meshData[i].gameObject.transform.parent,
                            position   = meshData[i].gameObject.transform.position,
                            rotation   = meshData[i].gameObject.transform.rotation,
                            localScale = meshData[i].gameObject.transform.localScale,
                            bakeObject = meshData[i].gameObject,

                            distanceRatio   = GetDistanceRatio(distance, core.parameters.Radius),
                            original        = meshData[i].parentObject,
                            skinnedOriginal = meshData[i].skinnedBakeOriginal,

                            option = o.GetComponent <ExploderOption>(),
                        });
                    }
                }
            }

            if (ctrCounter > 0)
            {
                ctr /= ctrCounter;
                core.parameters.Position = ctr;
            }

            if (list.Count == 0)
            {
                ExploderUtils.Log("No explodable objects found!");
                return(list);
            }

            if (core.parameters.UniformFragmentDistribution || core.parameters.Targets != null)
            {
                var fragmentPerObject = core.parameters.TargetFragments / list.Count;

                int cnt = core.parameters.TargetFragments;
                foreach (var meshObject in list)
                {
                    core.targetFragments[meshObject.id] = fragmentPerObject;
                    cnt -= fragmentPerObject;
                }

                while (cnt > 0)
                {
                    cnt--;

                    var randMeshObject = list[UnityEngine.Random.Range(0, list.Count - 1)];
                    core.targetFragments[randMeshObject.id] += 1;
                }
            }
            else
            {
                var sum          = 0.0f;
                var sumFragments = 0;

                foreach (var o in list)
                {
                    sum += o.distanceRatio;
                }

                foreach (var mesh in list)
                {
                    core.targetFragments[mesh.id] = (int)((mesh.distanceRatio / sum) * core.parameters.TargetFragments);
                    sumFragments += core.targetFragments[mesh.id];
                }

                if (sumFragments < core.parameters.TargetFragments)
                {
                    var diff = core.parameters.TargetFragments - sumFragments;

                    while (diff > 0)
                    {
                        foreach (var mesh in list)
                        {
                            core.targetFragments[mesh.id] += 1;
                            diff--;

                            if (diff == 0)
                            {
                                break;
                            }
                        }
                    }
                }
            }

            return(list);
        }
コード例 #24
0
        public IEnumerator CheckForAlarmClock()
        {
            AlarmClock alarmClock = null;

            yield return(null);

            _modSettings.ReadSettings();

            DebugLog("Attempting to Find Alarm Clock");
            while (SceneManager.Instance.CurrentState == SceneManager.State.Gameplay)
            {
                AlarmClock[] alarmClocks = (AlarmClock[])Object.FindObjectsOfType(typeof(AlarmClock));
                if (alarmClocks == null || alarmClocks.Length == 0)
                {
                    yield return(null);

                    continue;
                }

                foreach (var alarm in alarmClocks)
                {
                    DebugLog("Alarm Clock found - Hooking into it.");
                    alarm.MaxAlarmClockBuzzerTime = _modSettings.Settings.AlarmClockBuzzerTime;
                    DebugLog("Done setting up the Alarm Clocks");
                    alarmClock = alarm;
                    break;
                }
                break;
            }

            FieldInfo <bool>            buzzerStateField = GetField <bool>(alarmClock, "isOn");
            FieldInfo <PlaySoundResult> playResultField  = GetField <PlaySoundResult>(alarmClock, "alarmClockBuzzerSound");

            if (alarmClock == null || buzzerStateField == null || playResultField == null)
            {
                yield break;
            }

            if (_modSettings.Settings.RescanDirectory)
            {
                DebugLog("Rescanning the Sound Directory");
                var rescan = PickNextTrack(_modSettings.Settings.RescanDirectory);
                while (rescan.MoveNext())
                {
                    yield return(rescan.Current);
                }
                DebugLog("Rescan complete");
            }

            while (SceneManager.Instance.CurrentState == SceneManager.State.Gameplay)
            {
                if (buzzerStateField.Get())
                {
                    var normalBeep = _newClipQueue.Count == 0;

                    if (!normalBeep)
                    {
                        var forcedBeep = Random.Range(0, 100);
                        DebugLog("Alarm clock beep check. Rolling a D100. Need to roll higher than {0} for normal beep. Rolled a {1}.", 100 - _modSettings.Settings.ChanceOfNormalBeep, 100 - forcedBeep);
                        normalBeep |= forcedBeep < _modSettings.Settings.ChanceOfNormalBeep;
                        if (normalBeep)
                        {
                            DebugLog("Well, it looks like the clock isn't playing music right now. Kappa");
                        }

                        if (_modSettings.Settings.ChanceOfNormalBeep == 0 && forcedBeep == 0)
                        {
                            DebugLog("Wait, why are we rolling for alarm clock beep when that is impossible to get.");
                        }
                    }
                    else
                    {
                        DebugLog("Alarm clock beep check. Rolling a D100. Need to roll higher than {0} for normal beep. Rolled a natural twenty. Wait a minute, that was a D20.", 100 - _modSettings.Settings.ChanceOfNormalBeep);
                        DebugLog("Since there is no music queued anyways, the natural twenty still stands, regardless of the chance.");
                    }

                    AudioClips clip = normalBeep
                        ? new AudioClips(null, true)
                        : _newClipQueue.Dequeue();

                    // ReSharper disable once Unity.IncorrectMethodSignatureInStringLiteral
                    alarmClock.StopCoroutine("StopBuzzerAfterTime");
                    float       clipTime = -1;
                    AudioSource varAudio = null;
                    try
                    {
                        DebugLog("Alarm Clock just turned on. Trying to find out how long the clip length is.");
                        var playingSound = playResultField.Get();
                        if (playingSound != null)
                        {
                            var soundGroupVariation = playingSound.ActingVariation;
                            if (soundGroupVariation != null)
                            {
                                varAudio = soundGroupVariation.VarAudio;
                                if (varAudio != null)
                                {
                                    //varAudio.clip != null
                                    varAudio.Stop();
                                    _originalClip = varAudio.clip;

                                    if (!clip.IsVanilla)
                                    {
                                        varAudio.clip = clip.Clip;
                                    }

                                    DebugLog("Retrieved the clip successfully. The Clip name is {0} and the length is {1} seconds", varAudio.clip.name, varAudio.clip.length);
                                    var looped = varAudio.clip.name.ToLowerInvariant().Contains("[looped]");
                                    looped |= varAudio.clip.name.Equals("alarm_clock_beep");
                                    looped |= (clip.IsVanilla && _availableTracks.AudioFiles.Count > 0);
                                    var tracked = varAudio.clip.name.ToLowerInvariant().EndsWith(".it");
                                    tracked |= varAudio.clip.name.ToLowerInvariant().EndsWith(".s3m");
                                    tracked |= varAudio.clip.name.ToLowerInvariant().EndsWith(".xm");
                                    tracked |= varAudio.clip.name.ToLowerInvariant().EndsWith(".mod");
                                    if (looped)
                                    {
                                        clipTime      = _modSettings.Settings.AlarmClockBuzzerTime;
                                        varAudio.loop = true;
                                        DebugLog("The clip specified that it wants to be looped. Playing the Alarm clock for AlarmClockBuzzerTime.");
                                    }
                                    else
                                    {
                                        varAudio.loop = false;
                                        var shortSong = (tracked ? 600.0f : varAudio.clip.length) < _modSettings.Settings.AlarmClockBuzzerTime;
                                        clipTime = Mathf.Min(varAudio.clip.length, _modSettings.Settings.AlarmClockBuzzerTime);
                                        if (!shortSong)
                                        {
                                            var endTime   = tracked ? 600.0f : varAudio.clip.length - _modSettings.Settings.AlarmClockBuzzerTime;
                                            var startTime = Random.Range(0, endTime);
                                            varAudio.time = startTime;
                                            DebugLog("Playing clip from {0} to {1}", startTime, _modSettings.Settings.AlarmClockBuzzerTime + startTime);
                                        }
                                        else
                                        {
                                            DebugLog("Playing Entire clip");
                                        }
                                    }
                                    varAudio.Play();
                                }
                                else
                                {
                                    DebugLog("varAudio is null. Cannot continue.");
                                }
                            }
                            else
                            {
                                DebugLog("soundGroupVariation is null. Cannot continue.");
                            }
                        }
                        else
                        {
                            DebugLog("playingSound is null. Cannot continue.");
                        }
                    }
                    catch (Exception ex)
                    {
                        DebugLog("Failed to get Clip length due to Exception: {0}\n{1}", ex.Message, ex.StackTrace);
                        clipTime = _modSettings.Settings.AlarmClockBuzzerTime;
                    }

                    alarmClock.StartCoroutine(ShutOffAlarmClock(clipTime, alarmClock, buzzerStateField));

                    DebugLog("Alarm Clock will play for {0} seconds provided it isn't shut off sooner. Kappa", clipTime);

                    //Wait for Alarm clock to shut off.
                    yield return(new WaitUntil(() => !buzzerStateField.Get()));

                    if (varAudio != null && _originalClip != null)
                    {
                        varAudio.clip = _originalClip;
                        if (!clip.IsVanilla)
                        {
                            Object.Destroy(clip.Clip);
                        }
                    }
                }
                yield return(null);
            }
        }
コード例 #25
0
        private static List <OptionBehaviour> GetGameOptions(float lowestY)
        {
            List <OptionBehaviour> options = new List <OptionBehaviour>();

            /*EssentialsPlugin.Logger.LogInfo($"toggles {Object.FindObjectsOfType<ToggleOption>().Count}");
             * EssentialsPlugin.Logger.LogInfo($"numbers {Object.FindObjectsOfType<NumberOption>().Count}");
             * EssentialsPlugin.Logger.LogInfo($"strings {Object.FindObjectsOfType<StringOption>().Count}");
             * EssentialsPlugin.Logger.LogInfo($"keyvalues {Object.FindObjectsOfType<KeyValueOption>().Count}");*/
            ToggleOption toggleOption = Object.FindObjectsOfType <ToggleOption>().FirstOrDefault();
            NumberOption numberOption = Object.FindObjectsOfType <NumberOption>().FirstOrDefault();
            StringOption stringOption = Object.FindObjectsOfType <StringOption>().FirstOrDefault();
            //KeyValueOption kvOption = Object.FindObjectsOfType<KeyValueOption>().FirstOrDefault();

            int i = 0;

            foreach (CustomOption option in Options)
            {
                if (option.GameObject)
                {
                    option.GameObject.gameObject.SetActive(option.MenuVisible);

                    options.Add(option.GameObject);

                    continue;
                }

                if (option.Type == CustomOptionType.Toggle && AmongUsClient.Instance?.AmHost == true)
                {
                    if (toggleOption == null)
                    {
                        continue;
                    }

                    ToggleOption toggle = Object.Instantiate(toggleOption, toggleOption.transform.parent);//.DontDestroy();

                    if (!option.OnGameObjectCreated(toggle))
                    {
                        toggle?.gameObject?.Destroy();

                        continue;
                    }

                    options.Add(toggle);
                }
                else if (option.Type == CustomOptionType.Number)
                {
                    if (numberOption == null)
                    {
                        continue;
                    }

                    NumberOption number = Object.Instantiate(numberOption, numberOption.transform.parent);//.DontDestroy();

                    if (!option.OnGameObjectCreated(number))
                    {
                        number?.gameObject?.Destroy();

                        continue;
                    }

                    options.Add(number);
                }
                else if (option.Type == CustomOptionType.String || option.Type == CustomOptionType.Toggle && AmongUsClient.Instance?.AmHost != true)
                {
                    //if (option is IKeyValueOption)
                    //{
                    //    //if (kvOption == null) continue;

                    //    Transform parent = kvOption?.transform?.parent ?? toggleOption?.transform?.parent ?? numberOption?.transform?.parent ?? stringOption?.transform?.parent;

                    //    if (parent == null) continue;

                    //    KeyValueOption kv = kvOption == null ? new KeyValueOption().DontDestroy() : Object.Instantiate(kvOption);

                    //    if (kv == null) continue;

                    //    kv.transform.SetParent(/*kvOption.transform.*/parent);

                    //    option.OnGameOptionCreated(kv);

                    //    options.Add(kv);
                    //}

                    if (stringOption == null)
                    {
                        continue;
                    }

                    StringOption str = Object.Instantiate(stringOption, stringOption.transform.parent);//.DontDestroy();

                    if (!option.OnGameObjectCreated(str))
                    {
                        str?.gameObject?.Destroy();

                        continue;
                    }

                    options.Add(str);
                }

                if (!option.GameObject)
                {
                    continue;
                }

                if (Debug)
                {
                    EssentialsPlugin.Logger.LogInfo($"Option \"{option.Name}\" was created");
                }

                if (option.MenuVisible)
                {
                    option.GameObject.transform.localPosition = new Vector3(option.GameObject.transform.localPosition.x, lowestY - ++i * 0.5F, option.GameObject.transform.localPosition.z);
                }

                option.GameObject.gameObject.SetActive(option.MenuVisible);
            }

            return(options);
        }
コード例 #26
0
ファイル: Assertions.cs プロジェクト: nasa03/ness
        public static void CheckAssertions()
        {
            var assertions = Object.FindObjectsOfType(typeof(AssertionComponent)) as AssertionComponent[];

            CheckAssertions(assertions);
        }
コード例 #27
0
 private static void CheckComponents()
 {
     MonoBehaviour[] scripts = Object.FindObjectsOfType <MonoBehaviour>();
     AssertComponents(scripts);
 }
コード例 #28
0
 public static T[] FindObjectsOfType <T>(this MonoBehaviour obj) where T : MonoBehaviour
 {
     return(Object.FindObjectsOfType(typeof(T)) as T[]);
 }
コード例 #29
0
ファイル: Creator.cs プロジェクト: alters-mit/robot_creator
    /// <summary>
    /// Create a prefab from a .urdf file.
    /// </summary>
    /// <param name="urdfPath">The path to the .urdf file.</param>
    /// <param name="settings">Import settings for ROS.</param>
    /// <param name="immovable">If true, the root object is immovable.</param>
    private static void CreatePrefab(string urdfPath, ImportSettings settings, bool immovable)
    {
        // Import the robot.
        UrdfRobotExtensions.Create(urdfPath, settings);

        // Remove irrelevant ROS components.
        GameObject robot = Object.FindObjectOfType <UrdfRobot>().gameObject;

        robot.DestroyAll <UrdfJoint>();
        robot.DestroyAll <UrdfInertial>();
        robot.DestroyAll <UrdfVisuals>();
        robot.DestroyAll <UrdfVisual>();
        robot.DestroyAll <UrdfCollisions>();
        robot.DestroyAll <UrdfCollision>();
        robot.DestroyAll <UrdfLink>();
        robot.DestroyAll <UrdfRobot>();
        robot.DestroyAll <Controller>();
        // Destroy unwanted objects.
        robot.DestroyAllComponents <Light>();
        robot.DestroyAllComponents <Camera>();
        robot.DestroyAllComponents <UrdfPlugins>();

        // Save the generated collider meshes.
        string collidersDirectory = Path.Combine(Application.dataPath, "collider_meshes", robot.name);

        if (!Directory.Exists(collidersDirectory))
        {
            Directory.CreateDirectory(collidersDirectory);
        }
        foreach (MeshCollider mc in robot.GetComponentsInChildren <MeshCollider>())
        {
            mc.sharedMesh.name = Random.Range(0, 1000000).ToString();
            AssetDatabase.CreateAsset(mc.sharedMesh, "Assets/collider_meshes/" + robot.name + "/" + mc.sharedMesh.name);
            AssetDatabase.SaveAssets();
        }

        // Load the .urdf file.
        XmlDocument doc = new XmlDocument();

        doc.Load(urdfPath);
        XmlNode xmlRoot = doc.SelectSingleNode("robot");

        // Get the prismatic joints.
        XmlNodeList jointNodes = xmlRoot.SelectNodes("joint");
        // The name of each prismatic joint and its axis.
        Dictionary <string, DriveAxis> prismaticAxes = new Dictionary <string, DriveAxis>();

        for (int i = 0; i < jointNodes.Count; i++)
        {
            string jointType = jointNodes[i].Attributes["type"].Value.ToLower();
            if (jointType == "prismatic")
            {
                string jointChild = jointNodes[i].SelectSingleNode("child").Attributes["link"].Value;
                if (prismaticAxes.ContainsKey(jointChild))
                {
                    continue;
                }
                Vector3   xyz = jointNodes[i].SelectSingleNode("axis").Attributes["xyz"].Value.xyzToVector3();
                DriveAxis driveAxis;
                // Get the drive axis for a single-axis rotation.
                if (xyz.x != 0)
                {
                    driveAxis = DriveAxis.x;
                }
                else if (xyz.y != 0)
                {
                    driveAxis = DriveAxis.y;
                }
                else if (xyz.z != 0)
                {
                    driveAxis = DriveAxis.z;
                }
                else
                {
                    throw new System.Exception("No axis for: " + jointChild);
                }
                prismaticAxes.Add(jointChild, driveAxis);
            }
        }

        // Fix the articulation drives.;
        foreach (ArticulationBody a in robot.GetComponentsInChildren <ArticulationBody>())
        {
            if (a.jointType == ArticulationJointType.RevoluteJoint)
            {
                ArticulationDrive drive = a.xDrive;
                drive.stiffness = 1000;
                drive.damping   = 180;
                a.xDrive        = drive;
            }
            // Set the prismatic joint's drive values and expected axis.
            else if (a.jointType == ArticulationJointType.PrismaticJoint)
            {
                DriveAxis         da = prismaticAxes[a.name];
                ArticulationDrive drive;
                if (da == DriveAxis.x)
                {
                    drive = a.xDrive;
                }
                else if (da == DriveAxis.y)
                {
                    drive = a.yDrive;
                }
                else
                {
                    drive = a.zDrive;
                }
                drive.forceLimit = a.xDrive.forceLimit;
                drive.stiffness  = 1000;
                drive.damping    = 180;
                drive.lowerLimit = a.xDrive.lowerLimit;
                drive.upperLimit = a.xDrive.upperLimit;
                if (da == DriveAxis.x)
                {
                    a.linearLockX = ArticulationDofLock.LimitedMotion;
                    a.linearLockY = ArticulationDofLock.LockedMotion;
                    a.linearLockZ = ArticulationDofLock.LockedMotion;
                    a.xDrive      = drive;
                }
                else if (da == DriveAxis.y)
                {
                    a.linearLockX = ArticulationDofLock.LockedMotion;
                    a.linearLockY = ArticulationDofLock.LimitedMotion;
                    a.linearLockZ = ArticulationDofLock.LockedMotion;
                    a.yDrive      = drive;
                }
                else
                {
                    a.linearLockX = ArticulationDofLock.LockedMotion;
                    a.linearLockY = ArticulationDofLock.LockedMotion;
                    a.linearLockZ = ArticulationDofLock.LimitedMotion;
                    a.zDrive      = drive;
                }
                ExpectedDriveAxis eda = a.gameObject.AddComponent <ExpectedDriveAxis>();
                eda.axis = da;
            }
            a.anchorPosition = Vector3.zero;
            // Set the root articulation body as the root object.
            if (a.isRoot)
            {
                a.immovable = immovable;
            }
        }

        // Destroy redundant ArticulationBodies.
        ArticulationBody[] badBodies = robot.GetComponentsInChildren <ArticulationBody>().
                                       Where(a => !a.isRoot && a.mass < 0.01f && a.jointType == ArticulationJointType.FixedJoint &&
                                             a.GetComponentsInChildren <MeshFilter>().Length == 0 && a.GetComponentsInChildren <MeshCollider>().Length == 0).
                                       ToArray();
        foreach (ArticulationBody b in badBodies)
        {
            Object.DestroyImmediate(b.gameObject);
        }

        // Get the root object.
        if (robot.GetComponent <ArticulationBody>() == null)
        {
            ArticulationBody[] rootBodies = Object.FindObjectsOfType <ArticulationBody>().Where(a => a.isRoot).ToArray();
            if (rootBodies.Length != 1)
            {
                Debug.LogError("Root object of the robot doesn't have an ArticulationBody.");
            }
            else
            {
                rootBodies[0].gameObject.transform.parent = null;
                rootBodies[0].gameObject.name             = robot.name;
                Object.DestroyImmediate(robot);
                robot = rootBodies[0].gameObject;
            }
        }

        // Create the prefab directory if it doesn't exist.
        string absolutePrefabPath = Path.Combine(Application.dataPath, "prefabs");

        if (!Directory.Exists(absolutePrefabPath))
        {
            Directory.CreateDirectory(absolutePrefabPath);
        }

        // Create the prefab.
        PrefabUtility.SaveAsPrefabAsset(robot, "Assets/prefabs/" + robot.name + ".prefab");
        Object.DestroyImmediate(robot);
    }
コード例 #30
0
        public SaveData()
        {
            players      = new List <PlayerData>();
            enemies      = new List <EnemyData>();
            chests       = new List <ChestData>();
            barrels      = new List <BarrelData>();
            printers     = new List <PrinterData>();
            multiShops   = new List <MultiShopData>();
            brokenDrones = new List <BrokenDroneData>();
            fans         = new List <FanData>();

            chanceShrines    = new List <ShrineChanceData>();
            bloodShrines     = new List <ShrineBloodData>();
            bossShrines      = new List <ShrineBossData>();
            combatShrines    = new List <ShrineCombatData>();
            goldshoreShrines = new List <ShrineGoldshoresAccessData>();
            bazaarPods       = new List <BazaarPodData>();
            lunarCauldrons   = new List <LunarCauldronData>();
            healingShrines   = new List <ShrineHealingData>();
            orderShrines     = new List <ShrineRestackData>();

            itemDroplets = new List <ItemDropletData>();
            portals      = new List <PortalData>();
            beacons      = new List <BeaconData>();

            foreach (var item in NetworkUser.readOnlyInstancesList)
            {
                players.Add(new PlayerData(item));
            }

            foreach (var item in Object.FindObjectsOfType <CharacterMaster>())
            {
                if (item.GetBody() != null)
                {
                    if (!item.GetBody().isPlayerControlled)
                    {
                        enemies.Add(new EnemyData(item));
                    }
                }
            }
            foreach (var item in Object.FindObjectsOfType <ChestBehavior>())
            {
                chests.Add(new ChestData(item));
            }
            foreach (var item in Object.FindObjectsOfType <BarrelInteraction>())
            {
                barrels.Add(new BarrelData(item));
            }
            foreach (var item in Object.FindObjectsOfType <ShopTerminalBehavior>())
            {
                if (item.name.Contains("Duplicator"))
                {
                    printers.Add(new PrinterData(item));
                }
                if (item.name.Contains("LunarShopTerminal"))
                {
                    bazaarPods.Add(new BazaarPodData(item));
                }
                if (item.name.Contains("LunarCauldron"))
                {
                    lunarCauldrons.Add(new LunarCauldronData(item));
                }
            }
            foreach (var item in Object.FindObjectsOfType <MultiShopController>())
            {
                multiShops.Add(new MultiShopData(item));
            }
            foreach (var item in Object.FindObjectsOfType <ShrineChanceBehavior>())
            {
                chanceShrines.Add(new ShrineChanceData(item));
            }
            foreach (var item in Object.FindObjectsOfType <ShrineBloodBehavior>())
            {
                bloodShrines.Add(new ShrineBloodData(item));
            }
            foreach (var item in Object.FindObjectsOfType <ShrineBossBehavior>())
            {
                bossShrines.Add(new ShrineBossData(item));
            }
            foreach (var item in Object.FindObjectsOfType <ShrineCombatBehavior>())
            {
                combatShrines.Add(new ShrineCombatData(item));
            }
            foreach (var item in Object.FindObjectsOfType <ShrineHealingBehavior>())
            {
                healingShrines.Add(new ShrineHealingData(item));
            }
            foreach (var item in Object.FindObjectsOfType <ShrineRestackBehavior>())
            {
                orderShrines.Add(new ShrineRestackData(item));
            }
            foreach (var item in Object.FindObjectsOfType <PortalStatueBehavior>())
            {
                if (item.name.Contains("Goldshores"))
                {
                    goldshoreShrines.Add(new ShrineGoldshoresAccessData(item));
                }
            }
            foreach (var item in Object.FindObjectsOfType <SummonMasterBehavior>())
            {
                brokenDrones.Add(new BrokenDroneData(item));
            }
            foreach (var item in Object.FindObjectsOfType <GenericPickupController>())
            {
                if (item.enabled)
                {
                    itemDroplets.Add(new ItemDropletData(item));
                }
            }
            foreach (var item in Object.FindObjectsOfType <SceneExitController>())
            {
                if (!item.name.Contains("Teleporter"))
                {
                    if (item.destinationScene.sceneName != null)
                    {
                        portals.Add(new PortalData(item));
                    }
                }
            }
            foreach (var item in Object.FindObjectsOfType <PurchaseInteraction>())
            {
                if (item.name.Contains("GoldshoresBeacon"))
                {
                    Debug.Log(item.name);
                    beacons.Add(new BeaconData(item));
                }
                if (item.name.Contains("HumanFan"))
                {
                    Debug.Log(item.name);
                    fans.Add(new FanData(item));
                }
            }
            if (TeleporterInteraction.instance)
            {
                teleporter = new TeleporterData(TeleporterInteraction.instance);
            }
            run = new RunData(Object.FindObjectOfType <Run>());
        }