Beispiel #1
0
        static void UpdateSerializedProgramAssets(List <UdonBehaviour> udonBehaviours)
        {
            if (_serializedAssetField == null)
            {
                _serializedAssetField = typeof(UdonBehaviour).GetField("serializedProgramAsset", BindingFlags.NonPublic | BindingFlags.Instance);
            }

            foreach (UdonBehaviour behaviour in udonBehaviours)
            {
                UdonSharpProgramAsset programAsset = behaviour.programSource as UdonSharpProgramAsset;
                if (programAsset == null)
                {
                    continue;
                }

                AbstractSerializedUdonProgramAsset serializedProgramAsset = _serializedAssetField.GetValue(behaviour) as AbstractSerializedUdonProgramAsset;

                if (serializedProgramAsset == null ||
                    serializedProgramAsset != programAsset.SerializedProgramAsset)
                {
                    SerializedObject   serializedBehaviour       = new SerializedObject(behaviour);
                    SerializedProperty serializedProgramProperty = serializedBehaviour.FindProperty("serializedProgramAsset");
                    serializedProgramProperty.objectReferenceValue = programAsset.SerializedProgramAsset;
                    serializedBehaviour.ApplyModifiedPropertiesWithoutUndo();
                }
            }
        }
        public bool OnBuildRequested(VRCSDKRequestedBuildType requestedBuildType)
        {
            if (requestedBuildType == VRCSDKRequestedBuildType.Avatar)
            {
                return(true);
            }

            if (UdonSharpSettings.GetSettings().disableUploadCompile)
            {
                return(true);
            }

            UdonSharpCompilerV1.CompileSync(new UdonSharpCompileOptions()
            {
                IsEditorBuild = false
            });
            UdonSharpEditorCache.SaveAllCache();

            if (UdonSharpProgramAsset.AnyUdonSharpScriptHasError())
            {
                UdonSharpUtils.LogError("Failed to compile UdonSharp scripts for build, check error log for details.");
                UdonSharpUtils.ShowEditorNotification("Failed to compile UdonSharp scripts for build, check error log for details.");
                return(false);
            }

            if (UdonSharpEditorManager.RunAllUpgrades())
            {
                UdonSharpUtils.LogWarning(UdonSharpEditorManager.UPGRADE_MESSAGE);
                return(false);
            }

            return(true);
        }
Beispiel #3
0
        public static UdonSharpBehaviour GetUdonBehaviour(Type udonSharpType, GameObject gameObject)
        {
            UdonBehaviour adapter = gameObject.GetComponents <UdonBehaviour>().Where(udon => udon.programSource != null && udon.programSource.GetType() == typeof(UdonSharpProgramAsset) &&
                                                                                     (udon.programSource as UdonSharpProgramAsset).sourceCsScript.GetClass() == udonSharpType).FirstOrDefault();

            if (adapter != null)
            {
                return(UdonSharpEditorUtility.GetProxyBehaviour(adapter));
            }
            adapter = gameObject.GetComponents <UdonBehaviour>().Where(udon => udon.programSource == null).FirstOrDefault();
            if (adapter == null)
            {
                adapter = gameObject.AddComponent <UdonBehaviour>();
            }
            string[] guids = AssetDatabase.FindAssets(udonSharpType.Name + " t:UdonSharpProgramAsset");
            if (guids.Length > 0)
            {
                UdonSharpProgramAsset udonProgram = (UdonSharpProgramAsset)AssetDatabase.LoadMainAssetAtPath(AssetDatabase.GUIDToAssetPath(guids[0]));
                if (udonProgram != null && udonProgram.GetSerializedUdonProgramAsset() != null)
                {
                    adapter.AssignProgramAndVariables(udonProgram.GetSerializedUdonProgramAsset(), new VRC.Udon.Common.UdonVariableTable());
                    adapter.programSource = udonProgram;
                    UdonSharpEditorUtility.GetProxyBehaviour(adapter);
                }
            }
            return(UdonSharpEditorUtility.GetProxyBehaviour(adapter));
        }
        private static void HandleScriptModifications()
        {
            UdonSharpSettings settings = UdonSharpSettings.GetSettings();

            if (!settings.autoCompileOnModify)
            {
                _modifiedScripts.Clear();
                return;
            }

            if (settings.waitForFocus && !UnityEditorInternal.InternalEditorUtility.isApplicationActive)
            {
                return;
            }

            if (_modifiedScripts.Count == 0)
            {
                return;
            }

            try
            {
                UdonSharpProgramAsset.CompileAllCsPrograms();
            }
            finally
            {
                _modifiedScripts.Clear();
            }
        }
