Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by maggot · Nov 20, 2011 at 07:33 PM · c#errormonobehaviournew

Error trying to createMonoBehaviour using the 'new' keyword in cSharp script

I'm trying to read a public float called shootForce contained in a monoBehaviour class called player001controls using a monoBehaviour script called missileControls with cSharp.

player001controls.cs (extract)

     private float pShootForce;

 public float shootForce // The force at which missiles travel in m/s
 {
     get
     {
         return pShootForce;
     }
     set
     {
         pShootForce = value;
     }

}

missileControls.cs (extract)

 player001controls missileControl = new player001controls();

This executes, but when I fire a missile I get this error :

You are trying to create a MonoBehaviour 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

UnityEngine.MonoBehaviour:.ctor() player001controls:.ctor() moveMissiles:FixedUpdate() (at Assets/Scripts/moveMissiles.cs:9) Removing the 'new' from player001controls missileControl = new player001controls(); gives the error

Assets/Scripts/moveMissiles.cs(9,60): error CS0119: Expression denotes a type', where a variable', value' or method group' was expected

I want to be able to access the float shootForce at runtime, read from player001controls (or any other script).

Comment
Add comment · Show 4
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Jessy · Nov 20, 2011 at 08:15 PM 0
Share

I don't see how what Unity tells you doesn't solve your problem. A $$anonymous$$onoBehaviour is something to be attached to a Game Object.

avatar image maggot · Nov 20, 2011 at 08:41 PM 0
Share

missileControls.cs is a script component added to my missile prefab player001controls.cs is a script component added to my player GameObject

avatar image Holon777 · Nov 20, 2011 at 08:54 PM 0
Share

I think you you make a prefab out of the player001controls and Instantiate it, you'll be good to go.

public GameObject player001PreFab; // set this with inspector

player001controls missileControl = Instantiate(player001PreFab, Vector3.zero, Quaternion.identity);

avatar image jahroy · Nov 20, 2011 at 08:56 PM 1
Share

One of the basic rules of Unity is that you don't use constructors with $$anonymous$$onoBehaviours. This means you don't use the "new" operator. You attach scripts to GameObjects and reference them with public variables or GetComponent.

That has got to be one of the most descriptive and helpful compiler messages you're ever going to see (Unity rocks)!

4 Replies

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by maggot · Nov 25, 2011 at 12:12 PM

OK, heres my solution (final)

Declaration :

 public class Bullet
 {
 
     private float _shootForce;
 
     public float shootForce
 {
     get
     {
         _shootForce = 1f;
         return _shootForce;
     }
     set
     {
         _shootForce = value;
     }
 }

}

Invocation :

     Bullet bullet = new Bullet();

Execution :

     rigidbody.velocity = transform.up * bullet.shootForce;    

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
1

Answer by Bunny83 · Nov 21, 2011 at 12:13 AM

To create an instance of a MonoBehaviour class at runtime you have to use AddComponent because all components can't exist on it's own. They always need to be attached to a GameObject. If you want to create a script instance on the same GameObject where this script is attached to just use:

 // C#
 gameObject.AddComponent<player001controls>();

Ohh a little sidenote: classnames always should start with a capital letter. It get's very very difficult to read code where you mix typenames with variable names. That are some basic programming conventions.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by Holon777 · Nov 20, 2011 at 11:36 PM

I think you you make a prefab out of the player001controls and Instantiate it, you'll be good to go.

public GameObject player001PreFab; // set this with inspector

player001controls missileControl;

GameObject gObj = Instantiate(player001PreFab, Vector3.zero, Quaternion.identity);

missileControl = (player001controls)gObj.GetComponent(typeof(player001controls));

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by jahroy · Nov 20, 2011 at 09:02 PM

I recommend that you start by reading this:

  • http://unity3d.com/support/documentation/ScriptReference/index.Accessing_Other_Game_Objects.html

The above link explains some of the basic concepts of how scripts interact in Unity.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image MythN7 · Sep 02, 2013 at 06:10 PM 0
Share

I read through all this and I am getting the same problem as the top, however I did read the help files. Heres a link to a tutorial in the unity lessons. And typing in their script word for word produces this same error. http://unity3d.com/learn/tutorials/modules/beginner/scripting/variable-scope-and-access-modifiers

right before start they declared private AnotherClass myOtherClass; right after the alpha = 29 in start they have declared myOtherClass = new AnotherClass();

so unless im missing something here, it looks like your telling people its so obvious and basic that we should already understand this. where the official you tube lesson from unity is producing this error in there lesson as the way to do it.

 using UnityEngine;
 using System.Collections;
 
 public class ScopeAndAccess$$anonymous$$odifiers : $$anonymous$$onoBehaviour
 {
     public int alpha = 5;
     
     
     private int beta = 0;
     private int gamma = 5;
     
     
     private AnotherClass myOtherClass;
     
     
     void Start ()
     {
         alpha = 29;
         
         myOtherClass = new AnotherClass();
         myOtherClass.Fruit$$anonymous$$achine(alpha, myOtherClass.apples);
     }
     
     
     void Example (int pens, int crayons)
     {
         int answer;
         answer = pens * crayons * alpha;
         Debug.Log(answer);
     }
     
     
     void Update ()
     {
         Debug.Log("Alpha is set to: " + alpha);
     }
 }
 
 
 using UnityEngine;
 using System.Collections;
 
 public class AnotherClass
 {
     public int apples;
     public int bananas;
     
     
     private int stapler;
     private int sellotape;
     
     
     public void Fruit$$anonymous$$achine (int a, int b)
     {
         int answer;
         answer = a + b;
         Debug.Log("Fruit total: " + answer);
     }
     
     
     private void OfficeSort (int a, int b)
     {
         int answer;
         answer = a + b;
         Debug.Log("Office Supplies total: " + answer);
     }
 }

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

7 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Windows Script error upon opening a new javascript behavior script. 4 Answers

CS8025 Parser error 2 Answers

unity script error 1 Answer

Unfixable Assets/Scripts/PlayerAttack.cs(30,15): error CS1525: Unexpected symbol `private' 1 Answer

Scene Audio Script Error 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges