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
1
Question by Josmun · May 31, 2012 at 10:46 AM · methodaccessingmono-behaviour

How can i use the method of a non monobehaviour class in my normal scripts.

I'm trying to call a method from an utility class, but can't get to solve all the errors notified by Unity.

My objective right now is to select gameobjects by clicking on them (working fine now) thanks to apply a code to each objects i want to be able to select and an use of raycast on the camera.

Now i creataed an utility class that i want to call for retrieve a table of all the selected game objects.

Utility class code :

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 public class Utilitaires
 {
     // Use this for initialization
     public GameObject[] FindSelectedObjects()
     {
         GameObject[] gameObjects = (GameObject[]) MonoBehaviour.FindObjectsOfType(typeof(GameObject));
         List<GameObject> selectedGameObjects = new List<GameObject>();
         GameObject[] bl = null;
         for (int i = 0; i < gameObjects.Length; i++)
         {
             variables o = gameObjects[i].GetComponent("variables") as variables;
             if (o != null)
             {
                 if (o.isSelected())
                 {
                     selectedGameObjects.Add(gameObjects[i]);
                 }
             }
         }
 
         if (selectedGameObjects.ToArray().Length == 0) { return (GameObject[])bl.Clone(); } else { return (GameObject[])selectedGameObjects.ToArray().Clone(); }
     }
 }

My code accessing to the utility class :

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 public class Blabla : MonoBehaviour {
     
     public GameObject[] selectedObjects;
     public Utilitaires utilitaire;
     
     void Update()
     {
         selectedObjects = utilitaire.FindSelectedObjects();
     }
 }

The only error notified by unity right now is at selectedObjects = utilitaire.FindSelectedObjects(); telling :

NullReferenceException: Object reference not set to an instance of an object Blabla.Update () (at Assets/Blabla.cs:12)

does anyone have an idea of what's going on ?

Comment
Add comment
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

3 Replies

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

Answer by Bunny83 · May 31, 2012 at 11:55 AM

Utility classes usually contains just static functions. Usually you don't need / want an instance of such a class (note i said usually, there are always situations where it's different ;) ).

Almost all Unity provided functions are also static functions in Utility classes. You never create an instance of GUI, Mathf, Input, Network, Physics, ...

So just declare it like this:

 public class Utilitaires
 {
     public static GameObject[] FindSelectedObjects()
     {
         //...

And use it like this:

 Utilitaires.FindSelectedObjects()

If the class should only contain static stuff, make it a static class so you can't forget to make all your functions static:

 public static class Utilitaires
 {
     // Only static members allowed.
 }
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 Josmun · May 31, 2012 at 04:40 PM 0
Share

I learned something about static, thanks. You just made me upgrade one level in programmation. Thanks !

avatar image
4

Answer by whydoidoit · May 31, 2012 at 10:52 AM

Well you need to create an instance of your utility class:

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 public class Blabla : MonoBehaviour {
 
     public GameObject[] selectedObjects;
     public Utilitaires utilitaire  = new Utilitaires();
 
     void Update()
     {
         selectedObjects = utilitaire.FindSelectedObjects();
     }
 }
Comment
Add comment · Show 2 · 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 Josmun · May 31, 2012 at 11:44 AM 0
Share

Thanks a lot, that did it completely.

Sorry i'm more used to Javascript usually.

avatar image fashrista · Jun 21, 2018 at 12:43 PM 0
Share

I have been creating new instances of my non-monobehaviour classes and using different constructors in those classes. Is this ok. Do I understand the rules correctly :

You may not use constructors in classes that inherit from monobehaviour (there you should use Start() and Awake()) . But in classes that do not inherit from monobehaviour you can use constructors of those classes by creating new instances / objects of them.

?? is this correct ??

avatar image
1

Answer by David_Munoz · Nov 06, 2015 at 01:45 PM

Actually @Josmun the best way to do this is not using the methods described above. You should use the ScriptableObject class for the utility classes, such as beans or libraries. If they are beans, you should also use Serializable to store and manage the data.

For your example, you should use:

  public class MyLibrary : ScriptableObject {
      
      public GameObject[] FindSelectedObjects(){
 //TODO your logic
 }
 
  }
 
 

Then if you need to use that function, you should create an instance of your class NOT USING the "new" keyword, but using the CreateInstance function from the ScriptableObject class, and use this instance to access it:

 MyLibrary libraryObject = ScriptableObject.CreateInstance<MyLibrary>();
 GameObject[] selectedObjects= libraryObject.FindSelectedObjects();

For more information about ScriptableObjects, please refer to:

http://unity3d.com/es/learn/tutorials/modules/beginner/live-training-archive/scriptable-objects

[1]: http://unity3d.com/es/learn/tutorials/modules/beginner/live-training-archive/scriptable-objects

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 immeasurability · Oct 18, 2016 at 01:29 PM 0
Share

Best way! I was looking for! THX!!!

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

9 People are following this question.

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

Related Questions

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

Why are my MonoBehaviour methods not called? 1 Answer

Is it possible to change a variable, into a script not assigned to any game object? 3 Answers

A Question about GetComponent() (when accessing scripts).... 2 Answers

Call Functions Across Scripts, Null Object Error 1 Answer


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