Beispiel #5
0
        public static UdonSharpBehaviour AddUdonSharpComponent(this GameObject gameObject, System.Type type)
        {
            if (type == typeof(UdonSharpBehaviour))
            {
                throw new System.ArgumentException("Cannot add components of type 'UdonSharpBehaviour', you can only add subclasses of this type");
            }

            if (!typeof(UdonSharpBehaviour).IsAssignableFrom(type))
            {
                throw new System.ArgumentException("Type for AddUdonSharpComponent must be a subclass of UdonSharpBehaviour");
            }

            UdonBehaviour udonBehaviour = gameObject.AddComponent <UdonBehaviour>();

            UdonSharpProgramAsset programAsset = UdonSharpProgramAsset.GetProgramAssetForClass(type);

            udonBehaviour.programSource = programAsset;
            udonBehaviour.AllowCollisionOwnershipTransfer = false;

            SerializedObject   componentAsset = new SerializedObject(udonBehaviour);
            SerializedProperty serializedProgramAssetProperty = componentAsset.FindProperty("serializedProgramAsset");

            serializedProgramAssetProperty.objectReferenceValue = programAsset.SerializedProgramAsset;
            componentAsset.ApplyModifiedPropertiesWithoutUndo();

            UdonSharpBehaviour proxyComponent = UdonSharpEditorUtility.GetProxyBehaviour(udonBehaviour);

            if (EditorApplication.isPlaying)
            {
                udonBehaviour.InitializeUdonContent();
            }

            return(proxyComponent);
        }
Beispiel #6
0
        public override void OnInspectorGUI()
        {
            switch (errorState)
            {
            case BehaviourInspectorErrorState.Success:
                #if UDONSHARP_DEBUG
                EditorGUILayout.HelpBox("UDONSHARP_DEBUG is defined; backing UdonBehaviour is shown", MessageType.Info);
                #else
                EditorGUILayout.HelpBox("Something probably went wrong, you should not be able to see the underlying UdonBehaviour for UdonSharpBehaviours", MessageType.Warning);
                #endif

                EditorGUI.BeginDisabledGroup(true);
                EditorGUILayout.ObjectField("Linked U# Behaviour", UdonSharpEditorUtility.GetProxyBehaviour((UdonBehaviour)target), typeof(UdonSharpBehaviour), true);
                EditorGUILayout.ObjectField("Program Source", ((UdonBehaviour)target).programSource, typeof(AbstractUdonProgramSource), false);
                EditorGUI.EndDisabledGroup();
                break;

            case BehaviourInspectorErrorState.PrefabNeedsUpgrade:
                EditorGUILayout.HelpBox("U# behaviour needs upgrade on prefab, make sure you didn't have any issues during importing the prefab.", MessageType.Error);
                break;

            case BehaviourInspectorErrorState.NoValidUSharpProgram:
                EditorGUILayout.HelpBox("U# behaviour is not pointing to a valid U# program asset.", MessageType.Error);

                UdonSharpProgramAsset programAsset = ((UdonBehaviour)target).programSource as UdonSharpProgramAsset;

                if (programAsset && programAsset.sourceCsScript == null)
                {
                    UdonSharpGUI.DrawCreateScriptButton(programAsset);
                }
                break;
            }
        }
