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 Daniel G · Nov 27, 2013 at 03:06 AM · c#nullanother scriptsimple fix

How to know if a Script exists on another game object? C#

Hello,

I am wanting to find if a script exists on any game objects that come into my sphere of force (Physics.OverlapSphere)...

I first Find ALL GAME OBJs in a sphere around me of 20.0f.. Then i am CHECKING if those objects FOUND can be USED to eventually be MOVED UP... This check is the "bool ObjectInteractable(GameObject obj)"

THEN If an obj Found is Deemed NOT WORTHY to be moved i.e. "its out side the camera view" "Occulled from the camera" "Or simply doesnt have a rigidbody"

if the obj is NOT deemed worthy I Return FALSE. Which means that Obj Does NOT get to move!...

MY ISSUE: I want to add ONE more Parameter, to my "See if this object is DEEMED WORTHY" I want to Find if it has a script called "InteractableScript" I CANT FIGURE OUT HOW TO DO THIS?? It keeps giving me the error that it cant find it, I KNOW it cant find it, thats why im checking!

CODE (C#):

     void StageOneLevetate() {
         Collider [] ObjsInSphere = Physics.OverlapSphere(transform.position, 20.0f);
         for(int i = 0; i < ObjsInSphere.Length; ++i) {
             GameObject gObject = ObjsInSphere[i].transform.gameObject;
             
             //For EACH Obj that is in view wich ones have a TRUE on their little script attached to them that i got from UNITY answers...
             if (ObjectInteractable(gObject) == false) continue;
             
             if (gObject.rigidbody.mass < 1.0f) {
                 gObject.rigidbody.velocity = Vector3.up * Random.Range(1.0f, 2.0f);
                 gObject.rigidbody.AddTorque(new Vector3(Random.Range(-0.02f, 0.02f), Random.Range(-0.02f, 0.02f), Random.Range(-0.02f, 0.02f)));    
             }
             else if (gObject.rigidbody.mass < 5.0f) {
                 gObject.rigidbody.velocity = Vector3.up * Random.Range(3.0f, 4.0f);
                 gObject.rigidbody.AddTorque(new Vector3(Random.Range(-0.01f, 0.01f), Random.Range(-0.01f, 0.01f), Random.Range(-0.01f, 0.01f)));
             }
             
         }
     }
 
     //THIS Will go inside EACH 
     bool ObjectInteractable(GameObject obj) {
         if (obj.rigidbody == null) return false;
         if (obj.GetComponent<InteractableScript>() == null) return false;
     
         // ignore objects not in the view frustum.
         if (GeometryUtility.TestPlanesAABB(GeometryUtility.CalculateFrustumPlanes(Camera.main), obj.collider.bounds) == false) {
             return false;
         }
         
         // ignore objects that are occluded from our view.
         RaycastHit hit;
         if(Physics.Linecast(transform.position, obj.transform.position, out hit)) {
             if (hit.transform != obj.transform) return false;    
         }
         
         return true;
     }



Thanks so much for ANY help!! Daniel

I take the time to rate and accept good answers!

Comment
Add comment · Show 5
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 Daniel G · Nov 27, 2013 at 04:10 AM 0
Share

Any Ideas?

avatar image Huacanacha · Nov 27, 2013 at 05:38 AM 1
Share

A side note: you may want to cache your GetComponent checks for performance reasons, as I assume this code is run from FixedUpdate() and it can clearly return multiple objects to check each time.

Assu$$anonymous$$g you don't dynamically add or remove InteractableScript from objects you can store the GetComponent results in a Dictionary... then if it an object exists in the Dictionary check the bool, if it doesn't call GetComponent and store the result.

avatar image Tomer-Barkan · Nov 27, 2013 at 02:21 PM 1
Share

Finding a component given a specific gameobject is not that much of a problem, especially since in advance you limit the number of searches to only the objects around the player, and only those that have a collider.

I'd call this premature optimization and keep the code simple rather than add a dictionary which will take up memory. If and only if you have some performance issues, I'd try to disable the GetComponent and see if it actually helps performance at all, and only if it does bother with creating a dictionary. $$anonymous$$y guess would be that it won't.

avatar image Daniel G · Nov 27, 2013 at 03:42 PM 0
Share

Thank you @tbkn your so right! UpRate my question if you like it :D Thanks

avatar image Huacanacha · Nov 27, 2013 at 06:56 PM 0
Share

Right, I actually agree... what I meant to say was "if" you find this to be a performance issue you should consider caching the results. $$anonymous$$eeping it simple is a much better idea if it's not a noticeable drain on performance.

3 Replies

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

Answer by Daniel G · Nov 27, 2013 at 03:41 PM

My error was this... It was looking for a "TYPE" of script with the and no "" But all i wanted was to look for a NAME of a script...

Which is below using ("THE NAME OF THE SCRIPT")...

 if (obj.GetComponent("InteractableScript") == null) return false;



Thanks for all the help!! Daniel

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
5

Answer by Moor · Nov 27, 2013 at 04:30 AM

just this is enough

  if (obj.GetComponent<InteractableScript>) return false;
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 Daniel G · Nov 27, 2013 at 03:39 PM 0
Share

It needed to be this, Close though thanks!!

 if (obj.GetComponent("InteractableScript") == null) return false;
avatar image flaviusxvii · Nov 27, 2013 at 09:10 PM 0
Share

This:

 obj.GetComponent<InteractableScript>()

is much preferred over

 obj.GetComponent("InteractableScript")

For various reasons. Speed is one of them.

avatar image
1

Answer by Tomer-Barkan · Nov 27, 2013 at 06:23 AM

You use GetComponent to get the InteractableScript script from the object. If it doesn't exist, it returns null. So you check whether it returns null or not. If it does, then the object is not interactive. Otherwise it is. See your updated code (only changed the last return statement):

 bool ObjectInteractable(GameObject obj) {
    if (obj.rigidbody == null) return false;
    if (obj.GetComponent<InteractableScript>() == null) return false;
 
    // ignore objects not in the view frustum.
    if (GeometryUtility.TestPlanesAABB(GeometryUtility.CalculateFrustumPlanes(Camera.main), obj.collider.bounds) == false) {
      return false;
    }
 
    // ignore objects that are occluded from our view.
    RaycastHit hit;
    if(Physics.Linecast(transform.position, obj.transform.position, out hit)) {
      if (hit.transform != obj.transform) return false;    
    }

    // return true if object has InteractableScript, otherwise return false
    return (obj.GetComponent<InteractableScript>() != null);
 }


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

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

19 People are following this question.

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

Related Questions

Multiple Cars not working 1 Answer

Have null errors 1 Answer

Distribute terrain in zones 3 Answers

XMLDocument GetElementByID returning null 1 Answer

Confused as to why I'm getting a NullReference Exception 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