Representation of Script assets.

Inheritance: UnityEngine.TextAsset
		void OnEnable() {
			if (!Application.isPlaying) {
				monoScript = MonoScript.FromMonoBehaviour(script);
				int currentExecutionOrder = MonoImporter.GetExecutionOrder(monoScript);
				if (currentExecutionOrder != 10200) MonoImporter.SetExecutionOrder(monoScript, 10200);
			}
		}
Esempio n. 2
0
    static Type[] GetScriptDependencies(UnityEditor.MonoScript script)
    {
        if (script == null)
        {
            return(new Type[0]);
        }

        var currentType = script.GetClass();

        if (currentType == null)
        {
            return(new Type[0]);
        }

        Type[] output = null;
        if (!s_dependencyAttributes.TryGetValue(script, out output))
        {
            List <Type> types = new List <Type>();

            var attribs = currentType.GetCustomAttributes(typeof(ScriptDependencyAttribute), true);
            for (int i = 0; i < attribs.Length; ++i)
            {
                var dep = attribs[i] as ScriptDependencyAttribute;
                if (dep == null)
                {
                    continue;
                }
                types.AddRange(dep.GetScriptDependencies()
                               .Where(x => typeof(ScriptableObject).IsAssignableFrom(x) || typeof(MonoBehaviour).IsAssignableFrom(x))
                               );
            }
            s_dependencyAttributes[script] = output = types.ToArray();
        }
        return(output);
    }
		private ScriptNavigatorItem ScriptNavigatorItemFor(MonoScript script, string path)
		{
			var fullPath = System.IO.Path.GetFullPath(path); // get extension
			var fileName = System.IO.Path.GetFileName(fullPath);
			var instanceID = script.GetInstanceID();
			return new ScriptNavigatorItem(fileName, instanceID, FileNavigationService);
		}
 private void Init(MonoScript script)
 {
     this.m_Initialized = true;
     this.m_ScriptClass = script.GetClass();
     this.m_NetworkChannelLabel = new GUIContent("Network Channel", "QoS channel used for updates. Use the [NetworkSettings] class attribute to change this.");
     this.m_NetworkSendIntervalLabel = new GUIContent("Network Send Interval", "Maximum update rate in seconds. Use the [NetworkSettings] class attribute to change this, or implement GetNetworkSendInterval");
     foreach (System.Reflection.FieldInfo info in this.m_ScriptClass.GetFields(BindingFlags.Public | BindingFlags.Instance))
     {
         Attribute[] customAttributes = (Attribute[]) info.GetCustomAttributes(typeof(SyncVarAttribute), true);
         if (customAttributes.Length > 0)
         {
             this.m_SyncVarNames.Add(info.Name);
         }
     }
     MethodInfo method = script.GetClass().GetMethod("OnSerialize");
     if ((method != null) && (method.DeclaringType != typeof(NetworkBehaviour)))
     {
         this.m_HasOnSerialize = true;
     }
     int num2 = 0;
     foreach (System.Reflection.FieldInfo info3 in base.serializedObject.targetObject.GetType().GetFields())
     {
         if ((info3.FieldType.BaseType != null) && info3.FieldType.BaseType.Name.Contains("SyncList"))
         {
             num2++;
         }
     }
     if (num2 > 0)
     {
         this.m_ShowSyncLists = new bool[num2];
     }
 }
Esempio n. 5
0
    // Called at the first frame when the component is enabled
    void Start()
    {
        // Ensure we only read data if the application is playing
        // and we have a state file to initialize the engine with
        if (!Application.isPlaying || initialStateFile == null)
        {
            return;
        }

        // Allocate PulseEngine with log file path
        string dateAndTimeVar = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss");
        string logFilePath    = Application.persistentDataPath + "/" +
                                gameObject.name +
                                dateAndTimeVar + ".log";

        // Set the data_directory for Pulse to find all the data files it expects
        // This code will derive the data directory based on how this project was
        // included in the editor. Still investigating how to set data_dir in a package
        UnityEditor.MonoScript ms = UnityEditor.MonoScript.FromMonoBehaviour(this);
        string path = UnityEditor.AssetDatabase.GetAssetPath(ms);

        path   = System.IO.Path.GetDirectoryName(path) + "/../Data";
        engine = new PulseEngine(logFilePath, path);

        // Initialize engine state from tje state file content
        engine.SerializeFromString(initialStateFile.text,
                                   null, // requested data currently hardcoded
                                   serializationFormat,
                                   Time.time);

        previousTime = Time.time;
    }
Esempio n. 6
0
    private static void ProcessManagerAttributes()
    {
        var types = new string[] { ".cs", ".js" };

        var allScriptPaths = Directory.GetFiles("Assets", "*.*", SearchOption.AllDirectories)
                             .Where(s => types.Any(x => s.EndsWith(x, System.StringComparison.CurrentCultureIgnoreCase)))
                             .ToArray();

        instance.m_attributes.Clear();

        for (int i = 0; i < allScriptPaths.Length; ++i)
        {
            UnityEditor.MonoScript script = UnityEditor.AssetDatabase.LoadAssetAtPath(allScriptPaths[i], typeof(UnityEditor.MonoScript)) as UnityEditor.MonoScript;
            if (!script || script.GetClass() == null)
            {
                continue;
            }
            if (!typeof(Manager).IsAssignableFrom(script.GetClass()))
            {
                continue;
            }

            var type = script.GetClass();
            instance.m_attributes[type] = new ManagerAttributes(type);
        }

        instance.hideFlags = HideFlags.NotEditable;
        UnityEditor.EditorUtility.SetDirty(instance);
        var so = new UnityEditor.SerializedObject(instance);

        so.UpdateIfDirtyOrScript();
        UnityEditor.AssetDatabase.SaveAssets();
    }