Beispiel #7
0
        private static (bool, List <Attribute>) ShouldRunValidator(UdonBehaviour currentBehaviour, string symbol, Type variableType, object @return)
        {
            if (@return == null || variableType != typeof(UdonBehaviour))
            {
                return(false, null);
            }

            if (!UdonSharpEditorUtility.IsUdonSharpBehaviour(currentBehaviour))
            {
                return(false, null);
            }

            if (UdonSharpProgramAsset.GetBehaviourClass((UdonBehaviour)@return) != typeof(EventListener))
            {
                return(false, null);
            }

            var proxyBehaviour = UdonSharpEditorUtility.GetProxyBehaviour(currentBehaviour);
            var variable       = proxyBehaviour.GetType().GetField(symbol, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

            if (variable == null)
            {
                return(false, null);
            }

            var attrs = Validators.Select(validator => variable.GetCustomAttribute(validator)).Where(attr => attr != null).ToList();

            return(attrs.Count == 0 ? (false, null) : (true, attrs));
        }
        public static UdonAssemblyProgramAsset UdonSharpProgramToAssemblyProgram(UdonSharpProgramAsset udonSharpProgramAsset, string savePath)
        {
            if (EditorApplication.isPlaying)
            {
                throw new System.NotSupportedException("USharpEditorUtility.UdonSharpProgramToAssemblyProgram() cannot be called in play mode");
            }

            UdonAssemblyProgramAsset newProgramAsset = ScriptableObject.CreateInstance <UdonAssemblyProgramAsset>();

            AssetDatabase.CreateAsset(newProgramAsset, savePath);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);

            newProgramAsset = AssetDatabase.LoadAssetAtPath <UdonAssemblyProgramAsset>(savePath);

            udonSharpProgramAsset.CompileCsProgram();

            FieldInfo assemblyField = typeof(UdonAssemblyProgramAsset).GetField("udonAssembly", BindingFlags.NonPublic | BindingFlags.Instance);

            assemblyField.SetValue(newProgramAsset, UdonSharpEditorCache.Instance.GetUASMStr(udonSharpProgramAsset));

            MethodInfo assembleMethod = typeof(UdonAssemblyProgramAsset).GetMethod("AssembleProgram", BindingFlags.NonPublic | BindingFlags.Instance);

            assembleMethod.Invoke(newProgramAsset, new object[] { });

            IUdonProgram uSharpProgram         = udonSharpProgramAsset.GetRealProgram();
            FieldInfo    assemblyProgramGetter = typeof(UdonProgramAsset).GetField("program", BindingFlags.NonPublic | BindingFlags.Instance);
            IUdonProgram assemblyProgram       = (IUdonProgram)assemblyProgramGetter.GetValue(newProgramAsset);

            if (uSharpProgram == null || assemblyProgram == null)
            {
                return(null);
            }

            string[] symbols = uSharpProgram.SymbolTable.GetSymbols();

            foreach (string symbol in symbols)
            {
                uint        symbolAddress = uSharpProgram.SymbolTable.GetAddressFromSymbol(symbol);
                System.Type symbolType    = uSharpProgram.Heap.GetHeapVariableType(symbolAddress);
                object      symbolValue   = uSharpProgram.Heap.GetHeapVariable(symbolAddress);

                assemblyProgram.Heap.SetHeapVariable(assemblyProgram.SymbolTable.GetAddressFromSymbol(symbol), symbolValue, symbolType);
            }

            EditorUtility.SetDirty(newProgramAsset);

            newProgramAsset.SerializedProgramAsset.StoreProgram(assemblyProgram);
            EditorUtility.SetDirty(newProgramAsset.SerializedProgramAsset);

            AssetDatabase.SaveAssets();

            // This doesn't work unfortunately due to how Udon tries to locate the serialized asset when importing an assembly
            //string serializedAssetPath = $"{Path.GetDirectoryName(savePath)}/{Path.GetFileNameWithoutExtension(savePath)}_serialized.asset";

            //AssetDatabase.MoveAsset(AssetDatabase.GetAssetPath(newProgramAsset.SerializedProgramAsset), serializedAssetPath);
            //AssetDatabase.SaveAssets();

            return(newProgramAsset);
        }
        public override void OnInspectorGUI()
        {
            //base.OnInspectorGUI();

            if (!UdonSharpEditorUtility.IsProxyBehaviour(body))
            {
                UdonSharpGUI.DrawConvertToUdonBehaviourButton(body);
                return;
            }

            serializedObject.Update();

            T23_EditorUtility.ShowTitle("Option");
            GUILayout.Box("CommonBuffer", T23_EditorUtility.HeadlineStyle());

            UdonSharpProgramAsset programAsset = UdonSharpEditorUtility.GetUdonSharpProgramAsset((UdonSharpBehaviour)target);

            UdonSharpGUI.DrawCompileErrorTextArea(programAsset);

            if (GUILayout.Button("Set Broadcasts"))
            {
                body.broadcasts = T23_EditorUtility.TakeCommonBuffersRelate(body);
            }
            if (GUILayout.Button("Join Empty Broadcasts"))
            {
                T23_EditorUtility.JoinAllBufferingBroadcasts(body);
            }
            prop = serializedObject.FindProperty("autoJoin");
            EditorGUILayout.PropertyField(prop);

            prop = serializedObject.FindProperty("broadcasts");
            EditorGUILayout.PropertyField(prop);

            serializedObject.ApplyModifiedProperties();
        }
