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

I have a simple class…

using UnityEngine;
using System.Collections;

public class FactionData : MonoBehaviour {
	
	public string[] Flag = new string[5];
}

I drag that class onto a game object named “FactionDataGO”

In another class I need to use this class so I do this…

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

public class Globals : MonoBehaviour {

	public static FactionData gFactionData;
	
	void Start () 
	{
			
		camMainCamera.farClipPlane = 1000.0f;	
		
		//set up which faction gets which flag
		[B]gFactionData = new FactionData();[/B] //<--Unity hates this line
		gFactionData.Flag[0] = "none";	
		gFactionData.Flag[1] = "USA"
		gFactionData.Flag[2] = "Russia"
		gFactionData.Flag[3] = "SomeCountryName1"	
		gFactionData.Flag[4] = "SomeCountryName2"
	}
}

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.

1 Like

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()” to get it instead of “new FactionData();”

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

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.

7 Likes

man, you solved that in minutes. I’d been wrestling with that (on and off) since yesterday morning. thanks man :smile:

ya know what is weird, this line of code works in that same class…

public static List<Piece> gPiece = new List<Piece>();

It uses the “new’ keyword and Unity doesn’t complain and the class 'piece” does inherite MonoBehavior. maybe the has something to do with it, dunno, but thanks, its working as you described.

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.

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.

Not to be rude, but I suggest you learn basic C# programming before continuing your Unity adventures.

2 Likes

Thanks for the tips.
I’m learning how to program as well and was struggling with the same problem.

Hi! Hi had the same error message! The solution is on yout FactionData class, dont inherance from Monobehaviour, delete it:

using UnityEngine;
using System.Collections;

// Old code
// public class FactionData : MonoBehaviour {
// new code
public class FactionData {
   
    public string[] Flag = new string[5];
}

regrets

2 Likes

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.

5 Likes

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.

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.

5 Likes

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.

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:

GameObject gameObject = new GameObject();
T instance  = gameObject.AddComponent<T>();

where T is the MonoBehavior class you need to create an instance of.

1 Like

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

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/assets-mouselook-cs-29-62-error-cs1003-syntax-error-expected.1039702/#post-6730855

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

How to use code tags: https://discussions.unity.com/t/481379

1 Like