• 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 Joram56 · May 19, 2018 at 09:37 AM · instances

How to make a script full of methods provide methods independently for a number of gameobjects?

@Eno-Khaon

I have a script (class) containing a lot of static methods such as "FollowObject", "IsGrounded" "InFieldOfView" etc that I want to call from many different gameobjects, like enemies and projectiles and such.

 public class Move : MonoBehaviour {
 
 
     public Transform playerTrans;
     
      
 
     private static Vector3 direction = Vector3.zero;
 
 
     public void Start()
     {
         playerTrans = GameObject.FindGameObjectWithTag("Player").transform;
     }
 
     public static bool ObjectInRange(Transform objectTrans, Transform fromTrans, float rangeCheck)
     {
         
 
         //Direction from object to player
         if (objectTrans)
             direction = objectTrans.position - fromTrans.position;
 
         if (direction.magnitude < rangeCheck)
         {
             return true;
         }
         else return false;
 
     }
 
     public static void FollowObject(Transform objectTransform, Transform myTransform, int followRangeFrom, int followRangeTo, float followSpeed, GameObject gameObject)
     {
 
         //If in range, my Transform move toward object
         if (direction.magnitude > followRangeTo && direction.magnitude < followRangeFrom)
         {
             
             //Look at the player (3f is the rotation speed)
             gameObject.transform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(direction), 2f * Time.deltaTime);
 
             //Move toward player
             gameObject.transform.position += myTransform.forward * followSpeed * Time.deltaTime;
         }
        
     }
 
     public static bool IsGrounded(Transform myTransform, float checkRange)
     {
         RaycastHit hitInfo1;
 
         if (Physics.Raycast(myTransform.position, Vector3.down, out hitInfo1, checkRange))
         {
             if (hitInfo1.collider.tag == "Ground")
             {
                 return true;
             }
         }
         return false;
     }
 
     public static bool InFieldOfView(Transform myTransform, Vector3 queryPoint, float fov)
     {
 
         Vector3 directionV = queryPoint - myTransform.position;
 
         float angle = Vector3.Angle(directionV, myTransform.forward);
 
         //Debug.Log("");
         
         if (angle < fov*0.5f)
         {
             return true;
         }
 
         return false;
     }
                 
 }

These methods work fine if only one gameobject calls a Move function, once many calls a Move function like "Follow", none of the objects behave as intended and I assume that they are all moving as if their direction to player(object) is averaged or something. How would I provide a new Move class to all gameobjects that uses it so that each gameobjects has its own Move variables (for example direction to an object (like player))?

Here is the Update function and some Move calls in the "Enemy" class, of which I would like to have many instances.

    private void Update()
     {
         
         Move.FollowObject(player.transform, transform, followRangeFrom, followRangeTo, moveSpeed, gameObject);
 
         if (Time.time > canAttackTime && Move.ObjectInRange(player.transform, transform, followRangeTo) == true)
         {
             Debug.Log("call melee attack");
             MeleeAttack();
         }
 
         if (attacking)
         {
             CheckAttackTime();
         }
 
 
     }
 
     public void MeleeAttack()
     {
         attacking = true;
         attackTrigger.enabled = true;
         attackTimer = attackCD;
         canAttackTime = Time.time + attackCD;
 
         
     }
     
     void CheckAttackTime()
     {
         if (attackTimer > 0)
             attackTimer -= Time.deltaTime;
         else
         {
             attacking = false;
             attackTrigger.enabled = false;
         }
     }

I tried "Move = new move" and things like this but it is not possible to call methods in "Move" from this "move".

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

1 Reply

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

Answer by ShadyProductions · May 19, 2018 at 02:24 PM

I think you are looking for 'Extension methods'

They work like so:

 public static class Extensions {
      public static bool IsGrounded(this GameObject gObj) {
            return true; // example
      }
 }

Then on any GameObject type you can now call IsGrounded.

Comment
Add comment · Show 3 · 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 Joram56 · May 19, 2018 at 02:31 PM 0
Share

In your IsGrounded function, is that format with "this" required or can I pass arguments without "this". Also, would I need to add a "using" parameter or a new "Extension" variable or something to the GameObject that wants to call IsGrounded? Because I tried it now and the function name (IsGrounded) in the gameobject says name does not exist in the current context.

avatar image Joram56 · May 19, 2018 at 02:34 PM 0
Share

It looks like this is the answer though, I am reading up about extension methods so should manage on my own further. Thanks!

avatar image Joram56 · May 19, 2018 at 02:53 PM 1
Share

Got it working, Extension $$anonymous$$ethods are extremely useful! Thanks for telling me about them.

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

81 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 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 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 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 avatar image avatar image avatar image avatar image avatar image

Related Questions

Keeping track of multiple instances of one prefab 3 Answers

Find all instances of a script in the scene? 1 Answer

NullReferenceException with a text array 1 Answer

How can I prevent a prefab script from affecting all instances when entering a collider? 1 Answer

Network.Instance doesn't instance updated TextMesh 0 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