Esempio n. 7
0
            public static void Set(SerializedObject target, UnityEditor.MonoScript script)
            {
                var property = target.FindProperty("m_Script");

                property.objectReferenceValue = script;

                target.ApplyModifiedProperties();
            }
        public override void OnInspectorGUI()
        {
            var proCamera2DTriggerInfluence = (ProCamera2DTriggerInfluence)target;

            if(proCamera2DTriggerInfluence.ProCamera2D == null)
                EditorGUILayout.HelpBox("ProCamera2D is not set.", MessageType.Error, true);
            
            serializedObject.Update();

            // Show script link
            GUI.enabled = false;
            _script = EditorGUILayout.ObjectField("Script", _script, typeof(MonoScript), false) as MonoScript;
            GUI.enabled = true;

            // ProCamera2D
            _tooltip = new GUIContent("Pro Camera 2D", "");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("ProCamera2D"), _tooltip);            

            // Update interval
            _tooltip = new GUIContent("Update Interval", "Every X seconds detect collision. Smaller frequencies are more precise but also require more processing.");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("UpdateInterval"), _tooltip);            

            if (proCamera2DTriggerInfluence.UpdateInterval <= 0.01f)
                proCamera2DTriggerInfluence.UpdateInterval = 0.01f;

            // Trigger shape
            _tooltip = new GUIContent("Trigger Shape", "");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("TriggerShape"), _tooltip);

            // Focus point
            _tooltip = new GUIContent("Focus Point", "If set, the focus point will be this instead of the center of the trigger");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("FocusPoint"), _tooltip);

            // Influence smoothness
            _tooltip = new GUIContent("Influence Smoothness", "How smoothly should the camera move towards the focus point?");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("InfluenceSmoothness"), _tooltip);

            if (proCamera2DTriggerInfluence.InfluenceSmoothness < 0f)
                proCamera2DTriggerInfluence.InfluenceSmoothness = 0f;

            // Exclusive influence percentage
            _tooltip = new GUIContent("Exclusive Influence Percentage", "After entering this area the camera will reach it's max zoom value");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("ExclusiveInfluencePercentage"), _tooltip);

            // Trigger targets
            EditorGUILayout.BeginHorizontal();
            var tooltip = new GUIContent("Use Targets Mid Point", "If checked, the trigger will use the mid point of all your camera targets");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("UseTargetsMidPoint"), tooltip);

            if (!proCamera2DTriggerInfluence.UseTargetsMidPoint)
            {
                tooltip = new GUIContent("Trigger Target", "The target to use instead of the mid point of all camera targets");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("TriggerTarget"), tooltip);
            }
            EditorGUILayout.EndHorizontal();

            serializedObject.ApplyModifiedProperties();
        }
        void OnEnable()
        {
            var proCamera2DForwardFocus = (ProCamera2DForwardFocus)target;

            if(proCamera2DForwardFocus.ProCamera2D == null && Camera.main != null)
                proCamera2DForwardFocus.ProCamera2D = Camera.main.GetComponent<ProCamera2D>();

            _script = MonoScript.FromMonoBehaviour((ProCamera2DForwardFocus)target);
        }
        void OnEnable()
        {
            var proCamera2DTriggerInfluence = (ProCamera2DTriggerInfluence)target;

            if(proCamera2DTriggerInfluence.ProCamera2D == null && Camera.main != null)
                proCamera2DTriggerInfluence.ProCamera2D = Camera.main.GetComponent<ProCamera2D>();

            _script = MonoScript.FromMonoBehaviour(proCamera2DTriggerInfluence);
        }
        void OnEnable()
        {
            var proCamera2DCameraWindow = (ProCamera2DCameraWindow)target;

            if(proCamera2DCameraWindow.ProCamera2D == null && Camera.main != null)
                proCamera2DCameraWindow.ProCamera2D = Camera.main.GetComponent<ProCamera2D>();

            _script = MonoScript.FromMonoBehaviour((ProCamera2DCameraWindow)target);
        }
        void OnEnable()
        {
            var proCamera2DPixelPerfectSprite = (ProCamera2DPixelPerfectSprite)target;

            if (proCamera2DPixelPerfectSprite.ProCamera2D == null && Camera.main != null)
                proCamera2DPixelPerfectSprite.ProCamera2D = Camera.main.GetComponent<ProCamera2D>();

            _script = MonoScript.FromMonoBehaviour(proCamera2DPixelPerfectSprite);
        }
Esempio n. 13
0
	void OnGUI()
	{
		// CSV
		TextAsset newCsv = EditorGUILayout.ObjectField("CSV", csv, typeof(TextAsset), false) as TextAsset;
		if(newCsv != csv)
		{
			csv = newCsv;
			if(csv != null)
				arr = CsvParser2.Parse(csv.text);
			else
				arr = null;
		}

		// Script
		script = EditorGUILayout.ObjectField("Script", script, typeof(MonoScript), false) as MonoScript;

		// buttons
		EditorGUILayout.BeginHorizontal();
		if(GUILayout.Button("Refresh") && csv != null)
			arr = CsvParser2.Parse(csv.text);
		if(GUILayout.Button("Generate Code"))
		{
			string path = "";
			if(script != null)
			{
				path = AssetDatabase.GetAssetPath(script);
			}
			else
			{
				path = EditorUtility.SaveFilePanel("Save Script", "Assets", csv.name + "Table.cs", "cs");
            }
            if(!string.IsNullOrEmpty(path))
                script = CreateScript(csv, path);
        }
		EditorGUILayout.EndHorizontal();

		// columns
		if(arr != null)
		{
			foldout = EditorGUILayout.Foldout(foldout, "Columns");
			if(foldout)
			{
				EditorGUI.indentLevel++;
				if(csv != null && arr == null)
					arr = CsvParser2.Parse(csv.text);
				if(arr != null)
				{
					for(int i = 0 ; i < arr[0].Length ; i++)
					{
						EditorGUILayout.LabelField(arr[0][i]);
					}
				}
				EditorGUI.indentLevel--;
			}
		}
	}
        public override void OnInspectorGUI()
        {
            var proCamera2DForwardFocus = (ProCamera2DForwardFocus)target;

            serializedObject.Update();

            // Show script link
            _script = EditorGUILayout.ObjectField("Script", _script, typeof(MonoScript), false) as MonoScript;

            // ProCamera2D
            _tooltip = new GUIContent("Pro Camera 2D", "");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("ProCamera2D"), _tooltip);

            if(proCamera2DForwardFocus.ProCamera2D == null)
                EditorGUILayout.HelpBox("ProCamera2D is not set.", MessageType.Error, true);

            // Progressive
            _tooltip = new GUIContent("Progressive", "Should the forward focus move progressively based on the camera speed or should it transition to the focus based on the direction.");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("Progressive"), _tooltip);

            // Speed multiplier
            if(proCamera2DForwardFocus.Progressive)
            {
                _tooltip = new GUIContent("Speed Multiplier", "Multiply the camera speed by this number. You probably only want to change this value if the camera speed is not sufficient to reach the target focus.");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("SpeedMultiplier"), _tooltip);
            }

            // Transition smoothness
            _tooltip = new GUIContent("Transition smoothness", "How smoothly should the forward focus influence move?");

            EditorGUILayout.PropertyField(serializedObject.FindProperty("TransitionSmoothness"), _tooltip);

            if(proCamera2DForwardFocus.TransitionSmoothness < 0f) proCamera2DForwardFocus.TransitionSmoothness = 0f;

            // Maintain Influence On Stop
            _tooltip = new GUIContent("Maintain Influence On Stop", "Should the influence maintain after the camera stops?");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("MaintainInfluenceOnStop"), _tooltip);

            // Left focus
            _tooltip = new GUIContent("Left Focus", "How much should the camera compensate when moving left?");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("LeftFocus"), _tooltip);

            // Right focus
            _tooltip = new GUIContent("Right Focus", "How much should the camera compensate when moving right?");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("RightFocus"), _tooltip);

            // Up focus
            _tooltip = new GUIContent("Up Focus", "How much should the camera compensate when moving up?");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("TopFocus"), _tooltip);

            // Down focus
            _tooltip = new GUIContent("Down Focus", "How much should the camera compensate when moving down?");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("BottomFocus"), _tooltip);

            serializedObject.ApplyModifiedProperties();
        }
