简体   繁体   English

错误帮助-UnityException:声明变量时不允许调用此函数

[英]Error Help - UnityException: You are not allowed to call this function when declaring a variable

I'm getting the following runtime error... 我收到以下运行时错误...

"UnityException: You are not allowed to call this function when declaring a variable. Move it to the line after without a variable declaration. If you are using C# don't use this function in the constructor or field initializers, Instead move initialization to the Awake or Start function." “ UnityException:在声明变量时不允许调用此函数。在不声明变量的情况下,将其移至该行。如果使用的是C#,请不要在构造函数或字段初始化程序中使用此函数,而是将初始化移至唤醒或启动功能。”

The stack trace: 堆栈跟踪:

UnityEngine.GameObject..ctor () (at C:/buildslave/unity/build/artifacts/generated/common/runtime/UnityEngineGameObje‌​ctBindings.gen.cs:419)
BallManager..ctor ()
ArcadeBallManager..ctor ()
UnityEngine.GameObject:AddComponent()
BasicGame:Start() (at Assets/BasicGame.cs:106)

This seems to happen in a script where I use exampleObject.AddComponent<aType>() or exampleObject.GetComponent<aType>() . 这似乎发生在我使用exampleObject.AddComponent<aType>()exampleObject.GetComponent<aType>() exampleObject.AddComponent<aType>()的脚本中。

I have tried many ways of resolving this, starting with moving the lines of code to Awake() and Start Functions() (as suggested in the error log). 我尝试了多种方法来解决此问题,首先将代码行移至Awake()和Start Functions()(如错误日志中所建议)。

I have tried declaring the variable locally, globally, with different access modifiers and in addition I have played around with immediate vs delayed assignment after declaration. 我尝试使用不同的访问修饰符在本地,全局,全局声明该变量,此外,在声明后我尝试了立即赋值与延迟赋值。

I have also tried a variety of other "fixes" found on other posts ranging from restarting Unity to recreating the script etc. 我还尝试了在其他帖子上找到的各种其他“修复”,从重启Unity到重新创建脚本等。

I'm at the point where I'm wondering if I'm suffering from some kind of fundamental knowledge gap relating to this. 我正想知道自己是否正在遭受与此相关的某种基本知识鸿沟。

I'm not looking for a code fix here, I'm looking to understand what is going on so if anyone understands this error, can they shed some light on it please. 我不是在这里寻找代码修复程序,而是想了解正在发生的事情,因此,如果有人理解此错误,可以请他们提供一些帮助。

Additional details that could be important... I'm trying to choose a management system dynamically based on game type eg classicManager, specialManager, baseManager. 可能很重要的其他详细信息...我试图根据游戏类型(例如classicManager,specialManager,baseManager)动态选择管理系统。 The management classes share a base class. 管理类共享基类。 I'm going for polymorphism to address the base class... See below for pseudo example 我要进行多态处理以解决基类问题……请参见下面的伪示例

if(gameType == specialManager)
{
   manager = exampleObj.AddComponent<ClassicManager>() as baseManager;
} 

Any help would be greatly appreciated. 任何帮助将不胜感激。

New Code For Arx Added. 添加了新的Arx代码。

using UnityEngine;
using System.Collections;
using System;

public class BasicGame : MonoBehaviour {

    public GameObject ball_manager_obj;
    //public BallManager ball_manager_script;// = BallManager();
    // Can Be : "NumBallClasic"  or "NumballArcade" etc.

    //TEST...

    public ArcadeBallManager arcd;
    public ClassicNumBallManager clsc;


    //...TEST END

    public string game_type = "Arcade";

    public int seconds_left;
    public int minutes_left;

    public int game_length_mins = 2;

    public string game_time_string = "";

    public bool game_over = false;
    public bool game_paused = false;

    public int score = 0;

    public float ball_interval_min = 0.2f;
    public float ball_interval_max = 0.6f;
    public float ball_interval = 0.5f;

    public float ball_check_interval = 0.1f;


