Error building player because scripts have compile errors in the editor unity

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

Содержание

  1. Error building player because scripts had compiler errors
  2. unity error building player because scripts had compiler errors
  3. 3 Ответов

Error building player because scripts had compiler errors

Every time i try to build my game. I get an error:

Exception: Error building Player because scripts had compiler errors UnityEditor.BuildPlayerWindow.BuildPlayerWithDefaultSettings (Boolean askForBuildLocation, BuildOptions forceOptions) (at C:/BuildAgent/work/6bc5f79e0a4296d6/Editor/Mono/BuildPlayerWindow.cs:341) UnityEditor.BuildPlayerWindow.GUIBuildButtons (Boolean enableBuildButton, Boolean enableBuildAndRunButton, Boolean canInstallInBuildFolder) (at C:/BuildAgent/work/6bc5f79e0a4296d6/Editor/Mono/BuildPlayerWindow.cs:949) UnityEditor.BuildPlayerWindow.ShowBuildTargetSettings () (at C:/BuildAgent/work/6bc5f79e0a4296d6/Editor/Mono/BuildPlayerWindow.cs:923) UnityEditor.BuildPlayerWindow.OnGUI () (at C:/BuildAgent/work/6bc5f79e0a4296d6/Editor/Mono/BuildPlayerWindow.cs:697) System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) Rethrow as TargetInvocationException: Exception has been thrown by the target of an invocation. System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) UnityEditor.HostView.Invoke (System.String methodName, System.Object obj) (at C:/BuildAgent/work/6bc5f79e0a4296d6/Editor/Mono/GUI/DockArea.cs:213) UnityEditor.HostView.Invoke (System.String methodName) (at C:/BuildAgent/work/6bc5f79e0a4296d6/Editor/Mono/GUI/DockArea.cs:206) UnityEditor.HostView.OnGUI () (at C:/BuildAgent/work/6bc5f79e0a4296d6/Editor/Mono/GUI/DockArea.cs:107)

I get t$$anonymous$$s error on both Web player and PC And Mac Standalone.

Источник

unity error building player because scripts had compiler errors

hello i been using unity pro for sometime now but i have never came across a error like t$$anonymous$$s. because of t$$anonymous$$s error i’m unable to build my game and finish it 🙁 please help from Ben

3 Ответов

Ответ от CHPedersen · 24/03/15 09:25

What t$$anonymous$$s is telling you is that you can’t use editor code in your builds. W$$anonymous$$ch, when you t$$anonymous$$nk about it, makes perfect sense. «UnityEditor» is the namespace for all the code that is executed in the Editor. It isn’t part of the engine («UnityEngine»).

Remove code from your game that uses components that are only available in the Editor. T$$anonymous$$s could be file dialogs, for example.

Ответ от jayant_vishwakarma · 18/10/16 06:41

it Seems that you are using package from asset store or any other place it happens because external packages contains demo scene you just need to delete all the script that are using UnityEditor just click on error message and unity will redirect you to the script look at the top of the script if there is statement like «using UnityEditor» delete that script and error will gone if it is not gone look there is another any script that contains «using UnityEditor» delete that.

Источник

Error building player because scripts при билде

Короче, стандартная проблема — при постройке билда консоль выдает ошибку Error building player because scripts had compiler errors. Лог ничего дельного не говорит (либо просто я слишком тупой и не понимаю, в каком скрипте ошибка). Ясно, что имеется в наличии проблемный скрипт/скрипты, а вот как их найти либо выявить, конечно же, неясно. Что я могу сделать?

Последний раз редактировалось JustOstrava 20 ноя 2017, 12:02, всего редактировалось 1 раз.

Не умеешь — так учись, в чем проблема-то? Вот не понимаешь — другое дело.

Аватара пользователя
JustOstrava
UNец
 
Сообщения: 25
Зарегистрирован: 29 янв 2016, 18:07
Откуда: Санкт-Петербург

Re: Error building player because scripts при билде

Сообщение Valentinus 19 ноя 2017, 21:42

JustOstrava писал(а): Что я могу сделать?

вариантов два:
1. сжечь второй том
2. показать всем лог

другое мое творчество: samlib.ru/u/us_w/

Аватара пользователя
Valentinus
Старожил
 
Сообщения: 889
Зарегистрирован: 24 мар 2017, 18:33

Re: Error building player because scripts при билде

Сообщение JustOstrava 20 ноя 2017, 12:02

Valentinus писал(а):

JustOstrava писал(а): Что я могу сделать?

вариантов два:
1. сжечь второй том
2. показать всем лог

Логи — это одно из тех вещей, в которых я не шарю (знаю, что с таким мозжечком далеко не уйду), да и к тому же больше 40к знаков здесь вперить нельзя. Поэтому получите запись лога после последней удачной компиляции библиотеки во время билда (если что-то не то сварганил, буду естессна исправлять)

Не умеешь — так учись, в чем проблема-то? Вот не понимаешь — другое дело.

Аватара пользователя
JustOstrava
UNец
 
Сообщения: 25
Зарегистрирован: 29 янв 2016, 18:07
Откуда: Санкт-Петербург

Re: Error building player because scripts при билде

Сообщение JustOstrava 21 ноя 2017, 09:56

Все, ошибка решена. Оказалось, что раз в где-то пять неудач консоль начинала ругаться красным значком на один скрипт, который я снес, и билд сразу пошел. Спасибо всем, кто хотя бы подумал, как можно помочь. (3A4OT)

Не умеешь — так учись, в чем проблема-то? Вот не понимаешь — другое дело.

Аватара пользователя
JustOstrava
UNец
 
Сообщения: 25
Зарегистрирован: 29 янв 2016, 18:07
Откуда: Санкт-Петербург


Вернуться в Общие вопросы

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

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 14



Здравствуйте!
Я, увы, новичок, но искренне надеялась, что первое самое простенькое приложение скомпилирую без проблем, но увы.
Установив самые новые SDK, JDK, настроив самое простое приложение (отображение объекта на поверхности — 1 объект (анимашка FBX) — один TargetImage — одна ARCamera.

При компиляции выдает вот такие ошибки:
UnityEditor.BuildPlayerWindow+BuildMethodException : 3 errors
at UnityEditor.BuildPlayerWindow+DefaultBuildMethods. BuildPlayer (BuildPlayerOptions options) [0x0021f] in C:buildslaveunitybuildEditorMonoBuildPlayerW indowBuildMethods.cs:187
at UnityEditor.BuildPlayerWindow.CallBuildMethods (Boolean askForBuildLocation, BuildOptions defaultBuildOptions) [0x0007f] in C:buildslaveunitybuildEditorMonoBuildPlayerW indowBuildMethods.cs:94
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

Скриншот сцены и ошибок прикрепила.

Пожалуйста, помогите мне.

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь


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!

Понравилась статья? Поделить с друзьями:
  • Error building embree static ray caster committing scene failed
  • Error building driver info list fail error code 0x3
  • Error building certification path for the target
  • Error building asn 1 representation can t build oid for variable
  • Error build identity info does not contain a macosvariant