Esempio n. 15
0
		void OnEnable() {
			if (serializedObject == null) return;
			
			// Changing the script execution order
			if (!Application.isPlaying) {
				monoScript = MonoScript.FromMonoBehaviour(script);
				int currentExecutionOrder = MonoImporter.GetExecutionOrder(monoScript);
				if (currentExecutionOrder != 10000) MonoImporter.SetExecutionOrder(monoScript, 10000);
			}
		}
        public override void OnInspectorGUI()
        {
            var proCamera2DCameraWindow = (ProCamera2DCameraWindow)target;
            if (proCamera2DCameraWindow.ProCamera2D == null)
            {
                EditorGUILayout.HelpBox("ProCamera2D is not set.", MessageType.Error, true);
                return;
            }

            serializedObject.Update();

            // Show script link
            GUI.enabled = false;
            _script = EditorGUILayout.ObjectField("Script", _script, typeof(MonoScript), false) as MonoScript;
            GUI.enabled = true;

            // ProCamera2D
            _tooltip = new GUIContent("Pro Camera 2D", "");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("ProCamera2D"), _tooltip);


            string hAxis = "";
            string vAxis = "";
            switch (proCamera2DCameraWindow.ProCamera2D.Axis)
            {
                case MovementAxis.XY:
                    hAxis = "X";
                    vAxis = "Y";
                    break;

                case MovementAxis.XZ:
                    hAxis = "X";
                    vAxis = "Z";
                    break;

                case MovementAxis.YZ:
                    hAxis = "Y";
                    vAxis = "Z";
                    break;
            }

            _tooltip = new GUIContent("Width", "Window width");
            EditorGUILayout.Slider(serializedObject.FindProperty("CameraWindowRect.width"), 0f, 1f, _tooltip);

            _tooltip = new GUIContent("Height", "Window height");
            EditorGUILayout.Slider(serializedObject.FindProperty("CameraWindowRect.height"), 0f, 1f, _tooltip);

            _tooltip = new GUIContent(hAxis, "Window horizontal offset");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("CameraWindowRect.x"), _tooltip);

            _tooltip = new GUIContent(vAxis, "Window vertical offset");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("CameraWindowRect.y"), _tooltip);

            serializedObject.ApplyModifiedProperties();
        }
        void OnEnable()
        {
            ProCamera2DEditorHelper.AssignProCamera2D(target as BasePC2D);

            _script = MonoScript.FromMonoBehaviour((ProCamera2DTriggerRails)target);

            var proCamera2DTriggerRails = (ProCamera2DTriggerRails)target;

            if(proCamera2DTriggerRails.ProCamera2D != null && proCamera2DTriggerRails.ProCamera2DRails == null)
                proCamera2DTriggerRails.ProCamera2DRails = proCamera2DTriggerRails.ProCamera2D.GetComponentInChildren<ProCamera2DRails>();
        }
Esempio n. 18
0
    /// <summary>
    /// Visit this script and all dependencies (adding them recursively to the sorted list).
    /// This also builds a connections table that can be used as a nondirected graph of dependencies
    /// </summary>
    static void SortDependencies_Visit(UnityEditor.MonoScript current,
                                       HashSet <UnityEditor.MonoScript> visited,
                                       List <UnityEditor.MonoScript> sortedItems,
                                       Dictionary <Type, UnityEditor.MonoScript> lookup,
                                       UnityEditor.MonoScript visitedBy,
                                       Dictionary <UnityEditor.MonoScript, HashSet <UnityEditor.MonoScript> > connections
                                       )
    {
        if (visited.Add(current))
        {
            //
            // visit all dependencies (adding them recursively to the sorted list) before adding ourselves to the sorted list
            // this ensures that
            // 1. all dependencies are sorted
            // 2. cyclic dependencies can be caught if an item is visited AND it's been added to this list
            var depsRemaining = GetScriptDependencies(current);

            var visitedFrom = current;

            // do deps with fixed orders first
            for (int i = 0; i < depsRemaining.Length; ++i)
            {
                SortDependencies_Visit_VisitDependency(visited, sortedItems, lookup, connections, depsRemaining[i], visitedFrom,
                                                       true,
                                                       false);
            }

            // then non-leaves
            for (int i = 0; i < depsRemaining.Length; ++i)
            {
                SortDependencies_Visit_VisitDependency(visited, sortedItems, lookup, connections, depsRemaining[i], visitedFrom,
                                                       false,
                                                       false);
            }

            // then any leaves
            for (int i = 0; i < depsRemaining.Length; ++i)
            {
                SortDependencies_Visit_VisitDependency(visited, sortedItems, lookup, connections, depsRemaining[i], visitedFrom,
                                                       false,
                                                       true);
            }

#if LOG_DEBUG_VERBOSE
            Debug.Log("Sorted " + current.name);
#endif
            sortedItems.Add(current);
        }
        else
        {
            Debug.Assert(sortedItems.Contains(current), "Cyclic dependency found for ScriptDependency " + current.name + " via " + (visitedBy != null?visitedBy.name:"Unknown") + "!");
        }
    }
	static MonoScript _mono_pe;	///< MonoScript assets

	/**
	 * Load the pb_Object and pb_Entity classes to MonoScript assets.  Saves us from having to fall back on Reflection.
	 */
	static void LoadMonoScript()
	{
		GameObject go = new GameObject();

		pb_Object pb = go.AddComponent<pb_Object>();
		pb_Entity pe = go.AddComponent<pb_Entity>();

		_mono_pb = MonoScript.FromMonoBehaviour( pb );
		_mono_pe = MonoScript.FromMonoBehaviour( pe );

		DestroyImmediate(go);
	}
Esempio n. 20
0
        private static bool IsCustomizableScript(MonoScript script)
        {
            bool isCustomizable = false;

            Type scriptClass = script.GetClass();
            if (scriptClass != null)
            {
                isCustomizable = scriptClass.IsSubclassOf(typeof(MonoBehaviour)) || scriptClass.IsSubclassOf(typeof(ScriptableObject));
            }

            return isCustomizable;
        }
    ScriptData Init_Script(UnityEditor.MonoScript script)
    {
        if (script == null)
        {
            throw new System.ArgumentNullException("Init_Script: script cannot be null");
        }

        var scriptClass = script.GetClass();

        if (scriptClass == null)
        {
            throw new System.ArgumentNullException("Init_Script: must be a monoscript with a valid class");
        }

        ScriptData scriptData = null;

        if (scriptDataTable.TryGetValue(script, out scriptData))
        {
            return(scriptData);
        }
        else
        {
            scriptData        = scriptDataTable[script] = new ScriptData();
            scriptData.script = script;
        }


        var fixedOrderAttribute = scriptClass.GetCustomAttributes(typeof(ScriptExecutionOrderAttribute), true).Cast <ScriptExecutionOrderAttribute>().FirstOrDefault();

        if (fixedOrderAttribute != null)
        {
            scriptData.fixedOrderValue = fixedOrderAttribute.order;
        }
        var dependsOnAttributes = scriptClass.GetCustomAttributes(typeof(ScriptDependencyAttribute), true).Cast <ScriptDependencyAttribute>().ToArray();

        foreach (var i in dependsOnAttributes)
        {
            var dependsOnTypes = i.GetScriptDependencies()
                                 .Where(x => typeLookup.ContainsKey(x))
                                 .Select(x => typeLookup[x])
                                 .ToArray();

            foreach (var j in dependsOnTypes)
            {
                var dependsOnSD = Init_Script(j);
                dependsOnSD.dependedOnBy.Add(scriptData);
                scriptData.dependsOn.Add(dependsOnSD);
            }
        }

        return(scriptData);
    }
        public override void OnInspectorGUI()
        {
            var proCamera2DTriggerRails = (ProCamera2DTriggerRails)target;

            if(proCamera2DTriggerRails.ProCamera2D == null)
                EditorGUILayout.HelpBox("ProCamera2D is not set.", MessageType.Error, true);

            serializedObject.Update();

            // Show script link
            GUI.enabled = false;
            _script = EditorGUILayout.ObjectField("Script", _script, typeof(MonoScript), false) as MonoScript;
            GUI.enabled = true;

            // ProCamera2D
            _tooltip = new GUIContent("Pro Camera 2D", "");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("ProCamera2D"), _tooltip);            

            // Update interval
            _tooltip = new GUIContent("Update Interval", "Every X seconds detect collision. Smaller frequencies are more precise but also require more processing.");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("UpdateInterval"), _tooltip);            

            if (proCamera2DTriggerRails.UpdateInterval <= 0.01f)
                proCamera2DTriggerRails.UpdateInterval = 0.01f;

            // Trigger shape
            _tooltip = new GUIContent("Trigger Shape", "");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("TriggerShape"), _tooltip);

            // Trigger targets
            EditorGUILayout.BeginHorizontal();
            _tooltip = new GUIContent("Use Targets Mid Point", "If checked, the trigger will use the mid point of all your camera targets");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("UseTargetsMidPoint"), _tooltip);

            if (!proCamera2DTriggerRails.UseTargetsMidPoint)
            {
                _tooltip = new GUIContent("Trigger Target", "The target to use instead of the mid point of all camera targets");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("TriggerTarget"), _tooltip);
            }
            EditorGUILayout.EndHorizontal();

            // Mode
            _tooltip = new GUIContent("Mode", "Choose if you want this trigger to enable or disable the rails.");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("Mode"), _tooltip);

            // Transition Duration
            _tooltip = new GUIContent("Transition Duration", "The time it should take to transition from/to rails.");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("TransitionDuration"), _tooltip);


            serializedObject.ApplyModifiedProperties();
        }
    static Type[] GetScriptDependencies(UnityEditor.MonoScript script)
    {
        if (script == null)
        {
            return(new Type[0]);
        }

        var currentType = script.GetClass();

        if (currentType == null)
        {
            return(new Type[0]);
        }

        if (s_compatibleTypes == null)
        {
            var scriptsToSort = MonoImporter.GetAllRuntimeMonoScripts()
                                .Select(x => x.GetClass())
                                .Where(x => x != null)
                                .Distinct()
                                .ToArray();

            s_compatibleTypes = scriptsToSort.ToDictionary(
                x => x,
                x => scriptsToSort.Where(x.IsAssignableFrom).ToArray());
        }

        Type[] output = null;
        if (!s_dependencyAttributes.TryGetValue(script, out output))
        {
            HashSet <Type> types = new HashSet <Type>();

            var attribs = currentType.GetCustomAttributes(typeof(ScriptDependencyAttribute), true);
            for (int i = 0; i < attribs.Length; ++i)
            {
                var dep = attribs[i] as ScriptDependencyAttribute;
                if (dep == null)
                {
                    continue;
                }

                foreach (var depType in dep.GetScriptDependencies())
                {
                    types.UnionWith(s_compatibleTypes[depType]);
                }
            }
            s_dependencyAttributes[script] = output = types.ToArray();
        }
        return(output);
    }
        void OnEnable()
        {
            ProCamera2DEditorHelper.AssignProCamera2D(target as BasePC2D);

			var proCamera2DTriggerBoundaries = (ProCamera2DTriggerBoundaries)target;

            if (proCamera2DTriggerBoundaries.NumericBoundaries == null && proCamera2DTriggerBoundaries.ProCamera2D != null)
            {
                var numericBoundaries = proCamera2DTriggerBoundaries.ProCamera2D.GetComponent<ProCamera2DNumericBoundaries>();
                proCamera2DTriggerBoundaries.NumericBoundaries = numericBoundaries == null ? proCamera2DTriggerBoundaries.ProCamera2D.gameObject.AddComponent<ProCamera2DNumericBoundaries>() : numericBoundaries;
            }

            _script = MonoScript.FromMonoBehaviour(proCamera2DTriggerBoundaries);
        }
    private static void ProcessDependencies()
    {
        ResourceSingletonBuilder.BuildResourceSingletonsIfDirty();

        var so = new UnityEditor.SerializedObject(instance);

        var types = new string[] { ".cs", ".js" };

        var allScriptPaths = Directory.GetFiles("Assets", "*.*", SearchOption.AllDirectories)
                             .Where(s => types.Any(x => s.EndsWith(x, System.StringComparison.CurrentCultureIgnoreCase)))
                             .ToArray();

        instance.m_serializedItems.Clear();

        for (int i = 0; i < allScriptPaths.Length; ++i)
        {
            UnityEditor.MonoScript script = UnityEditor.AssetDatabase.LoadAssetAtPath(allScriptPaths[i], typeof(UnityEditor.MonoScript)) as UnityEditor.MonoScript;

            if (!script || script.GetClass() == null)
            {
                continue;
            }

            var type = script.GetClass();
            if (!typeof(Component).IsAssignableFrom(script.GetClass()) &&
                !typeof(ScriptableObject).IsAssignableFrom(script.GetClass()))
            {
                continue;
            }

            var typeExecutionOrder = UnityEditor.MonoImporter.GetExecutionOrder(script);
            if (typeExecutionOrder == 0)
            {
                continue;
            }

            instance.m_serializedItems.Add(new SerializedItem()
            {
                typeName       = type.FullName,
                executionOrder = typeExecutionOrder,
            });
        }

        so.Update();
        instance.hideFlags = HideFlags.NotEditable;
        UnityEditor.EditorUtility.SetDirty(instance);
        UnityEditor.AssetDatabase.Refresh();
    }
        /// <summary> Automatically delete Node sub-assets before deleting their script.
        /// This is important to do, because you can't delete null sub assets.
        /// <para/> For another workaround, see: https://gitlab.com/RotaryHeart-UnityShare/subassetmissingscriptdelete </summary>
        private static AssetDeleteResult OnWillDeleteAsset(string path, RemoveAssetOptions options)
        {
            // Skip processing anything without the .cs extension
            if (Path.GetExtension(path) != ".cs")
            {
                return(AssetDeleteResult.DidNotDelete);
            }

            // Get the object that is requested for deletion
            UnityEngine.Object obj = AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(path);

            // If we aren't deleting a script, return
            if (!(obj is UnityEditor.MonoScript))
            {
                return(AssetDeleteResult.DidNotDelete);
            }

            // Check script type. Return if deleting a non-node script
            UnityEditor.MonoScript script     = obj as UnityEditor.MonoScript;
            System.Type            scriptType = script.GetClass();
            if (scriptType == null || (scriptType != typeof(XNode.Node) && !scriptType.IsSubclassOf(typeof(XNode.Node))))
            {
                return(AssetDeleteResult.DidNotDelete);
            }

            // Find all ScriptableObjects using this script
            string[] guids = AssetDatabase.FindAssets("t:" + scriptType);
            for (int i = 0; i < guids.Length; i++)
            {
                string   assetpath = AssetDatabase.GUIDToAssetPath(guids[i]);
                Object[] objs      = AssetDatabase.LoadAllAssetRepresentationsAtPath(assetpath);
                for (int k = 0; k < objs.Length; k++)
                {
                    XNode.Node node = objs[k] as XNode.Node;
                    if (node.GetType() == scriptType)
                    {
                        if (node != null && node.graph != null)
                        {
                            // Delete the node and notify the user
                            Debug.LogWarning(node.name + " of " + node.graph + " depended on deleted script and has been removed automatically.", node.graph);
                            node.graph.RemoveNode(node);
                        }
                    }
                }
            }
            // We didn't actually delete the script. Tell the internal system to carry on with normal deletion procedure
            return(AssetDeleteResult.DidNotDelete);
        }
Esempio n. 27
0
    void OnValidate()
    {
#if UNITY_EDITOR
        if (script != null)
        {
            UnityEditor.MonoScript monoscript = (UnityEditor.MonoScript)script;

            if (monoscript == null)
            {
                throw new InvalidOperationException("Text asset is not a valid Monoscript");
            }

            stateClassFullName = monoscript.GetClass().FullName;
        }
#endif
    }
 public void MonoScriptIconChanged(MonoScript monoScript)
 {
   if ((UnityEngine.Object) monoScript == (UnityEngine.Object) null)
     return;
   bool flag = true;
   using (List<MonoScript>.Enumerator enumerator = this.m_MonoScriptIconsChanged.GetEnumerator())
   {
     while (enumerator.MoveNext())
     {
       if (enumerator.Current.GetInstanceID() == monoScript.GetInstanceID())
         flag = false;
     }
   }
   if (!flag)
     return;
   this.m_MonoScriptIconsChanged.Add(monoScript);
 }