    public Camera the_cam;

    public GameObject wall_container;
    public WallScript wall_script;

    public GameObject end_zone_container;
    public EndZoneScript end_zone_script;

    public Color lerp_colour_a = Color.white;
    public Color lerp_colour_b = new Color(0.2f,0.6f,0.8f,1.0f);
    public Color intended_colour = Color.white;
    public Color prev_colour = Color.white;

    public bool is_set_up = false;
    // Use this for initialization
    void Start() 
    {

        the_cam = GameObject.Find ("Main Camera").GetComponent<Camera> ();
        the_cam.backgroundColor = intended_colour;
        //this.gameObject.transform.localScale = (new Vector3(the_cam.rect.width, the_cam.rect.height,0));

        ball_manager_obj = new GameObject ();
        ball_manager_obj.transform.SetParent (this.gameObject.transform);
        ball_manager_obj.name = "BallManagerObj";

        wall_container = new GameObject ();
        wall_container.name = "WallContainer";
        wall_container.transform.SetParent (this.gameObject.transform);
        wall_container.AddComponent<WallScript>();
        wall_script = wall_container.GetComponent<WallScript> ();
        wall_script.createWalls ();

        end_zone_container = new GameObject ();
        end_zone_container.name = "EndZoneContainer";
        end_zone_container.transform.SetParent (this.gameObject.transform);
        end_zone_container.AddComponent<EndZoneScript> ();
        end_zone_script = end_zone_container.GetComponent<EndZoneScript> ();
        end_zone_script.createEndZone ();

        setGameType (game_type); //<<<<--TO BE SET SET VIA USER Eventually

        //chooseBallManager(ball_manager_obj, ball_manager_script);

        if(game_type == "NumBallClasic")
        {

            seconds_left = 0;
            minutes_left = game_length_mins;
            game_time_string = ("" + game_length_mins + ":00");

            BallManager ball_manager_script =      ((BallManager)ball_manager_obj.AddComponent<ClassicNumBallManager>());
            //return b_man;

        }
        if(game_type == "Arcade")
        {

            seconds_left = 0;
            minutes_left = game_length_mins;
            game_time_string = ("" + game_length_mins + ":00");

            if(ball_manager_obj != null)
            {

                BallManager ball_manager_script = (BallManager)ball_manager_obj.gameObject.AddComponent<ArcadeBallManager>();
            }
            else
            {
                ball_manager_obj = new GameObject ();
                BallManager ball_manager_script = (BallManager)ball_manager_obj.gameObject.AddComponent<ArcadeBallManager>();
                //ball_manager_script =  ball_manager_obj.GetComponent<ArcadeBallManager>();
            }


            //ArcadeBallManager nu_b_man = new ArcadeBallManager();
            //BallManager b_man = nu_b_man as BallManager;

            //return b_man;

        }
        else
        {
            seconds_left = 0;
            minutes_left = game_length_mins;

            game_time_string = ("" + game_length_mins + ":00");

            BallManager ball_manager_script =  ((BallManager)ball_manager_obj.AddComponent<ArcadeBallManager>());

            //BallManager b_man = new ArcadeBallManager() as BallManager;
            //return b_man;

        }


    }

New Code Added For 31eee384: (Note, class hardly touched - get sprite simply returns a new sprite for testing purposes atm) 为31eee384添加了新代码:(注意,几乎没有碰过类-get sprite只是返回了一个用于测试atm的新sprite)

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class ArcadeBallManager : BallManager {


    // Use this for initialization
    void Start () 
    {


    }

    // Update is called once per frame
    void Update () 
    {


    }


    public override Sprite getActiveSprite (string b_type)
    {
        //SendActiveSprite
        Sprite spr = new Sprite();

        return spr;
    }
}

In Short... 简而言之...

CHECK, CHECK AND CHECK AGAIN! 再次检查,检查!

If you haven't found the problem, repeat the above step. 如果尚未发现问题,请重复上述步骤。

The problem was as 31eee384 pointed out... Burried deep in my base class there was a line that read something like: 问题是31eee384指出的...在我的基类中深深埋藏着一行,内容如下:

GameObject obj = new GameObject();

To fix this error was simply a matter of initialising the GameObject inside a function eg 要解决此错误,只需在功能内初始化GameObject即可,例如

GameObject obj;

...

public void aFunc()
{
    obj = new GameObject();
}

NOTE: The error reads "... Instead move initialization to the Awake or Start function." 注意:错误显示为“ ...而是将初始化转移到唤醒或启动功能。” - this was NOT working IN THIS PARTICULAR CASE. -在这种特殊情况下,此方法无效。 continue reading to find out more. 继续阅读以了解更多信息。

Although the correct and basic answer is as above, I shall explain the circumstances that led me to this frustratingly simple error incase anyone else has made the same mistake... 尽管正确和基本的答案如上所述,但是我将解释在其他任何人犯了相同错误的情况下导致我遇到这个令人沮丧的简单错误的情况。

Way earlier, I had run into a null reference error stemming from code similar to the above. 早些时候,我遇到了一个空引用错误,该错误源于与上述类似的代码。 I was originally initialising the GameObject in the Start() function and could not figure out why I was receiving the null reference exception. 我最初是在Start()函数中初始化GameObject的,无法弄清楚为什么我收到了null引用异常。 As a work around I initialised the GameObject just outside the function I was using it in as follows (and as mentioned at the top)... 作为一种解决方法,我将GameObject初始化为在我正在使用的函数外部,如下所示(并在顶部提到)...

GameObject obj = new GameObject();

This line became berried in my code and forgotten about, as the fix seemed to work until I ran into the "...You are not allowed to call this function when declaring a variable" error. 这行代码在我的代码中被遗忘并被遗忘,因为此修复程序似乎一直有效,直到我遇到“ ...在声明变量时不允许调用此函数”错误。

The simple null reference error & the problem with "... Instead move initialization to the Awake or Start function." 简单的空引用错误以及“ ...而是将初始化移至Awake或Start函数”的问题。 ... ...

The Start() function was not firing in the base class because the class extending it was also using the Start() function. Start()函数没有在基类中触发,因为扩展它的类也使用Start()函数。 HEAD SLAP MOMENT 头拍瞬间

The complete fix: 完整修复:

1) Make sure you ONLY initialise Objects INSIDE a function. 1)确保仅在函数内部初始化对象。