Beispiel #10
0
    private ComponentSet AddUdonComponent(UdonSharpProgramAsset program, List <string> titleArray)
    {
        string title = ConfirmTitle(program.GetClass().Name.Replace("T23_", ""), titleArray);

        Type      t23Type      = program.GetClass();
        Component newComponent = gameObject.AddComponent(t23Type);

        FieldInfo groupField = t23Type.GetField("groupID");

        if (groupField != null)
        {
            groupField.SetValue(newComponent, groupID);
        }

        FieldInfo titleField = t23Type.GetField("title");

        if (titleField != null)
        {
            titleField.SetValue(newComponent, title);
        }

        UdonSharpBehaviour[] usharpArray = { (UdonSharpBehaviour)newComponent };
        UdonBehaviour[]      udon        = UdonSharpEditorUtility.ConvertToUdonBehaviours(usharpArray);

        ComponentSet res = new ComponentSet();

        res.title     = title;
        res.component = udon[0];

        return(res);
    }
        public static void DeleteProgramAsset(UdonSharpProgramAsset programAsset)
        {
            if (programAsset == null)
            {
                return;
            }

            AbstractSerializedUdonProgramAsset serializedAsset = programAsset.GetSerializedUdonProgramAsset();

            if (serializedAsset != null)
            {
                string assetPath = AssetDatabase.GetAssetPath(serializedAsset);
                serializedAsset = AssetDatabase.LoadAssetAtPath <AbstractSerializedUdonProgramAsset>(assetPath);

                if (serializedAsset != null)
                {
                    AssetDatabase.DeleteAsset(assetPath);
                }
            }

            string programAssetPath = AssetDatabase.GetAssetPath(programAsset);

            programAsset = AssetDatabase.LoadAssetAtPath <UdonSharpProgramAsset>(programAssetPath);

            if (programAsset != null)
            {
                AssetDatabase.DeleteAsset(programAssetPath);
            }
        }