Esempio n. 29
0
		void OnEnable() {
			if (serializedObject == null) return;

			// Changing the script execution order
			if (!Application.isPlaying) {
				int executionOrder = 0;
				monoScript = MonoScript.FromMonoBehaviour(GetMonoBehaviour(out executionOrder));
				int currentExecutionOrder = MonoImporter.GetExecutionOrder(monoScript);
				if (currentExecutionOrder != executionOrder) MonoImporter.SetExecutionOrder(monoScript, executionOrder);
			}

			solver = serializedObject.FindProperty("solver");
			timeStep = new SerializedContent(serializedObject.FindProperty("timeStep"), new GUIContent("Time Step", "If zero, will update the solver in every LateUpdate(). Use this for chains that are animated. If > 0, will be used as updating frequency so that the solver will reach its target in the same time on all machines."));
			fixTransforms = new SerializedContent(serializedObject.FindProperty("fixTransforms"), new GUIContent("Fix Transforms", "If true, will fix all the Transforms used by the solver to their initial state in each Update. This prevents potential problems with unanimated bones and animator culling with a small cost of performance. Not recommended for CCD and FABRIK solvers."));

			OnEnableVirtual();
		}
Esempio n. 30
0
        void OnEnable()
        {
            if (serializedObject == null) return;

            // Changing the script execution order
            if (!Application.isPlaying) {
                int executionOrder = 0;
                monoScript = MonoScript.FromMonoBehaviour(GetMonoBehaviour(out executionOrder));
                int currentExecutionOrder = MonoImporter.GetExecutionOrder(monoScript);
                if (currentExecutionOrder != executionOrder) MonoImporter.SetExecutionOrder(monoScript, executionOrder);
            }

            solver = serializedObject.FindProperty("solver");
            timeStep = new SerializedContent(serializedObject.FindProperty("timeStep"), new GUIContent("Time Step", "If zero, will update the solver in every LateUpdate(). Use this for chains that are animated. If > 0, will be used as updating frequency so that the solver will reach its target in the same time on all machines."));

            content = FindContent();
            OnEnableVirtual();
        }
Esempio n. 31
0
		public static bool TryGetMonoScript(object obj, out MonoScript script)
		{
			script = null;
			if (obj is MonoBehaviour)
			{
				MonoBehaviour monoBehaviour = (MonoBehaviour)obj;
				script = MonoScript.FromMonoBehaviour(monoBehaviour);
			}
			else
			{
				if (obj is ScriptableObject)
				{
					ScriptableObject scriptableObject = (ScriptableObject)obj;
					script = MonoScript.FromScriptableObject(scriptableObject);
				}
			}
			return script != null;
		}
Esempio n. 32
0
    private string GetClassName(MCP_AI.AgentAI.OPTIONS option,MonoScript ms)
    {
        switch (option)
        {
            case MCP_AI.AgentAI.OPTIONS.FSMAI:
                return typeof(FSM.FSMAI).Name;

            case MCP_AI.AgentAI.OPTIONS.BTAI:
                return typeof(BT.BTAI).Name;

            case MCP_AI.AgentAI.OPTIONS.RandomAI:
                return typeof(RandomAI).Name;
            case MCP_AI.AgentAI.OPTIONS.CustomAI:
                return ms.GetClass().Name;

        }
        return null;
    }
        void OnEnable()
        {
            ProCamera2DEditorHelper.AssignProCamera2D(target as BasePC2D);

			var proCamera2DTriggerBoundaries = (ProCamera2DTriggerBoundaries)target;

            if (proCamera2DTriggerBoundaries.NumericBoundaries == null && proCamera2DTriggerBoundaries.ProCamera2D != null)
            {
                var numericBoundaries = proCamera2DTriggerBoundaries.ProCamera2D.GetComponent<ProCamera2DNumericBoundaries>();
                proCamera2DTriggerBoundaries.NumericBoundaries = numericBoundaries == null ? proCamera2DTriggerBoundaries.ProCamera2D.gameObject.AddComponent<ProCamera2DNumericBoundaries>() : numericBoundaries;
            }

            if (proCamera2DTriggerBoundaries.PositionAndSizeOverrider == null && proCamera2DTriggerBoundaries.ProCamera2D != null)
            {
                var positionAndSizeOverrider = proCamera2DTriggerBoundaries.ProCamera2D.GetComponent<ProCamera2DPositionAndSizeOverrider>();
                proCamera2DTriggerBoundaries.PositionAndSizeOverrider = positionAndSizeOverrider == null ? proCamera2DTriggerBoundaries.ProCamera2D.gameObject.AddComponent<ProCamera2DPositionAndSizeOverrider>() : positionAndSizeOverrider;
                proCamera2DTriggerBoundaries.PositionAndSizeOverrider.hideFlags = HideFlags.HideInInspector;
            }

            _script = MonoScript.FromMonoBehaviour(proCamera2DTriggerBoundaries);
        }
        public void OnGUI()
        {
            //FsmEditorStyles.Init();

            // set style ot use rich text.
            if (labelStyle==null)
            {
                labelStyle = GUI.skin.GetStyle("Label");
                labelStyle.richText = true;
            }

            // unfocus invisible field
            GUI.SetNextControlName(_unfocusControlName);
            GUI.TextField(new Rect(0,-100,100,20),"");

            //	FsmEditorGUILayout.ToolWindowLargeTitle(this, "Ecosystem Publisher");

            _scriptTarget = EditorGUILayout.ObjectField("Script Target",_scriptTarget, typeof(MonoScript), false) as MonoScript;

            if (_scriptTarget!=null  && GUILayout.Button("Create"))
            {
                CreateResource();
            }

            sniptId = GUILayout.TextField(sniptId);

            if (! string.IsNullOrEmpty(sniptId))
            {
                if (GUILayout.Button("Delete"))
                {
                    DeleteResource(sniptId);
                }
            }

            if (wwwSniptRESTCall!=null)
            {
                GUILayout.Label("...");
            }
        }
