Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only.

    Please, do not make any changes to your username or email addresses at id.unity.com during this transition time.

    It's still possible to reply to existing private message conversations during the migration, but any new replies you post will be missing after the main migration is complete. We'll do our best to migrate these messages in a follow-up step.

    On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live.


    Read our full announcement for more information and let us know if you have any questions.

You are trying to create a MonoBehaviour using the 'new' keyword.

Discussion in 'Scripting' started by roto23, Jan 15, 2012.

  1. roto23

    roto23

    Joined:
    Oct 30, 2009
    Posts:
    240
    I have a simple class...
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class FactionData : MonoBehaviour {
    6.    
    7.     public string[] Flag = new string[5];
    8. }
    9.  
    I drag that class onto a game object named "FactionDataGO"

    In another class I need to use this class so I do this...
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. using System.Collections.Generic;
    5.  
    6. public class Globals : MonoBehaviour {
    7.  
    8.     public static FactionData gFactionData;
    9.    
    10.     void Start ()
    11.     {
    12.            
    13.         camMainCamera.farClipPlane = 1000.0f;  
    14.        
    15.         //set up which faction gets which flag
    16.         [B]gFactionData = new FactionData();[/B] //<--Unity hates this line
    17.         gFactionData.Flag[0] = "none"; 
    18.         gFactionData.Flag[1] = "USA"
    19.         gFactionData.Flag[2] = "Russia"
    20.         gFactionData.Flag[3] = "SomeCountryName1"  
    21.         gFactionData.Flag[4] = "SomeCountryName2"
    22.     }
    23. }
    24.  
    And I get that error msg...
    "You are trying to create a MonoBehaviour using the 'new' keyword. " I want to inherit : Monobehavior" so I can't use "ScriptableObject". BTW, the code works, just getting that warning. But when I write more complicated scripts, it will probably cause problems, so if i can solve this now, it would be better.
     
    hopetolive likes this.
  2. fholm

    fholm

    Joined:
    Aug 20, 2011
    Posts:
    2,052
    You can't (or shouldn't) instantiate classes that inherit from MonoBehaviour yourself. Either you remove the ": MonoBehaviour" part of the first FactionData type definition or you attach a copy of it to the same object as Globals is attached to and then do "gameObject.GetComponent<FactionData>()" to get it instead of "new FactionData();"

    Edit #1: Or you can also (if you want) replace "new FactionData();" with this:

    Code (csharp):
    1. gFactionData = gameObject.AddComponent<FactionData>();
    Edit #2: Looking over your code again, I can't see a reason for you to inherit the FactionData class from anything. The most clean approach is to just remove the inheritance to MonoBehaviour.
     
    Last edited: Jan 15, 2012
  3. roto23

    roto23

    Joined:
    Oct 30, 2009
    Posts:
    240
    man, you solved that in minutes. I'd been wrestling with that (on and off) since yesterday morning. thanks man :D

    ya know what is weird, this line of code works in that same class..
    Code (csharp):
    1.  
    2. public static List<Piece> gPiece = new List<Piece>();
    3.  
    It uses the "new' keyword and Unity doesn't complain and the class 'piece" does inherite MonoBehavior. maybe the <List> has something to do with it, dunno, but thanks, its working as you described.
     
    Last edited: Jan 15, 2012
  4. roto23

    roto23

    Joined:
    Oct 30, 2009
    Posts:
    240
    I cut a lot out for simplicity and it will grow, still possible I won't need to inherite monobehavior but this was fundamental to other scripts I will need to write down the road.
     
  5. npsf3000

    npsf3000

    Joined:
    Sep 19, 2010
    Posts:
    3,830
    That's because you're creating a new list [that just happens to contain references to Piece]. I suggest spending some free time on your fundamentals.
     
  6. fholm

    fholm

    Joined:
    Aug 20, 2011
    Posts:
    2,052
    Not to be rude, but I suggest you learn basic C# programming before continuing your Unity adventures.
     
    ZO5KmUG6R and loki-of-mute like this.
  7. Korsferd

    Korsferd

    Joined:
    Apr 15, 2015
    Posts:
    1
    Thanks for the tips.
    I'm learning how to program as well and was struggling with the same problem.
     
  8. LargeVader

    LargeVader

    Joined:
    Jan 29, 2016
    Posts:
    1
    Hi! Hi had the same error message! The solution is on yout FactionData class, dont inherance from Monobehaviour, delete it:


    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. // Old code
    6. // public class FactionData : MonoBehaviour {
    7. // new code
    8. public class FactionData {
    9.    
    10.     public string[] Flag = new string[5];
    11. }
    12.  

    regrets
     
  9. batpox

    batpox

    Joined:
    Sep 15, 2015
    Posts:
    6
    If you are new to Unity/C#, you might think you need to inherit MonoBehavior to get access to useful methods, such as Instantiate. However, many of the methods that you would get by 'being' a MonoBehavior object, are also available as static classes (for example GameObject.Instantiate). This is the generally the better approach for classes that you write yourself that are not things like gameObjects (for example, they might be support classes such as data manipulation, arithmetic helper functions, networking, etc.)

    When you inherit from MonoBehaviour you bring in a *lot* of complexity that you might not need or want. Check out the Unity documentation for the MonoBehaviour.
     
  10. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,778
    I know you're trying to help, but this post is five years old, with the last reply well over a year ago.... plus the question was already answered.
     
  11. Gatecrasher53

    Gatecrasher53

    Joined:
    Dec 23, 2017
    Posts:
    1
    Totally disagree. I just stumbled upon this thread and batpox's comment helped me with a similar problem to OPs.

    This isn't Stack Overflow.
     
  12. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    21,937
    It's totally dependent on the contents of the thread. If the contents of the thread are completely out of date then the thread will often be closed immediately after it has been resurrected.
     
  13. rmadsen

    rmadsen

    Joined:
    Jan 3, 2013
    Posts:
    3
    Much thanks to fholm for this solution.

    gFactionData = gameObject.AddComponent<FactionData>();


    This works well if your MonoBehavior is attached in the scene. I have a case where I want to use a MonoBehavior class without requiring that it be added to any scene. A more general solution in that case is:

    Code (CSharp):
    1. GameObject gameObject = new GameObject();
    2. T instance  = gameObject.AddComponent<T>();
    where T is the MonoBehavior class you need to create an instance of.
     
    Dragmine149 likes this.
  14. PSEntertainment

    PSEntertainment

    Joined:
    Jan 14, 2021
    Posts:
    3
    Hello, I'm troubling with the same problems as mentioned above. Please take a closer look to code as follow:
    public void ConfirmGameOver()
    {
    AdManager.instance.ShowFullScreenAd(); here the error of mono behaviour pops up but why?
    //activated when replay button is hit
    OnGameOverConfirmed(); //event is sent to TapController
    scoreText.text = "0";
    SetPageState(PageState.Start);
    AdManager.instance.HideBanner();
    }

    public void StartGame()
    {
    //activated when play button is hit
    SetPageState(PageState.Countdown);
    TapController.Instance.StartScript(); //needs to start player after play
    AdManager.instance.RequestBanner();

    Second error exist to my AdManager Script:

    public void RequestFullScreenAd()
    {
    this.fullScreenAd = new InterstitialAd(fullScreenAdID);

    this.fullScreenAd.OnAdLoaded += this.HandleOnAdLoaded;
    // called when an ad request failed to load
    this.fullScreenAd.OnAdFailedToLoad += this.HandleOnAdFailedToLoad;
    // called when an ad is clicked
    this.fullScreenAd.OnAdOpening += this.HandleOnAdOpened;
    // called when the user returned from the app after an ad click
    this.fullScreenAd.OnAdClosed += this.HandleOnAdClosed;
    // called when the ad click caused the user to leave the application
    this.fullScreenAd.OnAdLeavingApplication += this.HandleOnAdLeavingApplication;


    AdRequest request = new AdRequest.Builder().Build();
    this.fullScreenAd.LoadAd(request);
    }


    public void ShowInterstitial()
    {
    if (this.fullScreenAd.IsLoaded())
    {
    this.fullScreenAd.Show();
    }
    else
    {
    Debug.Log("Ad not loaded");
    }
    }

    //events below
    public void HandleOnAdLoaded(object sender, EventArgs args)
    {
    // do this when ad loads
    Debug.Log("Ad Loaed");
    }

    public void HandleOnAdFailedToLoad(object sender, EventArgs args)
    {
    // do this when ad fails to load
    Debug.Log("couldn't load ad");

    }

    public void HandleOnAdOpened(object sender, EventArgs args)
    {
    // do this when ad is opened
    MonoBehaviour.print("HandleAdOpened event received");
    }

    public void HandleOnAdClosed(object sender, EventArgs args)
    {
    // do this when ad is closed
    Debug.Log("Ad Closed");
    RequestFullScreenAd(); // Optional: in case you want to load another interstitial ad rightaway
    }

    public void HandleOnAdLeavingApplication(object sender, EventArgs args)
    {
    //do this when on leaving Application
    MonoBehaviour.print("HandleOnAdLeavingApplication event received");
    }

    public void ShowFullScreenAd()
    {
    if (fullScreenAd.IsLoaded())
    {
    fullScreenAd.Show();
    }
    else

    Im glad to hear from you guys. Please support. Thanks in advance
     
  15. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    39,571
    Please do not reply to 9-year-old threads. Make a new post... it's FREE and it is the forum rules.

    When you post, how to report your problem productively in the Unity3D forums:

    http://plbm.com/?p=220

    How to understand errors in general:

    https://forum.unity.com/threads/ass...3-syntax-error-expected.1039702/#post-6730855

    If you post a code snippet, ALWAYS USE CODE TAGS:

    How to use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/
     
    Bunny83 likes this.