Beispiel #12
0
        public override void OnInspectorGUI()
        {
            //base.OnInspectorGUI();

            if (!T23_EditorUtility.GuideJoinMaster(master, body, body.groupID, 2))
            {
                return;
            }

            serializedObject.Update();

            T23_EditorUtility.ShowTitle("Action");

            UdonSharpProgramAsset programAsset = UdonSharpEditorUtility.GetUdonSharpProgramAsset((UdonSharpBehaviour)target);

            UdonSharpGUI.DrawCompileErrorTextArea(programAsset);

            if (master)
            {
                GUILayout.Box("[#" + body.groupID.ToString() + "] " + body.title, T23_EditorUtility.HeadlineStyle());
                T23_EditorUtility.ShowSwapButton(master, body.title);
                body.priority = master.actionTitles.IndexOf(body.title);
            }
            else
            {
                body.groupID  = EditorGUILayout.IntField("Group ID", body.groupID);
                body.priority = EditorGUILayout.IntField("Priority", body.priority);
            }

            SerializedProperty recieverProp = serializedObject.FindProperty("recievers");

            if (recieverReorderableList == null)
            {
                recieverReorderableList                     = new ReorderableList(serializedObject, recieverProp);
                recieverReorderableList.draggable           = true;
                recieverReorderableList.displayAdd          = true;
                recieverReorderableList.drawHeaderCallback  = rect => EditorGUI.LabelField(rect, "Recievers");
                recieverReorderableList.drawElementCallback = (rect, index, isActive, isFocused) =>
                {
                    rect.height           = EditorGUIUtility.singleLineHeight;
                    body.recievers[index] = (Animator)EditorGUI.ObjectField(rect, body.recievers[index], typeof(Animator), true);
                };
            }
            recieverReorderableList.DoLayoutList();

            EditorGUI.BeginChangeCheck();
            operation = (ToggleOperation)EditorGUILayout.EnumPopup("Operation", GetOperation());
            if (EditorGUI.EndChangeCheck())
            {
                SelectOperation();
            }

            if (!master || master.randomize)
            {
                prop = serializedObject.FindProperty("randomAvg");
                EditorGUILayout.PropertyField(prop);
            }

            serializedObject.ApplyModifiedProperties();
        }
        public static UdonSharpBehaviour GetProxyBehaviour(UdonBehaviour udonBehaviour, ProxySerializationPolicy proxySerializationPolicy)
        {
            if (udonBehaviour == null)
            {
                throw new System.ArgumentNullException("Source Udon Behaviour cannot be null");
            }

            if (udonBehaviour.programSource == null)
            {
                throw new System.ArgumentNullException("Program source on UdonBehaviour cannot be null");
            }

            UdonSharpProgramAsset udonSharpProgram = udonBehaviour.programSource as UdonSharpProgramAsset;

            if (udonSharpProgram == null)
            {
                throw new System.ArgumentException("UdonBehaviour must be using an UdonSharp program");
            }

            UdonSharpBehaviour proxyBehaviour = FindProxyBehaviour(udonBehaviour, proxySerializationPolicy);

            if (proxyBehaviour)
            {
                return(proxyBehaviour);
            }

            // We've failed to find an existing proxy behaviour so we need to create one
            System.Type scriptType = udonSharpProgram.GetClass();

            if (scriptType == null)
            {
                return(null);
            }

            SetIgnoreEvents(true);

            try
            {
                proxyBehaviour           = (UdonSharpBehaviour)udonBehaviour.gameObject.AddComponent(scriptType);
                proxyBehaviour.hideFlags = HideFlags.DontSaveInBuild |
#if !UDONSHARP_DEBUG
                                           HideFlags.HideInInspector |
#endif
                                           HideFlags.DontSaveInEditor;
                proxyBehaviour.enabled = false;
            }
            finally
            {
                SetIgnoreEvents(false);
            }

            SetBackingUdonBehaviour(proxyBehaviour, udonBehaviour);

            _proxyBehaviourLookup.Add(udonBehaviour, proxyBehaviour);

            CopyUdonToProxy(proxyBehaviour, proxySerializationPolicy);

            return(proxyBehaviour);
        }
Beispiel #14
0
        /// <summary>
        /// Runs upgrade process on all U# scripts
        /// </summary>
        /// <returns>True if some scripts have been updated</returns>
        internal static bool UpgradeScripts()
        {
            bool upgraded = UpgradeScripts(UdonSharpProgramAsset.GetAllUdonSharpPrograms());

            _needsProgramUpgradePass = false;

            return(upgraded);
        }
 private static void OnEditorUpdate()
 {
     if (_requiresCompile)
     {
         UdonSharpProgramAsset.CompileAllCsPrograms();
         _requiresCompile = false;
     }
 }
Beispiel #16
0
    public void AddAction(UdonSharpProgramAsset program)
    {
        ComponentSet set = AddUdonComponent(program, actionTitles);

        actionSet.Add(set);
        actionTitles.Add(set.title);
        OrderComponents();
        shouldMoveComponents = true;
    }
    private static void OnRightToolbarGUI()
    {
        if (GUILayout.Button("Compile UdpnSharp"))
        {
            UdonSharpProgramAsset.CompileAllCsPrograms();
        }

        GUILayout.FlexibleSpace();
    }