Esempio n. 35
0
        public static AssetDeleteResult OnWillDeleteAsset(string path, RemoveAssetOptions options)
        {
            UnityEngine.Object obj = AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(path);

            if (!(obj is UnityEditor.MonoScript))
            {
                return(AssetDeleteResult.DidNotDelete);
            }

            UnityEditor.MonoScript script     = obj as UnityEditor.MonoScript;
            System.Type            scriptType = script.GetClass();

            if (scriptType != typeof(Node) && !scriptType.IsSubclassOf(typeof(Node)))
            {
                return(AssetDeleteResult.DidNotDelete);
            }

            //Find ScriptableObjects using this script
            string[] guids = AssetDatabase.FindAssets("t:" + scriptType);
            for (int i = 0; i < guids.Length; i++)
            {
                string   assetpath = AssetDatabase.GUIDToAssetPath(guids[i]);
                Object[] objs      = AssetDatabase.LoadAllAssetRepresentationsAtPath(assetpath);
                for (int k = 0; k < objs.Length; k++)
                {
                    Node node = objs[k] as Node;
                    if (node.GetType() == scriptType)
                    {
                        if (node != null && node.graph != null)
                        {
                            Debug.LogWarning(node.name + " of " + node.graph + " depended on deleted script and has been removed automatically.", node.graph);
                            node.graph.RemoveNode(node);
                        }
                    }
                }
            }
            return(AssetDeleteResult.DidNotDelete);
        }
    private static void ProcessDependencies()
    {
        ResourceSingletonBuilder.BuildResourceSingletonsIfDirty();

        var types = new string[] { ".cs", ".js" };

        var allScriptPaths = Directory.GetFiles("Assets", "*.*", SearchOption.AllDirectories)
                             .Where(s => types.Any(x => s.EndsWith(x, System.StringComparison.CurrentCultureIgnoreCase)))
                             .ToArray();

        for (int i = 0; i < allScriptPaths.Length; ++i)
        {
            UnityEditor.MonoScript script = UnityEditor.AssetDatabase.LoadAssetAtPath(allScriptPaths[i], typeof(UnityEditor.MonoScript)) as UnityEditor.MonoScript;
            if (!script || script.GetClass() == null)
            {
                continue;
            }
            if (!typeof(Component).IsAssignableFrom(script.GetClass()))
            {
                continue;
            }

            var type       = script.GetClass();
            var attributes = (ComponentDependencyAttribute[])type.GetCustomAttributes(typeof(ComponentDependencyAttribute), true);
            if (attributes.Length == 0)
            {
                continue;
            }

            var dependencies = attributes
                               .Where(x => x != null)
                               .SelectMany(x => x.GetComponentDependencies())
                               .ToArray();

            ProcessAll_SetDependencies(type, dependencies);
        }
    }
Esempio n. 37
0
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        if (Application.isPlaying)
            return;

        MCP_AI.Environment myTarget = (MCP_AI.Environment)target;
        myTarget.AttackerControllerType =(MCP_AI.AgentAI.OPTIONS)EditorGUILayout.EnumPopup("Attacker Controller Type",myTarget.AttackerControllerType);
        if (myTarget.AttackerControllerType == MCP_AI.AgentAI.OPTIONS.CustomAI)
        {
            aS = EditorGUILayout.ObjectField("Controller Class", aS, typeof(MonoScript), false) as MonoScript;
            if (aS != null && aS.GetClass().BaseType.Equals(typeof(MCP_AI.AIController)))
            {
                myTarget.AttackController = aS.GetClass().Name;
            }
        }
        else
        {
            myTarget.AttackController = GetClassName(myTarget.AttackerControllerType, null);
        }

        myTarget.DefenderControllerType = (MCP_AI.AgentAI.OPTIONS)EditorGUILayout.EnumPopup("Defender Controller Type", myTarget.DefenderControllerType);
        if (myTarget.DefenderControllerType == MCP_AI.AgentAI.OPTIONS.CustomAI)
        {
            dS = EditorGUILayout.ObjectField("Controller Class", dS, typeof(MonoScript), false) as MonoScript;
            if (dS != null && dS.GetClass().BaseType.Equals(typeof(MCP_AI.AIController)))
            {

                myTarget.DefendController = dS.GetClass().Name;
            }
        }
        else
        {
            myTarget.DefendController = GetClassName(myTarget.DefenderControllerType, null);
        }
    }
 private void Init(MonoScript script)
 {
   this.m_Initialized = true;
   this.m_ScriptClass = script.GetClass();
   this.m_NetworkChannelLabel = new GUIContent("Network Channel", "QoS channel used for updates. Use the [NetworkSettings] class attribute to change this.");
   this.m_NetworkSendIntervalLabel = new GUIContent("Network Send Interval", "Maximum update rate in seconds. Use the [NetworkSettings] class attribute to change this, or implement GetNetworkSendInterval");
   foreach (System.Reflection.FieldInfo field in this.m_ScriptClass.GetFields(BindingFlags.Instance | BindingFlags.Public))
   {
     if (((Attribute[]) field.GetCustomAttributes(typeof (SyncVarAttribute), true)).Length > 0)
       this.m_SyncVarNames.Add(field.Name);
   }
   MethodInfo method = script.GetClass().GetMethod("OnSerialize");
   if (method != null && method.DeclaringType != typeof (NetworkBehaviour))
     this.m_HasOnSerialize = true;
   int length = 0;
   foreach (System.Reflection.FieldInfo field in this.serializedObject.targetObject.GetType().GetFields())
   {
     if (field.FieldType.BaseType != null && field.FieldType.BaseType.Name.Contains("SyncList"))
       ++length;
   }
   if (length <= 0)
     return;
   this.m_ShowSyncLists = new bool[length];
 }
 private static bool IsDefaultTimeElement(MonoScript element)
 {
     return(element.name == string.Empty);
 }
Esempio n. 40
0
    /// <summary>
    /// Does this script have fixed order?
    /// </summary>
    static bool HasFixedOrder(UnityEditor.MonoScript script)
    {
        int output = 0;

        return(GetFixedOrder(script, out output));
    }
Esempio n. 41
0
 /// <summary>
 /// Does this script have dependencies?
 /// </summary>
 static bool HasDependencies(UnityEditor.MonoScript script)
 {
     return(GetScriptDependencies(script).Length > 0);
 }
Esempio n. 42
0
 public static extern int GetExecutionOrder(MonoScript script);
 internal static extern void CopyMonoScriptIconToImporters([NotNull("NullExceptionObject")] MonoScript script);
        public override void OnInspectorGUI()
        {
            if (m_Edited)
            {
                UpdateOrder(m_Edited);
                m_Edited = null;
            }

            EditorGUILayout.BeginVertical(EditorStyles.inspectorFullWidthMargins);
            {
                GUILayout.Label(Content.helpText, EditorStyles.helpBox);

                EditorGUILayout.Space();

                // Vertical that contains box and the toolbar below it
                Rect listRect = EditorGUILayout.BeginVertical();
                {
                    int        dropFieldId = EditorGUIUtility.GetControlID(s_DropFieldHash, FocusType.Passive, listRect);
                    MonoScript dropped     = EditorGUI.DoDropField(listRect, dropFieldId, typeof(MonoScript), MonoScriptValidatorCallback, false, Styles.dropField) as MonoScript;
                    if (dropped)
                    {
                        AddScriptToCustomOrder(dropped);
                    }

                    // Vertical that is used as a border around the scrollview
                    EditorGUILayout.BeginVertical(Styles.boxBackground);
                    {
                        // The scrollview itself
                        m_Scroll = EditorGUILayout.BeginVerticalScrollView(m_Scroll);
                        {
                            // List
                            Rect r       = GUILayoutUtility.GetRect(10, kListElementHeight * m_CustomTimeScripts.Count, GUILayout.ExpandWidth(true));
                            int  changed = DragReorderGUI.DragReorder(r, kListElementHeight, m_CustomTimeScripts, DrawElement);
                            if (changed >= 0)
                            {
                                // Give dragged item value in between neighbors
                                SetExecutionOrderAtIndexAccordingToNeighbors(changed, 0);
                                // Update neighbors if needed
                                UpdateOrder(m_CustomTimeScripts[changed]);
                                // Neighbors may have been moved so there's more space around dragged item,
                                // so set order again to get possible rounding benefits
                                SetExecutionOrderAtIndexAccordingToNeighbors(changed, 0);
                            }
                        } EditorGUILayout.EndScrollView();
                    } EditorGUILayout.EndVertical();

                    // The toolbar below the box
                    GUILayout.BeginHorizontal(Styles.toolbar);
                    {
                        GUILayout.FlexibleSpace();
                        Rect       r2;
                        GUIContent content = Content.iconToolbarPlus;
                        r2 = GUILayoutUtility.GetRect(content, Styles.toolbarDropDown);
                        if (EditorGUI.DropdownButton(r2, content, FocusType.Passive, Styles.toolbarDropDown))
                        {
                            ShowScriptPopup(r2);
                        }
                    } GUILayout.EndHorizontal();
                } GUILayout.EndVertical();

                ApplyRevertGUI();
            } GUILayout.EndVertical();

            GUILayout.FlexibleSpace();
        }
Esempio n. 45
0
        private static bool CheckIfScriptLoaded(SerializedProperty scriptProperty)
        {
            MonoScript targetScript = scriptProperty?.objectReferenceValue as MonoScript;

            return(targetScript != null && targetScript.GetScriptTypeWasJustCreatedFromComponentMenu());
        }
 private static bool IsValidScript(MonoScript script)
 {
     return(!((UnityEngine.Object)script == (UnityEngine.Object)null) && script.GetClass() != null && ((typeof(MonoBehaviour).IsAssignableFrom(script.GetClass()) || typeof(ScriptableObject).IsAssignableFrom(script.GetClass())) && AssetDatabase.GetAssetPath((UnityEngine.Object)script).IndexOf("Assets/") == 0));
 }
Esempio n. 47
0
 internal static extern void CopyMonoScriptIconToImporters(MonoScript script);
 private static extern void Init(MonoScript self, string scriptContents, string className, string nameSpace, string assemblyName, bool isEditorScript);
 private static extern void Init_Internal([Writable] MonoScript script);
Esempio n. 50
0
    static void ProcessAll()
    {
        var types       = new string[] { ".cs", ".js" };
        var fixedOrders = new Dictionary <UnityEditor.MonoScript, int>();

        var allScriptPaths = Directory.GetFiles("Assets", "*.*", SearchOption.AllDirectories)
                             .Where(s => types.Any(x => s.EndsWith(x, System.StringComparison.CurrentCultureIgnoreCase)))
                             .ToArray();

        var allScripts = new List <UnityEditor.MonoScript>();

        for (int i = 0; i < allScriptPaths.Length; ++i)
        {
            UnityEditor.MonoScript script = UnityEditor.AssetDatabase.LoadAssetAtPath(allScriptPaths[i], typeof(UnityEditor.MonoScript)) as UnityEditor.MonoScript;
            if (!script || script.GetClass() == null)
            {
                continue;
            }
            int newOrder = 0;
            if (GetFixedOrder(script, out newOrder))
            {
                fixedOrders[script] = newOrder;
            }
            allScripts.Add(script);
        }

        var scriptOrders = new Dictionary <UnityEditor.MonoScript, int>();
        var sortedDeps   = SortDependencies(allScripts.ToArray());

        for (int i = 0; i < sortedDeps.Count; ++i)
        {
            bool hasFixedOrderItem = false;

            //
            // find out the starting priority for this island
            var currentIsland = sortedDeps[i];

            var newDepOrder = -currentIsland.Length;
            for (int j = 0; j < currentIsland.Length; ++j)
            {
                var script      = currentIsland[j].script;
                int scriptOrder = 0;
                if (fixedOrders.TryGetValue(script, out scriptOrder))
                {
                    // -j due to sorted items before it
                    newDepOrder       = Mathf.Min(scriptOrder - j, newDepOrder);
                    hasFixedOrderItem = true;
                }
            }

            //
            // Don't edit execution order unless there's a fixed order or a dependency
            // This allows the script exection order UI to work normally for these cases
            // instead of forcing them to exection order 0
            if (currentIsland.Length == 1 && !hasFixedOrderItem)
            {
                continue;
            }

#if LOG_DEBUG
            Debug.Log("ScriptExectionOrder: Island:" + i + " starts at " + newDepOrder
                      + " Scripts:" + string.Join(", ", currentIsland
                                                  .Select(x => (fixedOrders.ContainsKey(x.script)
                        ? (x.script.name + "[" + fixedOrders[x.script] + "]")
                        : x.script.name) + "(" + x.isLeaf + ")")
                                                  .ToArray()));
#endif


            //
            // apply priorities in order
            for (int j = 0; j < currentIsland.Length; ++j)
            {
                int scriptFixedOrder = 0;
                var script           = currentIsland[j].script;
                var isLeaf           = currentIsland[j].isLeaf;
                if (fixedOrders.TryGetValue(script, out scriptFixedOrder))
                {
                    newDepOrder = Mathf.Max(scriptFixedOrder, newDepOrder);
                    if (newDepOrder != scriptFixedOrder)
                    {
                        Debug.LogWarning("ScriptExectionOrder: " + script.name + " has fixed exection order " + scriptFixedOrder + " but due to ScriptDependency sorting is now at order " + newDepOrder);
                    }
                    fixedOrders.Remove(script);
                }
                else if (fixedOrders.Count == 0)
                {
                    newDepOrder = isLeaf && !currentIsland.Skip(j + 1).Any(x => x.isLeaf)
                        ? Mathf.Max(0, newDepOrder)
                        : Mathf.Max(-currentIsland.Length, newDepOrder);
                }

                scriptOrders[script] = newDepOrder;

                // Leaves have no dependencies so the next behaviour can share the same execution order as a leaf
                //
                if (!isLeaf || (isLeaf && !hasFixedOrderItem))
                {
                    ++newDepOrder;
                }
            }
        }

        foreach (var i in scriptOrders)
        {
            var script       = i.Key;
            var order        = i.Value;
            var currentOrder = UnityEditor.MonoImporter.GetExecutionOrder(script);
            if (order != currentOrder)
            {
                UnityEditor.MonoImporter.SetExecutionOrder(script, order);
            }
        }
    }
 public static extern int GetExecutionOrder([NotNull("NullExceptionObject")] MonoScript script);
Esempio n. 52
0
 public static extern void SetExecutionOrder(MonoScript script, int order);
        void OnEnable()
        {
            ProCamera2DEditorHelper.AssignProCamera2D(target as BasePC2D);

            _script = MonoScript.FromMonoBehaviour((ProCamera2DCameraWindow)target);
        }
Esempio n. 54
0
        public override void OnInspectorGUI()
        {
            if (!m_Initialized)
            {
                serializedObject.Update();
                SerializedProperty scriptProperty = serializedObject.FindProperty("m_Script");
                if (scriptProperty == null)
                {
                    return;
                }

                MonoScript targetScript = scriptProperty.objectReferenceValue as MonoScript;
                Init(targetScript);
            }

            EditorGUI.BeginChangeCheck();
            serializedObject.Update();

            // Loop through properties and create one field (including children) for each top level property.
            SerializedProperty property = serializedObject.GetIterator();
            bool expanded = true;

            while (property.NextVisible(expanded))
            {
                bool isSyncVar = m_SyncVarNames.Contains(property.name);
                if (property.propertyType == SerializedPropertyType.ObjectReference)
                {
                    if (property.name == "m_Script")
                    {
                        if (hideScriptField)
                        {
                            continue;
                        }

                        EditorGUI.BeginDisabledGroup(true);
                    }

                    EditorGUILayout.PropertyField(property, true);

                    if (isSyncVar)
                    {
                        GUILayout.Label(m_SyncVarIndicatorContent, EditorStyles.miniLabel, GUILayout.Width(EditorStyles.miniLabel.CalcSize(m_SyncVarIndicatorContent).x));
                    }

                    if (property.name == "m_Script")
                    {
                        EditorGUI.EndDisabledGroup();
                    }
                }
                else
                {
                    EditorGUILayout.BeginHorizontal();

                    EditorGUILayout.PropertyField(property, true);

                    if (isSyncVar)
                    {
                        GUILayout.Label(m_SyncVarIndicatorContent, EditorStyles.miniLabel, GUILayout.Width(EditorStyles.miniLabel.CalcSize(m_SyncVarIndicatorContent).x));
                    }

                    EditorGUILayout.EndHorizontal();
                }
                expanded = false;
            }
            serializedObject.ApplyModifiedProperties();
            EditorGUI.EndChangeCheck();

            // find SyncLists.. they are not properties.
            int syncListIndex = 0;

            foreach (var field in serializedObject.targetObject.GetType().GetFields())
            {
                if (field.FieldType.BaseType != null && field.FieldType.BaseType.Name.Contains("SyncList"))
                {
                    m_ShowSyncLists[syncListIndex] = EditorGUILayout.Foldout(m_ShowSyncLists[syncListIndex], "SyncList " + field.Name + "  [" + field.FieldType.Name + "]");
                    if (m_ShowSyncLists[syncListIndex])
                    {
                        EditorGUI.indentLevel += 1;
                        var synclist = field.GetValue(serializedObject.targetObject) as IEnumerable;
                        if (synclist != null)
                        {
                            int index = 0;
                            var enu   = synclist.GetEnumerator();
                            while (enu.MoveNext())
                            {
                                if (enu.Current != null)
                                {
                                    EditorGUILayout.LabelField("Item:" + index, enu.Current.ToString());
                                }
                                index += 1;
                            }
                        }
                        EditorGUI.indentLevel -= 1;
                    }
                    syncListIndex += 1;
                }
            }

            if (m_HasOnSerialize)
            {
                var beh = target as NetworkBehaviour;
                if (beh != null)
                {
                    EditorGUILayout.LabelField(m_NetworkChannelLabel, new GUIContent(beh.GetNetworkChannel().ToString()));
                    EditorGUILayout.LabelField(m_NetworkSendIntervalLabel, new GUIContent(beh.GetNetworkSendInterval().ToString()));
                }
            }
        }
        // *undocumented*
        private static string GetObjectTypeName(Object o)
        {
            if (o == null)
            {
                return("Nothing Selected");
            }

            if (o is GameObject)
            {
                return(o.name);
            }

            // Show "Tags & Layers" instead of "TagManager"
            if (o is TagManager)
            {
                return("Tags & Layers");
            }

            if (o is Component)
            {
                var behaviour = o as MonoBehaviour;
                if (behaviour)
                {
                    var scriptClassName = behaviour.GetScriptClassName();
                    if (scriptClassName == "InvalidStateMachineBehaviour")
                    {
                        return(behaviour.name + " (Script)");
                    }
                    return(scriptClassName + " (Script)");
                }

                var meshfilter = o as MeshFilter;
                if (meshfilter)
                {
                    var mesh = meshfilter.sharedMesh;
                    return((mesh ? mesh.name : "[none]") + " (MeshFilter)");
                }

                return(o.GetType().Name);
            }

            // Importers don't have names. Just show the type without parenthesis (like we do for components).
            if (o is AssetImporter)
            {
                var monoImporter = o as MonoImporter;
                if (monoImporter)
                {
                    var script = monoImporter.GetScript();
                    return("Default References (" + (script ? script.name : string.Empty) + ")");
                }

                if (NativeClassExtensionUtilities.ExtendsANativeType(o))
                {
                    var script = MonoScript.FromScriptedObject(o);
                    if (script != null)
                    {
                        return(script.GetClass().Name + " (Script)");
                    }
                }

                return(o.GetType().Name);
            }

            return(o.name + " (" + o.GetType().Name + ")");
        }
		public void MonoScriptIconChanged(MonoScript monoScript)
		{
			if (monoScript == null)
			{
				return;
			}
			bool flag = true;
			foreach (MonoScript current in this.m_MonoScriptIconsChanged)
			{
				if (current.GetInstanceID() == monoScript.GetInstanceID())
				{
					flag = false;
				}
			}
			if (flag)
			{
				this.m_MonoScriptIconsChanged.Add(monoScript);
			}
		}
        void OnEnable()
        {
            ProCamera2DEditorHelper.AssignProCamera2D(target as BasePC2D);

            _script = MonoScript.FromMonoBehaviour((ProCamera2DTriggerInfluence)target);
        }
Esempio n. 58
0
        private static string GetObjectTypeName(UnityEngine.Object o)
        {
            string result;

            if (o == null)
            {
                result = "Nothing Selected";
            }
            else if (o is GameObject)
            {
                result = o.name;
            }
            else if (o is TagManager)
            {
                result = "Tags & Layers";
            }
            else if (o is Component)
            {
                MonoBehaviour monoBehaviour = o as MonoBehaviour;
                if (monoBehaviour)
                {
                    string scriptClassName = monoBehaviour.GetScriptClassName();
                    if (scriptClassName == "InvalidStateMachineBehaviour")
                    {
                        result = monoBehaviour.name + " (Script)";
                    }
                    else
                    {
                        result = scriptClassName + " (Script)";
                    }
                }
                else
                {
                    MeshFilter meshFilter = o as MeshFilter;
                    if (meshFilter)
                    {
                        Mesh sharedMesh = meshFilter.sharedMesh;
                        result = ((!sharedMesh) ? "[none]" : sharedMesh.name) + " (MeshFilter)";
                    }
                    else
                    {
                        result = o.GetType().Name;
                    }
                }
            }
            else if (o is AssetImporter)
            {
                MonoImporter monoImporter = o as MonoImporter;
                if (monoImporter)
                {
                    MonoScript script = monoImporter.GetScript();
                    result = "Default References (" + ((!script) ? string.Empty : script.name) + ")";
                }
                else
                {
                    SubstanceImporter substanceImporter = o as SubstanceImporter;
                    if (substanceImporter)
                    {
                        MonoScript substanceArchive = substanceImporter.GetSubstanceArchive();
                        if (substanceArchive)
                        {
                            result = substanceArchive.name + " (Substance Archive)";
                            return(result);
                        }
                    }
                    result = o.GetType().Name;
                }
            }
            else
            {
                result = o.name + " (" + o.GetType().Name + ")";
            }
            return(result);
        }
Esempio n. 59
0
 private static extern void Init([NotNull("NullExceptionObject")] MonoScript self, string className, string nameSpace, string assemblyName, bool isEditorScript);
Esempio n. 60
-27
    void OnGUI()
    {
        GUILayout.BeginVertical();
        GUILayout.BeginHorizontal();
        var lNewScriptToSearch = (MonoScript)EditorGUILayout.ObjectField(scriptToSearch, typeof(MonoScript));
        scriptNameToSearch = EditorGUILayout.TextField(scriptNameToSearch);
        if (scriptToSearch!=lNewScriptToSearch)
        {
            scriptToSearch = lNewScriptToSearch;
            scriptNameToSearch = scriptToSearch.name;
        }

        if (GUILayout.Button("search", GUILayout.ExpandWidth(false))
            && scriptNameToSearch.Length>0)
        {
            //var lType = System.Type.GetType(lScriptName);
            List<GameObject> lResult = new List<GameObject>();
            var lAllObject = (GameObject[])Resources.FindObjectsOfTypeAll(typeof(GameObject));
            foreach (var lObject in lAllObject)
            {
                if (lObject.GetComponent(scriptNameToSearch))
                    lResult.Add(lObject);
            }
            result = lResult.ToArray();
        }
        GUILayout.EndHorizontal();
        scrollPos = GUILayout.BeginScrollView(scrollPos);
        foreach (var lObject in result)
        {
            EditorGUILayout.ObjectField(lObject, typeof(GameObject));
        }
        GUILayout.EndScrollView();
        GUILayout.EndVertical();
    }