Error building player because scripts have compile errors in the editor что делать

I have the Tiled2Unity plugin. When I begin to build a version of my game in Unity, be it standalone version or anything else,i get the following error, "Error building Player because scripts have

I have the Tiled2Unity plugin. When I begin to build a version of my game in Unity, be it standalone version or anything else,i get the following error, «Error building Player because scripts have compile errors in the editor»

Then it points me to this class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using UnityEditor;

namespace Tiled2Unity
{
    public class CircleObject : TmxObject
    {
    }
}

Can someone please help me figure out what is the problem?

Programmer's user avatar

Programmer

119k21 gold badges231 silver badges318 bronze badges

asked Mar 3, 2017 at 21:26

Letholor's user avatar

1

You cannot build any your script that contains using UnityEditor; or class/API from the UnityEditor namespace. This is why you should put any script that contains any of these in a folder called Editor.

When Unity is building your project, it ignores any script placed in this folder since it considers them as an Editor script or plugin.

You have three choices:

  1. Remove using UnityEditor; from your script.

  2. Place your script in a folder called Editor.

  3. Use Unity’s preprocessor directive to determie when not to compile with using UnityEditor;

    You can do that by replacing:

     using UnityEditor;
    

    with

     #if UNITY_EDITOR 
     using UnityEditor;
     #endif 
    

I would go with #2. Create a different script for any Editor stuff and place it in the Editor folder. Note that Unity will not compile any script in this folder when building your project. Scripts in this folder are meant to run in the Editor only.

Wai Ha Lee's user avatar

Wai Ha Lee

8,41977 gold badges60 silver badges90 bronze badges

answered Mar 3, 2017 at 21:44

Programmer's user avatar

ProgrammerProgrammer

119k21 gold badges231 silver badges318 bronze badges

2

I was having the same problem however easily found a fix.

Go into every Script you have in that unity project and double check the first lines, the ones which say «Using UnityEngine» and «Unity System Collections». I had only added to these lines with a «Using UnityEngine.UI» however when I was going through ALL my scripts for that project I found that there a few extra ones there that weren’t there when I started and I had not added (they added themselves there) , for example there was a «Using System Collections XMP» or something random like that. Simply delete these, save the script and you should be good to go.

I have no idea why they are there and what type of problem they seemed to cause however I can now build my project to android problem free now.

answered Jul 30, 2020 at 11:59

WorkedForMe's user avatar

1

Exception: Error building Player because scripts had compile

FFFUUU
Как же задолбали эти ошибки !!!!!!
Exception: Error building Player because scripts had compiler errors
что это такое ?
помогите плз…
Раньше такого не было.

inkogni2
UNIт
 
Сообщения: 52
Зарегистрирован: 20 сен 2011, 20:43

Re: Exception: Error building Player because scripts had compile

Сообщение DbIMok 29 дек 2011, 15:35

ваши ошибки, вам и FFFUUU. это значит, что пока ошибки не исправите, билда не будет.

Аватара пользователя
DbIMok
Адепт
 
Сообщения: 6321
Зарегистрирован: 31 июл 2009, 14:05

Re: Exception: Error building Player because scripts had compile

Сообщение AndreyMust19 29 дек 2011, 19:14

Движок не может скомпилировать скрипты, если есть хотя бы 1 ошибка синтаксиса или семантики.
Самого бесит, но виноват тот, кто написал код — компилятор просто его не понимает.

Нужна помощь? Сами, сами, сами, сами, сами… делаем все сами

AndreyMust19
Адепт
 
Сообщения: 1119
Зарегистрирован: 07 июн 2011, 13:19

Re: Exception: Error building Player because scripts had compile

Сообщение seaman 29 дек 2011, 23:23

Самого бесит

Компилятор заранее об этом предупреждает. Так что просто не стройте проект пока не исправите ошибки.

seaman
Адепт
 
Сообщения: 8351
Зарегистрирован: 24 янв 2011, 12:32
Откуда: Самара

Re: Exception: Error building Player because scripts had compile

Сообщение inkogni2 30 дек 2011, 11:52

seaman писал(а):

Самого бесит

Компилятор заранее об этом предупреждает. Так что просто не стройте проект пока не исправите ошибки.

Но в движке же я пориграть сцену могу :ymsmug:
и так на ВСЕХ проэктах, даже со стандартным набором ассетов….

inkogni2
UNIт
 
Сообщения: 52
Зарегистрирован: 20 сен 2011, 20:43

Re: Exception: Error building Player because scripts had compile

Сообщение VVM 30 дек 2011, 13:17

Аватара пользователя
VVM
UNец
 
Сообщения: 47
Зарегистрирован: 16 сен 2011, 11:57
Откуда: Санкт-Петербург


Re: Exception: Error building Player because scripts had compile

Сообщение VVM 01 янв 2012, 14:43

И ?

Если не понятен смысл прочитанного, то перечитайте еще раз, более вдумчиво. Это мое ИМХО, хотите принимайте, хотите — нет.

Что касается «Exception: Error building player because scripts had compiler errors» — так вам все уже объяснили. Как исправите ошибки в скрипте (скриптах), откомпилируете их, все должно запускаться.

Аватара пользователя
VVM
UNец
 
Сообщения: 47
Зарегистрирован: 16 сен 2011, 11:57
Откуда: Санкт-Петербург

Re: Exception: Error building Player because scripts had compile

Сообщение AndreyMust19 01 янв 2012, 14:45

Но в движке же я пориграть сцену могу

При запуске игры в режиме редактора, если скрипты не скомпилировались из-за ошибки, берется результат предыдущей успешной компиляции.
При построении проекта такое не пройдет.

Нужна помощь? Сами, сами, сами, сами, сами… делаем все сами

AndreyMust19
Адепт
 
Сообщения: 1119
Зарегистрирован: 07 июн 2011, 13:19

Re: Exception: Error building Player because scripts had compile

Сообщение waruiyume 01 янв 2012, 14:57

При запуске игры в режиме редактора, если скрипты не скомпилировались из-за ошибки, берется результат предыдущей успешной компиляции.

Где это можно включить?

Аватара пользователя
waruiyume
Адепт
 
Сообщения: 6059
Зарегистрирован: 30 окт 2010, 05:03
Откуда: Ростов на Дону


Вернуться в Почемучка

Кто сейчас на конференции

Сейчас этот форум просматривают: Google [Bot] и гости: 33



I am having problem with building a game. it keep saying ‘Error building Player because scripts have compile errors in the editor’

I followed tips from this and still got nothing on working.

a friend suggested me to add

public static class EditorUtil

{

#if UNITY_EDITOR
    //Editr code here
    #endif 
}

and it still continues with same error.

this is the full code:

 using UnityEngine;

 using System.Collections.Generic;

#if UNITY_EDITOR
using UnityEditor;
#endif



public static class EditorUtil
 {


#if UNITY_EDITOR
    //Editr code here

    static string m_EditorResourcesPath = string.Empty;
    private static string path = string.Empty;

    internal static string editorResourcesPath
    {



        get
        {
            if (string.IsNullOrEmpty(m_EditorResourcesPath))
            {
                string path;

                if (SearchForEditorResourcesPath(out path))
                    m_EditorResourcesPath = path;
                else
                    Debug.LogError("Unable to locate editor resources. Make sure the PostProcessing package has been installed correctly.");
            }

            return m_EditorResourcesPath;
        }
    }

    static bool SearchForEditorResourcesPath(out string path)
    {
        path = string.Empty;

        string searchStr = EditorUtil.path;
        string str = null;

        foreach (var assetPath in AssetDatabase.GetAllAssetPaths())
        {
            if (assetPath.Contains(searchStr))
            {
                str = assetPath;
                break;
            }
        }

        if (str == null)
            return false;

        path = str.Substring(0, str.LastIndexOf(searchStr) + searchStr.Length);
        return true;
    }

    internal static T Load<T>(string path, string name) where T : Object
    {
        EditorUtil.path = path;
        return AssetDatabase.LoadAssetAtPath<T>(editorResourcesPath + name);
    }

    private static List<string> layers;
    private static string[] layerNames;

    public static LayerMask LayerMaskField(string label, LayerMask selected)
    {
        if (layers == null) 
        {
            layers = new List<string>();
            layerNames = new string[4];
        }
        else 
        {
            layers.Clear ();
        }

        int emptyLayers = 0;
        for (int i = 0; i < 32; i++) 
        {
            string layerName = LayerMask.LayerToName (i);

            if (layerName != "") 
            { 
                layers.Add (layerName);
            } 
            else
            {
                emptyLayers++;
            }
        }

        if (layerNames.Length != layers.Count)
        {
            layerNames = new string[layers.Count];
        }

        for (int i=0; i < layerNames.Length; i++) 
            layerNames[i] = layers[i];

        selected.value =  EditorGUILayout.MaskField (label, selected.value, layerNames);
        return selected;
    }

    public static Rect GetCurrentRect (float fieldSize = 18)
    {
        return GUILayoutUtility.GetRect(GUIContent.none, GUIStyle.none, GUILayout.Height(fieldSize));
    }

    public static GameObject GetSelectedGameObject ()
    {
        return Selection.activeGameObject;
    }



    public static AnimationClip GetAnimationClipFromAnimator(Animator animator, string name)
    {
        if (animator == null)
            return null;

        foreach (AnimationClip animClip in animator.runtimeAnimatorController.animationClips)
        {
            if (animClip.name == name)
                return animClip;
        }
        return null;
    }

#endif 
}

whats a solution for this? I’ve searched many posts in here and other forums and yet I keep getting the same error.

example error

Edit: second pic

I am having problem with building a game. it keep saying ‘Error building Player because scripts have compile errors in the editor’

I followed tips from this and still got nothing on working.

a friend suggested me to add

public static class EditorUtil

{

#if UNITY_EDITOR
    //Editr code here
    #endif 
}

and it still continues with same error.

this is the full code:

 using UnityEngine;

 using System.Collections.Generic;

#if UNITY_EDITOR
using UnityEditor;
#endif



public static class EditorUtil
 {


#if UNITY_EDITOR
    //Editr code here

    static string m_EditorResourcesPath = string.Empty;
    private static string path = string.Empty;

    internal static string editorResourcesPath
    {



        get
        {
            if (string.IsNullOrEmpty(m_EditorResourcesPath))
            {
                string path;

                if (SearchForEditorResourcesPath(out path))
                    m_EditorResourcesPath = path;
                else
                    Debug.LogError("Unable to locate editor resources. Make sure the PostProcessing package has been installed correctly.");
            }

            return m_EditorResourcesPath;
        }
    }

    static bool SearchForEditorResourcesPath(out string path)
    {
        path = string.Empty;

        string searchStr = EditorUtil.path;
        string str = null;

        foreach (var assetPath in AssetDatabase.GetAllAssetPaths())
        {
            if (assetPath.Contains(searchStr))
            {
                str = assetPath;
                break;
            }
        }

        if (str == null)
            return false;

        path = str.Substring(0, str.LastIndexOf(searchStr) + searchStr.Length);
        return true;
    }

    internal static T Load<T>(string path, string name) where T : Object
    {
        EditorUtil.path = path;
        return AssetDatabase.LoadAssetAtPath<T>(editorResourcesPath + name);
    }

    private static List<string> layers;
    private static string[] layerNames;

    public static LayerMask LayerMaskField(string label, LayerMask selected)
    {
        if (layers == null) 
        {
            layers = new List<string>();
            layerNames = new string[4];
        }
        else 
        {
            layers.Clear ();
        }

        int emptyLayers = 0;
        for (int i = 0; i < 32; i++) 
        {
            string layerName = LayerMask.LayerToName (i);

            if (layerName != "") 
            { 
                layers.Add (layerName);
            } 
            else
            {
                emptyLayers++;
            }
        }

        if (layerNames.Length != layers.Count)
        {
            layerNames = new string[layers.Count];
        }

        for (int i=0; i < layerNames.Length; i++) 
            layerNames[i] = layers[i];

        selected.value =  EditorGUILayout.MaskField (label, selected.value, layerNames);
        return selected;
    }

    public static Rect GetCurrentRect (float fieldSize = 18)
    {
        return GUILayoutUtility.GetRect(GUIContent.none, GUIStyle.none, GUILayout.Height(fieldSize));
    }

    public static GameObject GetSelectedGameObject ()
    {
        return Selection.activeGameObject;
    }



    public static AnimationClip GetAnimationClipFromAnimator(Animator animator, string name)
    {
        if (animator == null)
            return null;

        foreach (AnimationClip animClip in animator.runtimeAnimatorController.animationClips)
        {
            if (animClip.name == name)
                return animClip;
        }
        return null;
    }

#endif 
}

whats a solution for this? I’ve searched many posts in here and other forums and yet I keep getting the same error.

example error

Edit: second pic


Former user

created an issue
2017-09-30

When I try to build the project I get the following error: «Error Building Player because scripts have compile errors in the editor». I am running 5.6.3p2

To reproduce the error simply create a new empty scene and import the Uduino asset and save the scene. Even in this simplest possible case you will get the error when you try building the project.

Comments (6)

  1. Marc Teys

    repo owner

    I could not reproduce the errror by importing Uduino asset. Did you run the initial configuration and/or manually set the .NET API compatibility ? (Set the API Compatibility level to .NET 2.0 (and not .Net 2.0 Subset). This setting is located under EditProject settingsPlayer. )

    • 2017-10-02T08:47:52+00:00

  2. Albert

    I have tried both and am still unable to build. I have also tried when the board is connected and disconnected, when the Uduino asset is placed into the scene, and when it is not, and nearly any other combination. When you tried reproducing the error, were you using the latest Unity 5.6.3p2?

    There is another message in the console, right before the one mentioned above, that I did not notice previously:

    » Assets/Uduino/Scripts/UduinoDevice.cs(2,7): error CS0246: The type or namespace name `UnityEditor’ could not be found. Are you missing an assembly reference?»

    «Error building Player because scripts had compiler errors»

    • 2017-10-02T17:41:40+00:00

  3. Albert

    • 2017-10-02T17:45:23+00:00

  4. Marc Teys

    repo owner

    Oh I see, in the last update I added a reference to UnityEditor without adding the flag for building.

    You can edit the script UduinoDevice.cs as following:

    using UnityEngine;
    #if UNITY_EDITOR
    using UnityEditor;
    #endif
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    
    namespace Uduino
    {
        public class UduinoDevice : SerialArduino
        {
            public string name {
                get
                {
                    return _name;
                } set
                {
                    if (_name == "")
                        _name = value;
                }
            }
            private string _name = "";
    
            public int boardType = 0;
    
            public bool continuousRead = false;
            public string read = null;
            public string lastRead = null;
            public string lastWrite = null;
            private Dictionary<string, List<string>> bundles = new Dictionary<string, List<string>>();
    
            public System.Action<string> callback = null;
    
            public UduinoDevice(string port, int baudrate = 9600, int readTimeout = 100, int writeTimeout = 100, int boardType = 0) : base(port, baudrate)
            {
                this.readTimeout = readTimeout;
                this.writeTimeout = writeTimeout;
                this.boardType = boardType;
            }
    
            /// <summary>
            /// Add a message to the bundle
            /// </summary>
            /// <param name="message">Message to send</param>
            /// <param name="bundle">Bundle Name</param>
            public void AddToBundle( string message , string bundle)
            {
                List<string> existing;
                if (!bundles.TryGetValue(bundle, out existing))
                {
                    existing = new List<string>();
                    bundles[bundle] = existing;
                }
                existing.Add("," + message);
              //  Log.Debug("Message <color=#4CAF50>" + message + "</color> added to the bundle " + bundle);
            }
    
            /// <summary>
            /// Send a Bundle to the arduino
            /// </summary>
            /// <param name="bundleName">Name of the bundle to send</param>
            public void SendBundle(string bundleName)
            {
                List<string> bundleValues;
                if (bundles.TryGetValue(bundleName, out bundleValues))
                {
                    string fullMessage = "b " + bundleValues.Count;
    
                    if (bundleValues.Count == 1 ) // If there is one message
                    {
                        string message = bundleValues[0].Substring(1, bundleValues[0].Length - 1);
                        if (message.Contains("r")) ReadFromArduino(message);
                        else WriteToArduino(message);
                        return;
                    }
    
                    for (int i = 0; i < bundleValues.Count; i++)
                        fullMessage += bundleValues[i];
    
                    if (fullMessage.Contains("r")) ReadFromArduino(fullMessage);
                    else WriteToArduino(fullMessage);
    
                    if (fullMessage.Length >= 120)  /// TODO : Max Length, matching avec arduino
                        Log.Warning("The bundle message is too big. Try to not send too many messages or increase UDUINOBUFFER in Uduino library.");
    
                    bundles.Remove(bundleName);
                }
                else
                {
                    if(bundleName != "init")
                        Log.Info("You are tring to send the bundle "" + bundleName + "" but it seems that it's empty.");
                }
            }
    
            public void SendAllBundles()
            {
                Log.Debug("Send all bundles");
                List<string> bundleNames = new List<string>(bundles.Keys);
                foreach (string key in bundleNames)
                    SendBundle(key);
            }
    
            public override void WritingSuccess(string message)
            {
                lastWrite = message;
            }
    
            public override void ReadingSuccess(string message)
            {
                if(lastRead == null) 
                {
                    lastRead = message;
                    return; // If the previous message was empty it's meaning that it was the first one; so we don't transmit it. 
                }
                else 
                    lastRead = message;
    
                if (UduinoManager.Instance)
                {
                    UduinoManager.Instance.InvokeAsync(() =>
                    {
                        if (message.Split(' ')[0] == "uduinoIdentity")
                            return;
    
                        if (callback != null)
                            callback(message);
                        UduinoManager.Instance.TriggerEvent(message, _name);
                        #if UNITY_EDITOR
                        if (Application.isPlaying) EditorUtility.SetDirty(UduinoManager.Instance);
                        #endif
                    });
                } else if(!Application.isPlaying && callback != null) //if it's the editor
                    callback(message);
            }
        }
    }
    
    • 2017-10-02T21:44:17+00:00

  5. Albert

    That fixed it

    • 2017-10-02T21:54:45+00:00

  6. Marc Teys

    repo owner

    • changed status to
      resolved

    Closing, issue fixed in the last version

    • 2017-10-05T14:24:49+00:00

  7. Log in to comment

Jira Software: the preferred issue tracker for Bitbucket. Join the team!

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Comments

@javiertorres7

I am trying to complete the building step, but it says that I need to fix some compile errors in the scripts, even though, I did not mess with code in the scripts. I also I do not know how to look for the errors in the scripts. I am using Visual Studio 2015 as my editor and I don’t see any errors.

@javiertorres7

I am using Unity 5.50f3 (64bit) by the way.

@timGerken

Hi @javiertorres7 ,
Can you give a little more detail about the errors that the Unity console is reporting? Maybe attach a screen shot? Unity 5.5.0f3 is the correct version of Unity (projectversion.txt). I exclusively use 64-bit.
Thanks!
Tim

@javiertorres7

@timGerken

@javiertorres7

uniiii

@timGerken

@javiertorres7
You are probably being affected by the details described in this thread. I just made a commit in Master to work with Unity 5.5.1p4 and Visual Studio 2017. Please let me know if these changes also resolve the issue you describe here.

2 participants

@timGerken

@javiertorres7

Понравилась статья? Поделить с друзьями:
  • Error building player because scripts have compile errors in the editor unity
  • Error building player because script class layout is incompatible between the editor and the player
  • Error building player because build target was unsupported
  • Error building embree static ray caster committing scene failed
  • Error building driver info list fail error code 0x3