Beispiel #18
0
    public void AddTrigger(UdonSharpProgramAsset program)
    {
        ComponentSet set = AddUdonComponent(program, triggerTitles);

        triggerSet.Add(set);
        triggerTitles.Add(set.title);
        OrderComponents();
        shouldMoveComponents = true;
    }
        public void Compile()
        {
            Profiler.BeginSample("UdonSharp Compile");

            System.Diagnostics.Stopwatch compileTimer = new System.Diagnostics.Stopwatch();
            compileTimer.Start();

            int totalErrorCount = 0;

            try
            {
                EditorUtility.DisplayProgressBar("UdonSharp Compile", "Parsing Syntax Trees...", 0f);

                UdonSharpProgramAsset[] allPrograms = UdonSharpProgramAsset.GetAllUdonSharpPrograms();
                List <(UdonSharpProgramAsset, string)> programAssetsAndPaths = new List <(UdonSharpProgramAsset, string)>();

                foreach (UdonSharpProgramAsset programAsset in allPrograms)
                {
                    if (programAsset == null || programAsset.sourceCsScript == null)
                    {
                        continue;
                    }

                    programAssetsAndPaths.Add((programAsset, AssetDatabase.GetAssetPath(programAsset.sourceCsScript)));
                }

                UdonSharpProgramAsset[] programAssetsToCompile = modules.Select(e => e.programAsset).Where(e => e != null && e.sourceCsScript != null).ToArray();

                try
                {
                    beforeCompile?.Invoke(programAssetsToCompile);
                }
                catch (System.Exception e)
                {
                    Debug.LogError($"Exception thrown by pre compile listener\n{e}");
                }

                object syntaxTreeLock = new object();
                List <(UdonSharpProgramAsset, Microsoft.CodeAnalysis.SyntaxTree)> programsAndSyntaxTrees = new List <(UdonSharpProgramAsset, Microsoft.CodeAnalysis.SyntaxTree)>();
                Dictionary <UdonSharpProgramAsset, (string, Microsoft.CodeAnalysis.SyntaxTree)> syntaxTreeSourceLookup = new Dictionary <UdonSharpProgramAsset, (string, Microsoft.CodeAnalysis.SyntaxTree)>();

                string[] defines = UdonSharpUtils.GetProjectDefines(isEditorBuild);

                Parallel.ForEach(programAssetsAndPaths, (currentProgram) =>
                {
                    string programSource = UdonSharpUtils.ReadFileTextSync(currentProgram.Item2);

                    Microsoft.CodeAnalysis.SyntaxTree programSyntaxTree = CSharpSyntaxTree.ParseText(programSource, CSharpParseOptions.Default.WithDocumentationMode(DocumentationMode.None).WithPreprocessorSymbols(defines));

                    lock (syntaxTreeLock)
                    {
                        programsAndSyntaxTrees.Add((currentProgram.Item1, programSyntaxTree));
                        syntaxTreeSourceLookup.Add(currentProgram.Item1, (programSource, programSyntaxTree));
                    }
                });
Beispiel #20
0
 private void AddAction()
 {
     if (addAction)
     {
         if (addAction.GetClass().GetField("isAction") != null)
         {
             master.AddAction(addAction);
             addAction = null;
         }
     }
 }
Beispiel #21
0
 private void AddTrigger()
 {
     if (addTrigger)
     {
         if (addTrigger.GetClass().GetField("isTrigger") != null)
         {
             master.AddTrigger(addTrigger);
             addTrigger = null;
         }
     }
 }
Beispiel #22
0
 private void SetBroadcast()
 {
     if (setBroadcast)
     {
         if (setBroadcast.GetClass().GetField("isBroadcast") != null)
         {
             master.SetBroadcast(setBroadcast);
             setBroadcast = null;
         }
     }
 }
        public static UdonSharpBehaviour AddUdonSharpComponent(this GameObject gameObject, System.Type type)
        {
            if (type == typeof(UdonSharpBehaviour))
            {
                throw new System.ArgumentException("Cannot add components of type 'UdonSharpBehaviour', you can only add subclasses of this type");
            }

            if (!typeof(UdonSharpBehaviour).IsAssignableFrom(type))
            {
                throw new System.ArgumentException("Type for AddUdonSharpComponent must be a subclass of UdonSharpBehaviour");
            }

            UdonBehaviour udonBehaviour = gameObject.AddComponent <UdonBehaviour>();

            UdonSharpProgramAsset programAsset = UdonSharpProgramAsset.GetProgramAssetForClass(type);

            udonBehaviour.programSource = programAsset;
#pragma warning disable CS0618 // Type or member is obsolete
            udonBehaviour.SynchronizePosition             = false;
            udonBehaviour.AllowCollisionOwnershipTransfer = false;
#pragma warning restore CS0618 // Type or member is obsolete

            switch (programAsset.behaviourSyncMode)
            {
            case BehaviourSyncMode.Continuous:
                udonBehaviour.SyncMethod = Networking.SyncType.Continuous;
                break;

            case BehaviourSyncMode.Manual:
                udonBehaviour.SyncMethod = Networking.SyncType.Manual;
                break;

            case BehaviourSyncMode.None:
                udonBehaviour.SyncMethod = Networking.SyncType.None;
                break;
            }

            SerializedObject   componentAsset = new SerializedObject(udonBehaviour);
            SerializedProperty serializedProgramAssetProperty = componentAsset.FindProperty("serializedProgramAsset");

            serializedProgramAssetProperty.objectReferenceValue = programAsset.SerializedProgramAsset;
            componentAsset.ApplyModifiedPropertiesWithoutUndo();

            UdonSharpBehaviour proxyComponent = UdonSharpEditorUtility.GetProxyBehaviour(udonBehaviour);

            if (EditorApplication.isPlaying)
            {
                udonBehaviour.InitializeUdonContent();
            }

            return(proxyComponent);
        }
        private static void CreateUSharpScript()
        {
            string folderPath = "Assets/";

            if (Selection.activeObject != null)
            {
                folderPath = AssetDatabase.GetAssetPath(Selection.activeObject);
                if (Selection.activeObject.GetType() != typeof(UnityEditor.DefaultAsset))
                {
                    folderPath = Path.GetDirectoryName(folderPath);
                }
            }
            else if (Selection.assetGUIDs.Length > 0)
            {
                folderPath = AssetDatabase.GUIDToAssetPath(Selection.assetGUIDs[0]);
            }

            folderPath = folderPath.Replace('\\', '/');

            string chosenFilePath = EditorUtility.SaveFilePanelInProject("Save UdonSharp File", "", "cs", "Save UdonSharp file", folderPath);

            if (chosenFilePath.Length > 0)
            {
                chosenFilePath = UdonSharpSettings.SanitizeScriptFilePath(chosenFilePath);
                string chosenFileName = Path.GetFileNameWithoutExtension(chosenFilePath).Replace(" ", "").Replace("#", "Sharp");
                string assetFilePath  = Path.Combine(Path.GetDirectoryName(chosenFilePath), $"{chosenFileName}.asset");

                if (AssetDatabase.LoadAssetAtPath <UdonSharpProgramAsset>(assetFilePath) != null)
                {
                    if (!EditorUtility.DisplayDialog("File already exists", $"Corresponding asset file '{assetFilePath}' already found for new UdonSharp script. Overwrite?", "Ok", "Cancel"))
                    {
                        return;
                    }
                }

                string fileContents = UdonSharpSettings.GetProgramTemplateString(chosenFileName);

                File.WriteAllText(chosenFilePath, fileContents, System.Text.Encoding.UTF8);

                AssetDatabase.ImportAsset(chosenFilePath, ImportAssetOptions.ForceSynchronousImport);
                MonoScript newScript = AssetDatabase.LoadAssetAtPath <MonoScript>(chosenFilePath);

                UdonSharpProgramAsset newProgramAsset = ScriptableObject.CreateInstance <UdonSharpProgramAsset>();
                newProgramAsset.sourceCsScript = newScript;

                AssetDatabase.CreateAsset(newProgramAsset, assetFilePath);

                AssetDatabase.Refresh();
            }
        }
Beispiel #25
0
    private Component[] GetSurfaceComponents()
    {
        List <string> usharpClass = new List <string>();

        UdonBehaviour[] udonComponents = GetComponents <UdonBehaviour>();
        foreach (var udon in udonComponents)
        {
            UdonSharpProgramAsset program = udon.programSource as UdonSharpProgramAsset;
            if (program != null)
            {
                usharpClass.Add(program.GetClass().Name);
            }
        }
        return(GetComponents <Component>().Where(o => !usharpClass.Contains(o.GetType().ToString())).ToArray());
    }
        public CompilationModule(UdonSharpProgramAsset sourceAsset)
        {
            programAsset           = sourceAsset;
            resolver               = new ResolverContext();
            moduleSymbols          = new SymbolTable(resolver, null);
            moduleLabels           = new LabelTable();
            fieldsWithInitializers = new HashSet <FieldDeclarationSyntax>();

            if (programAsset.sourceCsScript == null)
            {
                throw new System.ArgumentException($"Asset '{AssetDatabase.GetAssetPath(programAsset)}' does not have a valid program source to compile from");
            }

            settings = UdonSharpSettings.GetSettings();
        }
        private static UdonSharpProgramAsset GetUdonSharpProgram(MonoScript programScript)
        {
            string[] udonSharpDataAssets = AssetDatabase.FindAssets($"t:{typeof(UdonSharpProgramAsset).Name}");

            foreach (string dataGuid in udonSharpDataAssets)
            {
                UdonSharpProgramAsset programAsset = AssetDatabase.LoadAssetAtPath <UdonSharpProgramAsset>(AssetDatabase.GUIDToAssetPath(dataGuid));

                if (programAsset && programAsset.sourceCsScript == programScript)
                {
                    return(programAsset);
                }
            }

            return(null);
        }
        public static UdonSharpBehaviour AddComponent(GameObject gameObject, System.Type type)
        {
            if (type == typeof(UdonSharpBehaviour))
            {
                throw new System.ArgumentException("Cannot add components of type 'UdonSharpBehaviour', you can only add subclasses of this type");
            }

            if (!typeof(UdonSharpBehaviour).IsAssignableFrom(type))
            {
                throw new System.ArgumentException("Type for AddUdonSharpComponent must be a subclass of UdonSharpBehaviour");
            }

            UdonBehaviour udonBehaviour = Undo.AddComponent <UdonBehaviour>(gameObject);

            UdonSharpProgramAsset programAsset = UdonSharpProgramAsset.GetProgramAssetForClass(type);

            udonBehaviour.programSource = programAsset;
#pragma warning disable CS0618 // Type or member is obsolete
            udonBehaviour.AllowCollisionOwnershipTransfer = false;
#pragma warning restore CS0618 // Type or member is obsolete

            SerializedObject   componentAsset = new SerializedObject(udonBehaviour);
            SerializedProperty serializedProgramAssetProperty = componentAsset.FindProperty("serializedProgramAsset");

            serializedProgramAssetProperty.objectReferenceValue = programAsset.SerializedProgramAsset;
            componentAsset.ApplyModifiedProperties();

            System.Type scriptType = programAsset.GetClass();

            UdonSharpBehaviour proxyComponent = (UdonSharpBehaviour)Undo.AddComponent(udonBehaviour.gameObject, scriptType);
            proxyComponent.hideFlags = HideFlags.DontSaveInBuild |
#if !UDONSHARP_DEBUG
                                       HideFlags.HideInInspector |
#endif
                                       HideFlags.DontSaveInEditor;
            proxyComponent.enabled = false;

            UdonSharpEditorUtility.SetBackingUdonBehaviour(proxyComponent, udonBehaviour);
            UdonSharpEditorUtility.CopyUdonToProxy(proxyComponent, ProxySerializationPolicy.AllWithCreateUndo);

            if (EditorApplication.isPlaying)
            {
                udonBehaviour.InitializeUdonContent();
            }

            return(proxyComponent);
        }
        private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
        {
            foreach (string importedAssetPath in importedAssets)
            {
                UdonSharpProgramAsset importedAsset = AssetDatabase.LoadAssetAtPath <UdonSharpProgramAsset>(importedAssetPath);

                if (importedAsset && (importedAsset.CompiledVersion < UdonSharpProgramVersion.CurrentVersion || importedAsset.ScriptVersion < UdonSharpProgramVersion.CurrentVersion))
                {
                    UdonSharpUpgrader.QueueUpgrade(importedAsset);
                    UdonSharpEditorCache.Instance.QueueUpgradePass();
                }

                if (importedAsset)
                {
                    UdonSharpProgramAsset.ClearProgramAssetCache();
                }
            }
        }
Beispiel #30
0
 private static void GetVariableType(UdonBehaviour udonBehaviour, string symbolName, out Type variableType,
                                     IUdonVariableTable publicVariables, UdonSharpProgramAsset programAsset)
 {
     if (!publicVariables.TryGetVariableType(symbolName, out variableType))
     {
         var symbolTable = udonBehaviour.GetSymbolTable();
         if (symbolTable.HasAddressForSymbol(symbolName))
         {
             var symbolAddress = symbolTable.GetAddressFromSymbol(symbolName);
             var program       = programAsset.GetRealProgram();
             variableType = program.Heap.GetHeapVariableType(symbolAddress);
         }
         else
         {
             variableType = null;
         }
     }
 }