user3380292
user3380292

Reputation:

Declaring a new instance of a class in C#

Unity is not liking this and upon research and a warning from unity

("You are trying to create a MonoBehavior using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively your script can inherit from ScriptableObject or no base class at all.)

I know of AddComponent, but I don't quite think that's what I want.

public Boids boids = new Boids();

Boids is my 2nd class. I saw this work on a tutorial, so I'm kind of confused on why this doesn't work in Monodevelop.

Upvotes: 0

Views: 4763

Answers (2)

pek
pek

Reputation: 18035

If I understand you correctly, you need your AI script to get all the Boid instances in the scene and do something with them.

If this is the case, then there are multiple ways of doing this, a simple way would be:

  1. Have a public Boids[] boids field declared in your AI script
  2. Create a single game object and add your AI script
  3. Create a bunch of game objects and add the Boids script to them in the Unity editor
  4. Select the game object that contains your AI script. You should see a boids field in the inspector. Drag and drop all your Boid game objects to that field
  5. You can now access all the linked Boids in your AI script

Here is some example scripts:

public class AI : MonoBehaviour
{
    public Boid[] boids;

    void Update()
    {
        foreach (Boid boid in this.boids)
        {
            // Do something with boid
        }
    }
}

public class Boid : MonoBehaviour
{
    public float searchRadius;
    // Anything else
}

Upvotes: 0

Mick
Mick

Reputation: 6864

Pretty easy to google...

http://forum.unity3d.com/threads/119537-You-are-trying-to-create-a-MonoBehaviour-using-the-new-keyword

It's to do with what Boids inherits. New is apparently not the correct way to instantiate the object, it should be instatiated using the unity framework

gameObject.AddComponent<Boids>()

Upvotes: 1

Related Questions