2) Ensure the function you initialise with actually runs in the base class. 2)确保初始化时使用的函数实际上在基类中运行。

In my case I changed the name of the Start() function in the base class to InitBase(). 就我而言,我将基类中Start()函数的名称更改为InitBase()。 I then called this from the extended class. 然后,我从扩展类中调用此方法。

Hope this helps :) 希望这可以帮助 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 UnityException:不允许调用此函数 - UnityException: Not allowed to call this function UnityException:不允许从 MonoBehaviour 构造函数调用 GetActiveScene - UnityException: GetActiveScene is not allowed to be called from a MonoBehaviour constructor 以编程方式声明变量时,“必须声明标量变量”错误 - “Must Declare the Scalar Variable” error when programatically declaring variables C# 帮助声明变量我将其初始化为 - C# help declaring variable i initialize it to UnityException:不允许从 MonoBehaviour 构造函数调用 get_time - UnityException: get_time is not allowed to be called from MonoBehaviour constructor 为什么在任何成员变量(即调用函数/属性)之前允许'@'不影响其值? - Why is '@' allowed before any member variable (i.e. call to a function/Property) when it doesn't affects its value? 声明变量时的性能问题 - Performance issues when declaring variable 在.Net中的函数/方法中声明和处置局部变量 - Declaring and disposing a local variable in a function/method in .Net 使用VS13在C#中声明变量时出现奇怪的错误 - Strange error when declaring a variable in C# using VS13 在 razor 页面中声明可为空的变量会产生错误 - Declaring a nullable variable in a razor page produces error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM